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
c621fa50b5dada6e51e64286d7b3e3a01815721a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Arg.lean
a0ebb526c5460fc42601016b5ae0f6c1d0404882
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,124
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term namespace Lean.Elab.Term /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg where | stx (val : Syntax) | expr (val : Expr) deriving Inhabited /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg where ref : Syntax := Syntax.missing name : Name val : Arg deriving Inhabited /-- 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) : MetaM (Array NamedArg) := do if namedArgs.any (namedArg.name == ·.name) then throwError "argument '{namedArg.name}' was already set" return namedArgs.push namedArg partial def expandArgs (args : Array Syntax) : MetaM (Array NamedArg × Array Arg × Bool) := do let (args, ellipsis) := if args.isEmpty then (args, false) else if args.back.isOfKind ``Lean.Parser.Term.ellipsis then (args.pop, true) else (args, false) let (namedArgs, args) ← args.foldlM (init := (#[], #[])) fun (namedArgs, args) stx => do if stx.getKind == ``Lean.Parser.Term.namedArgument then -- trailing_tparser try ("(" >> ident >> " := ") >> termParser >> ")" let name := stx[1].getId.eraseMacroScopes let val := stx[3] let namedArgs ← addNamedArg namedArgs { ref := stx, name := name, val := Arg.stx val } return (namedArgs, args) else if stx.getKind == ``Lean.Parser.Term.ellipsis then throwErrorAt stx "unexpected '..'" else return (namedArgs, args.push $ Arg.stx stx) return (namedArgs, args, ellipsis) def expandApp (stx : Syntax) : MetaM (Syntax × Array NamedArg × Array Arg × Bool) := do let (namedArgs, args, ellipsis) ← expandArgs stx[1].getArgs return (stx[0], namedArgs, args, ellipsis) end Lean.Elab.Term
f77b2292edf8642ff7a79c690865794d9156522c
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/rewrite.lean
df6c18a1882cdcf590b9d14e408ac1d38fa8018d
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
1,407
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rewrite import data.nat.basic open tactic example : ∀ x y z a b c : ℕ, true := begin intros, have : x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc ← mk_mapp ``add_monoid.add_assoc [`(ℕ),none], (l,p) ← assoc_rewrite_intl assoc this tgt, note `h none p ), erw h, guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end example : ∀ x y z a b c : ℕ, true := begin intros, have : ∀ y, x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc_rewrite_target this ), guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end variables x y z a b c : ℕ variables h₀ : ∀ (y : ℕ), x + (y + z) = 3 + y variables h₁ : a + (b + x) + y + (z + b + a) ≤ 0 variables h₂ : y + b + c = y + b + a include h₀ h₁ h₂ example : a + (b + x) + y + (z + b + c) ≤ 0 := by { assoc_rw [h₀,h₂] at *, guard_hyp _inst := is_associative ℕ has_add.add, -- keep a local instance of is_associative to cache -- type class queries exact h₁ }
6e52eea93f11718422e4979f241fbf346a160136
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Actions.lean
4be6e4e1792ea25776555352ff1b594d891a24fa
[ "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
3,966
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich, Mac Malone -/ import Lake.Util.Proc import Lake.Util.NativeLib import Lake.Build.Context namespace Lake open System def compileLeanModule (name : String) (leanFile : FilePath) (oleanFile? ileanFile? cFile? : Option FilePath) (leanPath : SearchPath := []) (rootDir : FilePath := ".") (dynlibs : Array FilePath := #[]) (dynlibPath : SearchPath := {}) (leanArgs : Array String := #[]) (lean : FilePath := "lean") : BuildM Unit := do logStep s!"Building {name}" let mut args := leanArgs ++ #[leanFile.toString, "-R", rootDir.toString] if let some oleanFile := oleanFile? then createParentDirs oleanFile args := args ++ #["-o", oleanFile.toString] if let some ileanFile := ileanFile? then createParentDirs ileanFile args := args ++ #["-i", ileanFile.toString] if let some cFile := cFile? then createParentDirs cFile args := args ++ #["-c", cFile.toString] for dynlib in dynlibs do args := args.push s!"--load-dynlib={dynlib}" proc { args cmd := lean.toString env := #[ ("LEAN_PATH", leanPath.toString), (sharedLibPathEnvVar, (← getSearchPath sharedLibPathEnvVar) ++ dynlibPath |>.toString) ] } def compileO (name : String) (oFile srcFile : FilePath) (moreArgs : Array String := #[]) (compiler : FilePath := "cc") : BuildM Unit := do logStep s!"Compiling {name}" createParentDirs oFile proc { cmd := compiler.toString args := #["-c", "-o", oFile.toString, srcFile.toString] ++ moreArgs } def compileStaticLib (name : String) (libFile : FilePath) (oFiles : Array FilePath) (ar : FilePath := "ar") : BuildM Unit := do logStep s!"Creating {name}" createParentDirs libFile proc { cmd := ar.toString args := #["rcs", libFile.toString] ++ oFiles.map toString } def compileSharedLib (name : String) (libFile : FilePath) (linkArgs : Array String) (linker : FilePath := "cc") : BuildM Unit := do logStep s!"Linking {name}" createParentDirs libFile proc { cmd := linker.toString args := #["-shared", "-o", libFile.toString] ++ linkArgs } def compileExe (name : String) (binFile : FilePath) (linkFiles : Array FilePath) (linkArgs : Array String := #[]) (linker : FilePath := "cc") : BuildM Unit := do logStep s!"Linking {name}" createParentDirs binFile proc { cmd := linker.toString args := #["-o", binFile.toString] ++ linkFiles.map toString ++ linkArgs } /-- Download a file using `curl`, clobbering any existing file. -/ def download (name : String) (url : String) (file : FilePath) : LogIO PUnit := do logInfo s!"Downloading {name}" if (← file.pathExists) then IO.FS.removeFile file else createParentDirs file let args := if (← getIsVerbose) then #[] else #["-s"] proc (quiet := true) { cmd := "curl" args := args ++ #["-f", "-o", file.toString, "-L", url] } /-- Unpack an archive `file` using `tar` into the directory `dir`. -/ def untar (name : String) (file : FilePath) (dir : FilePath) (gzip := true) : LogIO PUnit := do logInfo s!"Unpacking {name}" let mut opts := "-x" if (← getIsVerbose) then opts := opts.push 'v' if gzip then opts := opts.push 'z' proc { cmd := "tar", args := #[opts, "-f", file.toString, "-C", dir.toString] } /-- Pack a directory `dir` using `tar` into the archive `file`. -/ def tar (name : String) (dir : FilePath) (file : FilePath) (gzip := true) (excludePaths : Array FilePath := #[]) : LogIO PUnit := do logInfo s!"Packing {name}" createParentDirs file let mut args := #["-c"] if gzip then args := args.push "-z" if (← getIsVerbose) then args := args.push "-v" for path in excludePaths do args := args.push s!"--exclude={path}" proc { cmd := "tar" args := args ++ #["-f", file.toString, "-C", dir.toString, "."] }
2681c7aab0c6a31d6dbfb316e3ba42632c050bb3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/presheafed_space/gluing.lean
144ed3c721d9e9de6115ab929fbf03e1bef21681
[ "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
26,250
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import topology.gluing import algebraic_geometry.open_immersion import algebraic_geometry.locally_ringed_space.has_colimits /-! # Gluing Structured spaces Given a family of gluing data of structured spaces (presheafed spaces, sheafed spaces, or locally ringed spaces), we may glue them together. The construction should be "sealed" and considered as a black box, while only using the API provided. ## Main definitions * `algebraic_geometry.PresheafedSpace.glue_data`: A structure containing the family of gluing data. * `category_theory.glue_data.glued`: The glued presheafed space. This is defined as the multicoequalizer of `∐ V i j ⇉ ∐ U i`, so that the general colimit API can be used. * `category_theory.glue_data.ι`: The immersion `ι i : U i ⟶ glued` for each `i : J`. ## Main results * `algebraic_geometry.PresheafedSpace.glue_data.ι_is_open_immersion`: The map `ι i : U i ⟶ glued` is an open immersion for each `i : J`. * `algebraic_geometry.PresheafedSpace.glue_data.ι_jointly_surjective` : The underlying maps of `ι i : U i ⟶ glued` are jointly surjective. * `algebraic_geometry.PresheafedSpace.glue_data.V_pullback_cone_is_limit` : `V i j` is the pullback (intersection) of `U i` and `U j` over the glued space. Analogous results are also provided for `SheafedSpace` and `LocallyRingedSpace`. ## Implementation details Almost the whole file is dedicated to showing tht `ι i` is an open immersion. The fact that this is an open embedding of topological spaces follows from `topology.gluing.lean`, and it remains to construct `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_X, ι i '' U)` for each `U ⊆ U i`. Since `Γ(𝒪_X, ι i '' U)` is the the limit of `diagram_over_open`, the components of the structure sheafs of the spaces in the gluing diagram, we need to construct a map `ι_inv_app_π_app : Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_V, U_V)` for each `V` in the gluing diagram. We will refer to ![this diagram](https://i.imgur.com/P0phrwr.png) in the following doc strings. The `X` is the glued space, and the dotted arrow is a partial inverse guaranteed by the fact that it is an open immersion. The map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_{U_j}, _)` is given by the composition of the red arrows, and the map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_{V_{jk}}, _)` is given by the composition of the blue arrows. To lift this into a map from `Γ(𝒪_X, ι i '' U)`, we also need to show that these commute with the maps in the diagram (the green arrows), which is just a lengthy diagram-chasing. -/ noncomputable theory open topological_space category_theory opposite open category_theory.limits algebraic_geometry.PresheafedSpace open category_theory.glue_data namespace algebraic_geometry universes v u variables (C : Type u) [category.{v} C] namespace PresheafedSpace /-- A family of gluing data consists of 1. An index type `J` 2. A presheafed space `U i` for each `i : J`. 3. A presheafed space `V i j` for each `i j : J`. (Note that this is `J × J → PresheafedSpace C` rather than `J → J → PresheafedSpace C` to connect to the limits library easier.) 4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data (PresheafedSpace.{v} C) := (f_open : ∀ i j, is_open_immersion (f i j)) attribute [instance] glue_data.f_open namespace glue_data variables {C} (D : glue_data C) local notation `𝖣` := D.to_glue_data local notation `π₁ `i`, `j`, `k := @pullback.fst _ _ _ _ _ (D.f i j) (D.f i k) _ local notation `π₂ `i`, `j`, `k := @pullback.snd _ _ _ _ _ (D.f i j) (D.f i k) _ local notation `π₁⁻¹ `i`, `j`, `k := (PresheafedSpace.is_open_immersion.pullback_fst_of_right (D.f i j) (D.f i k)).inv_app local notation `π₂⁻¹ `i`, `j`, `k := (PresheafedSpace.is_open_immersion.pullback_snd_of_left (D.f i j) (D.f i k)).inv_app /-- The glue data of topological spaces associated to a family of glue data of PresheafedSpaces. -/ abbreviation to_Top_glue_data : Top.glue_data := { f_open := λ i j, (D.f_open i j).base_open, to_glue_data := 𝖣 .map_glue_data (forget C) } lemma ι_open_embedding [has_limits C] (i : D.J) : open_embedding (𝖣 .ι i).base := begin rw ← (show _ = (𝖣 .ι i).base, from 𝖣 .ι_glued_iso_inv (PresheafedSpace.forget _) _), exact open_embedding.comp (Top.homeo_of_iso (𝖣 .glued_iso (PresheafedSpace.forget _)).symm).open_embedding (D.to_Top_glue_data.ι_open_embedding i) end lemma pullback_base (i j k : D.J) (S : set (D.V (i, j)).carrier) : (π₂ i, j, k) '' ((π₁ i, j, k) ⁻¹' S) = D.f i k ⁻¹' (D.f i j '' S) := begin have eq₁ : _ = (π₁ i, j, k).base := preserves_pullback.iso_hom_fst (forget C) _ _, have eq₂ : _ = (π₂ i, j, k).base := preserves_pullback.iso_hom_snd (forget C) _ _, rw [coe_to_fun_eq, coe_to_fun_eq, ← eq₁, ← eq₂, coe_comp, set.image_comp, coe_comp, set.preimage_comp, set.image_preimage_eq, Top.pullback_snd_image_fst_preimage], refl, rw ← Top.epi_iff_surjective, apply_instance end /-- The red and the blue arrows in ![this diagram](https://i.imgur.com/0GiBUh6.png) commute. -/ @[simp, reassoc] lemma f_inv_app_f_app (i j k : D.J) (U : (opens (D.V (i, j)).carrier)) : (D.f_open i j).inv_app U ≫ (D.f i k).c.app _ = (π₁ i, j, k).c.app (op U) ≫ (π₂⁻¹ i, j, k) (unop _) ≫ (D.V _).presheaf.map (eq_to_hom (begin delta is_open_immersion.open_functor, dsimp only [functor.op, is_open_map.functor, opens.map, unop_op], congr, apply pullback_base, end)) := begin have := PresheafedSpace.congr_app (@pullback.condition _ _ _ _ _ (D.f i j) (D.f i k) _), dsimp only [comp_c_app] at this, rw [← cancel_epi (inv ((D.f_open i j).inv_app U)), is_iso.inv_hom_id_assoc, is_open_immersion.inv_inv_app], simp_rw category.assoc, erw [(π₁ i, j, k).c.naturality_assoc, reassoc_of this, ← functor.map_comp_assoc, is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app_assoc, ← (D.V (i, k)).presheaf.map_comp, ← (D.V (i, k)).presheaf.map_comp], convert (category.comp_id _).symm, erw (D.V (i, k)).presheaf.map_id, refl end /-- We can prove the `eq` along with the lemma. Thus this is bundled together here, and the lemma itself is separated below. -/ lemma snd_inv_app_t_app' (i j k : D.J) (U : opens (pullback (D.f i j) (D.f i k)).carrier) : ∃ eq, (π₂⁻¹ i, j, k) U ≫ (D.t k i).c.app _ ≫ (D.V (k, i)).presheaf.map (eq_to_hom eq) = (D.t' k i j).c.app _ ≫ (π₁⁻¹ k, j, i) (unop _) := begin split, rw [← is_iso.eq_inv_comp, is_open_immersion.inv_inv_app, category.assoc, (D.t' k i j).c.naturality_assoc], simp_rw ← category.assoc, erw ← comp_c_app, rw [congr_app (D.t_fac k i j), comp_c_app], simp_rw category.assoc, erw [is_open_immersion.inv_naturality, is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app'_assoc], simp_rw [← (𝖣 .V (k, i)).presheaf.map_comp, eq_to_hom_map (functor.op _), eq_to_hom_op, eq_to_hom_trans], rintros x ⟨y, hy, eq⟩, replace eq := concrete_category.congr_arg ((𝖣 .t i k).base) eq, change ((π₂ i, j, k) ≫ D.t i k).base y = (D.t k i ≫ D.t i k).base x at eq, rw [𝖣 .t_inv, id_base, Top.id_app] at eq, subst eq, use (inv (D.t' k i j)).base y, change ((inv (D.t' k i j)) ≫ (π₁ k, i, j)).base y = _, congr' 2, rw [is_iso.inv_comp_eq, 𝖣 .t_fac_assoc, 𝖣 .t_inv, category.comp_id] end /-- The red and the blue arrows in ![this diagram](https://i.imgur.com/q6X1GJ9.png) commute. -/ @[simp, reassoc] lemma snd_inv_app_t_app (i j k : D.J) (U : opens (pullback (D.f i j) (D.f i k)).carrier) : (π₂⁻¹ i, j, k) U ≫ (D.t k i).c.app _ = (D.t' k i j).c.app _ ≫ (π₁⁻¹ k, j, i) (unop _) ≫ (D.V (k, i)).presheaf.map (eq_to_hom (D.snd_inv_app_t_app' i j k U).some.symm) := begin have e := (D.snd_inv_app_t_app' i j k U).some_spec, reassoc! e, rw ← e, simp [eq_to_hom_map], end variable [has_limits C] lemma ι_image_preimage_eq (i j : D.J) (U : opens (D.U i).carrier) : (opens.map (𝖣 .ι j).base).obj ((D.ι_open_embedding i).is_open_map.functor.obj U) = (D.f_open j i).open_functor.obj ((opens.map (𝖣 .t j i).base).obj ((opens.map (𝖣 .f i j).base).obj U)) := begin dsimp only [opens.map, is_open_map.functor], congr' 1, rw [← (show _ = (𝖣 .ι i).base, from 𝖣 .ι_glued_iso_inv (PresheafedSpace.forget _) i), ← (show _ = (𝖣 .ι j).base, from 𝖣 .ι_glued_iso_inv (PresheafedSpace.forget _) j), coe_comp, coe_comp, set.image_comp, set.preimage_comp, set.preimage_image_eq], refine eq.trans (D.to_Top_glue_data.preimage_image_eq_image' _ _ _) _, rw [coe_comp, set.image_comp], congr' 1, erw set.eq_preimage_iff_image_eq, rw ← set.image_comp, change (D.t i j ≫ D.t j i).base '' _ = _, rw 𝖣 .t_inv, { simp }, { change function.bijective (Top.homeo_of_iso (as_iso _)), exact homeomorph.bijective _, apply_instance }, { rw ← Top.mono_iff_injective, apply_instance } end /-- (Implementation). The map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_{U_j}, 𝖣.ι j ⁻¹' (𝖣.ι i '' U))` -/ def opens_image_preimage_map (i j : D.J) (U : opens (D.U i).carrier) : (D.U i).presheaf.obj (op U) ⟶ (D.U j).presheaf.obj _ := (D.f i j).c.app (op U) ≫ (D.t j i).c.app _ ≫ (D.f_open j i).inv_app (unop _) ≫ (𝖣 .U j).presheaf.map (eq_to_hom (D.ι_image_preimage_eq i j U)).op lemma opens_image_preimage_map_app' (i j k : D.J) (U : opens (D.U i).carrier) : ∃ eq, D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ = ((π₁ j, i, k) ≫ D.t j i ≫ D.f i j).c.app (op U) ≫ (π₂⁻¹ j, i, k) (unop _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom eq) := begin split, delta opens_image_preimage_map, simp_rw category.assoc, rw [(D.f j k).c.naturality, f_inv_app_f_app_assoc], erw ← (D.V (j, k)).presheaf.map_comp, simp_rw ← category.assoc, erw [← comp_c_app, ← comp_c_app], simp_rw category.assoc, dsimp only [functor.op, unop_op, quiver.hom.unop_op], rw [eq_to_hom_map (opens.map _), eq_to_hom_op, eq_to_hom_trans], congr end /-- The red and the blue arrows in ![this diagram](https://i.imgur.com/mBzV1Rx.png) commute. -/ lemma opens_image_preimage_map_app (i j k : D.J) (U : opens (D.U i).carrier) : D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ = ((π₁ j, i, k) ≫ D.t j i ≫ D.f i j).c.app (op U) ≫ (π₂⁻¹ j, i, k) (unop _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom ((opens_image_preimage_map_app' D i j k U).some)) := (opens_image_preimage_map_app' D i j k U).some_spec -- This is proved separately since `reassoc` somehow timeouts. lemma opens_image_preimage_map_app_assoc (i j k : D.J) (U : opens (D.U i).carrier) {X' : C} (f' : _ ⟶ X') : D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ ≫ f' = ((π₁ j, i, k) ≫ D.t j i ≫ D.f i j).c.app (op U) ≫ (π₂⁻¹ j, i, k) (unop _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom ((opens_image_preimage_map_app' D i j k U).some)) ≫ f' := by simpa only [category.assoc] using congr_arg (λ g, g ≫ f') (opens_image_preimage_map_app D i j k U) /-- (Implementation) Given an open subset of one of the spaces `U ⊆ Uᵢ`, the sheaf component of the image `ι '' U` in the glued space is the limit of this diagram. -/ abbreviation diagram_over_open {i : D.J} (U : opens (D.U i).carrier) : (walking_multispan _ _)ᵒᵖ ⥤ C := componentwise_diagram 𝖣 .diagram.multispan ((D.ι_open_embedding i).is_open_map.functor.obj U) /-- (Implementation) The projection from the limit of `diagram_over_open` to a component of `D.U j`. -/ abbreviation diagram_over_open_π {i : D.J} (U : opens (D.U i).carrier) (j : D.J) := limit.π (D.diagram_over_open U) (op (walking_multispan.right j)) /-- (Implementation) We construct the map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_V, U_V)` for each `V` in the gluing diagram. We will lift these maps into `ι_inv_app`. -/ def ι_inv_app_π_app {i : D.J} (U : opens (D.U i).carrier) (j) : (𝖣 .U i).presheaf.obj (op U) ⟶ (D.diagram_over_open U).obj (op j) := begin rcases j with (⟨j, k⟩|j), { refine D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ ≫ (D.V (j, k)).presheaf.map (eq_to_hom _), dsimp only [functor.op, opens.map, unop_op], congr' 2, rw set.preimage_preimage, change (D.f j k ≫ 𝖣 .ι j).base ⁻¹' _ = _, congr' 3, exact colimit.w 𝖣 .diagram.multispan (walking_multispan.hom.fst (j, k)) }, { exact D.opens_image_preimage_map i j U } end /-- (Implementation) The natural map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_X, 𝖣.ι i '' U)`. This forms the inverse of `(𝖣.ι i).c.app (op U)`. -/ def ι_inv_app {i : D.J} (U : opens (D.U i).carrier) : (D.U i).presheaf.obj (op U) ⟶ limit (D.diagram_over_open U) := limit.lift (D.diagram_over_open U) { X := (D.U i).presheaf.obj (op U), π := { app := λ j, D.ι_inv_app_π_app U (unop j), naturality' := λ X Y f', begin induction X using opposite.rec, induction Y using opposite.rec, let f : Y ⟶ X := f'.unop, have : f' = f.op := rfl, clear_value f, subst this, rcases f with (_|⟨j,k⟩|⟨j,k⟩), { erw [category.id_comp, category_theory.functor.map_id], rw category.comp_id }, { erw category.id_comp, congr' 1 }, erw category.id_comp, -- It remains to show that the blue is equal to red + green in the original diagram. -- The proof strategy is illustrated in ![this diagram](https://i.imgur.com/mBzV1Rx.png) -- where we prove red = pink = light-blue = green = blue. change D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ ≫ (D.V (j, k)).presheaf.map (eq_to_hom _) = D.opens_image_preimage_map _ _ _ ≫ ((D.f k j).c.app _ ≫ (D.t j k).c.app _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom _), erw opens_image_preimage_map_app_assoc, simp_rw category.assoc, erw [opens_image_preimage_map_app_assoc, (D.t j k).c.naturality_assoc], rw snd_inv_app_t_app_assoc, erw ← PresheafedSpace.comp_c_app_assoc, -- light-blue = green is relatively easy since the part that differs does not involve -- partial inverses. have : D.t' j k i ≫ (π₁ k, i, j) ≫ D.t k i ≫ 𝖣 .f i k = (pullback_symmetry _ _).hom ≫ (π₁ j, i, k) ≫ D.t j i ≫ D.f i j, { rw [← 𝖣 .t_fac_assoc, 𝖣 .t'_comp_eq_pullback_symmetry_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.condition, 𝖣 .t_fac_assoc] }, rw congr_app this, erw PresheafedSpace.comp_c_app_assoc (pullback_symmetry _ _).hom, simp_rw category.assoc, congr' 1, rw ← is_iso.eq_inv_comp, erw is_open_immersion.inv_inv_app, simp_rw category.assoc, erw [nat_trans.naturality_assoc, ← PresheafedSpace.comp_c_app_assoc, congr_app (pullback_symmetry_hom_comp_snd _ _)], simp_rw category.assoc, erw [is_open_immersion.inv_naturality_assoc, is_open_immersion.inv_naturality_assoc, is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app_assoc], repeat { erw ← (D.V (j, k)).presheaf.map_comp }, congr, end } } /-- `ι_inv_app` is the left inverse of `D.ι i` on `U`. -/ lemma ι_inv_app_π {i : D.J} (U : opens (D.U i).carrier) : ∃ eq, D.ι_inv_app U ≫ D.diagram_over_open_π U i = (D.U i).presheaf.map (eq_to_hom eq) := begin split, delta ι_inv_app, rw limit.lift_π, change D.opens_image_preimage_map i i U = _, dsimp [opens_image_preimage_map], rw [congr_app (D.t_id _), id_c_app, ← functor.map_comp], erw [is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app'_assoc], simp only [eq_to_hom_op, eq_to_hom_trans, eq_to_hom_map (functor.op _), ← functor.map_comp], rw set.range_iff_surjective.mpr _, { simp }, { rw ← Top.epi_iff_surjective, apply_instance } end /-- The `eq_to_hom` given by `ι_inv_app_π`. -/ abbreviation ι_inv_app_π_eq_map {i : D.J} (U : opens (D.U i).carrier) := (D.U i).presheaf.map (eq_to_iso (D.ι_inv_app_π U).some).inv /-- `ι_inv_app` is the right inverse of `D.ι i` on `U`. -/ lemma π_ι_inv_app_π (i j : D.J) (U : opens (D.U i).carrier) : D.diagram_over_open_π U i ≫ D.ι_inv_app_π_eq_map U ≫ D.ι_inv_app U ≫ D.diagram_over_open_π U j = D.diagram_over_open_π U j := begin rw ← cancel_mono ((componentwise_diagram 𝖣 .diagram.multispan _).map (quiver.hom.op (walking_multispan.hom.snd (i, j))) ≫ (𝟙 _)), simp_rw category.assoc, rw limit.w_assoc, erw limit.lift_π_assoc, rw [category.comp_id, category.comp_id], change _ ≫ _ ≫ (_ ≫ _) ≫ _ = _, rw [congr_app (D.t_id _), id_c_app], simp_rw category.assoc, rw [← functor.map_comp_assoc, is_open_immersion.inv_naturality_assoc], erw is_open_immersion.app_inv_app_assoc, iterate 3 { rw ← functor.map_comp_assoc }, rw nat_trans.naturality_assoc, erw ← (D.V (i, j)).presheaf.map_comp, convert limit.w (componentwise_diagram 𝖣 .diagram.multispan _) (quiver.hom.op (walking_multispan.hom.fst (i, j))), { rw category.comp_id, apply_with mono_comp { instances := ff }, change mono ((_ ≫ D.f j i).c.app _), rw comp_c_app, apply_with mono_comp { instances := ff }, erw D.ι_image_preimage_eq i j U, all_goals { apply_instance } }, end /-- `ι_inv_app` is the inverse of `D.ι i` on `U`. -/ lemma π_ι_inv_app_eq_id (i : D.J) (U : opens (D.U i).carrier) : D.diagram_over_open_π U i ≫ D.ι_inv_app_π_eq_map U ≫ D.ι_inv_app U = 𝟙 _ := begin ext j, induction j using opposite.rec, rcases j with (⟨j, k⟩|⟨j⟩), { rw [← limit.w (componentwise_diagram 𝖣 .diagram.multispan _) (quiver.hom.op (walking_multispan.hom.fst (j, k))), ← category.assoc, category.id_comp], congr' 1, simp_rw category.assoc, apply π_ι_inv_app_π }, { simp_rw category.assoc, rw category.id_comp, apply π_ι_inv_app_π } end instance componentwise_diagram_π_is_iso (i : D.J) (U : opens (D.U i).carrier) : is_iso (D.diagram_over_open_π U i) := begin use D.ι_inv_app_π_eq_map U ≫ D.ι_inv_app U, split, { apply π_ι_inv_app_eq_id }, { rw [category.assoc, (D.ι_inv_app_π _).some_spec], exact iso.inv_hom_id ((D.to_glue_data.U i).presheaf.map_iso (eq_to_iso _)) } end instance ι_is_open_immersion (i : D.J) : is_open_immersion (𝖣 .ι i) := { base_open := D.ι_open_embedding i, c_iso := λ U, by { erw ← colimit_presheaf_obj_iso_componentwise_limit_hom_π, apply_instance } } /-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`. Vᵢⱼ ⟶ Uᵢ | | ↓ ↓ Uⱼ ⟶ X -/ def V_pullback_cone_is_limit (i j : D.J) : is_limit (𝖣 .V_pullback_cone i j) := pullback_cone.is_limit_aux' _ $ λ s, begin refine ⟨_, _, _, _⟩, { refine PresheafedSpace.is_open_immersion.lift (D.f i j) s.fst _, erw ← D.to_Top_glue_data.preimage_range j i, have : s.fst.base ≫ D.to_Top_glue_data.to_glue_data.ι i = s.snd.base ≫ D.to_Top_glue_data.to_glue_data.ι j, { rw [← 𝖣 .ι_glued_iso_hom (PresheafedSpace.forget _) _, ← 𝖣 .ι_glued_iso_hom (PresheafedSpace.forget _) _], have := congr_arg PresheafedSpace.hom.base s.condition, rw [comp_base, comp_base] at this, reassoc! this, exact this _ }, rw [← set.image_subset_iff, ← set.image_univ, ← set.image_comp, set.image_univ, ← coe_comp, this, coe_comp, ← set.image_univ, set.image_comp], exact set.image_subset_range _ _ }, { apply is_open_immersion.lift_fac }, { rw [← cancel_mono (𝖣 .ι j), category.assoc, ← (𝖣 .V_pullback_cone i j).condition], conv_rhs { rw ← s.condition }, erw is_open_immersion.lift_fac_assoc }, { intros m e₁ e₂, rw ← cancel_mono (D.f i j), erw e₁, rw is_open_immersion.lift_fac } end lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ (i : D.J) (y : D.U i), (𝖣 .ι i).base y = x := 𝖣 .ι_jointly_surjective (PresheafedSpace.forget _ ⋙ category_theory.forget Top) x end glue_data end PresheafedSpace namespace SheafedSpace variables (C) [has_products.{v} C] /-- A family of gluing data consists of 1. An index type `J` 2. A sheafed space `U i` for each `i : J`. 3. A sheafed space `V i j` for each `i j : J`. (Note that this is `J × J → SheafedSpace C` rather than `J → J → SheafedSpace C` to connect to the limits library easier.) 4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data (SheafedSpace.{v} C) := (f_open : ∀ i j, SheafedSpace.is_open_immersion (f i j)) attribute [instance] glue_data.f_open namespace glue_data variables {C} (D : glue_data C) local notation `𝖣` := D.to_glue_data /-- The glue data of presheafed spaces associated to a family of glue data of sheafed spaces. -/ abbreviation to_PresheafedSpace_glue_data : PresheafedSpace.glue_data C := { f_open := D.f_open, to_glue_data := 𝖣 .map_glue_data forget_to_PresheafedSpace } variable [has_limits C] /-- The gluing as sheafed spaces is isomorphic to the gluing as presheafed spaces. -/ abbreviation iso_PresheafedSpace : 𝖣 .glued.to_PresheafedSpace ≅ D.to_PresheafedSpace_glue_data.to_glue_data.glued := 𝖣 .glued_iso forget_to_PresheafedSpace lemma ι_iso_PresheafedSpace_inv (i : D.J) : D.to_PresheafedSpace_glue_data.to_glue_data.ι i ≫ D.iso_PresheafedSpace.inv = 𝖣 .ι i := 𝖣 .ι_glued_iso_inv _ _ instance ι_is_open_immersion (i : D.J) : is_open_immersion (𝖣 .ι i) := by { rw ← D.ι_iso_PresheafedSpace_inv, apply_instance } lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ (i : D.J) (y : D.U i), (𝖣 .ι i).base y = x := 𝖣 .ι_jointly_surjective (SheafedSpace.forget _ ⋙ category_theory.forget Top) x /-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`. Vᵢⱼ ⟶ Uᵢ | | ↓ ↓ Uⱼ ⟶ X -/ def V_pullback_cone_is_limit (i j : D.J) : is_limit (𝖣 .V_pullback_cone i j) := 𝖣 .V_pullback_cone_is_limit_of_map forget_to_PresheafedSpace i j (D.to_PresheafedSpace_glue_data.V_pullback_cone_is_limit _ _) end glue_data end SheafedSpace namespace LocallyRingedSpace /-- A family of gluing data consists of 1. An index type `J` 2. A locally ringed space `U i` for each `i : J`. 3. A locally ringed space `V i j` for each `i j : J`. (Note that this is `J × J → LocallyRingedSpace` rather than `J → J → LocallyRingedSpace` to connect to the limits library easier.) 4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data LocallyRingedSpace := (f_open : ∀ i j, LocallyRingedSpace.is_open_immersion (f i j)) attribute [instance] glue_data.f_open namespace glue_data variables (D : glue_data) local notation `𝖣` := D.to_glue_data /-- The glue data of ringed spaces associated to a family of glue data of locally ringed spaces. -/ abbreviation to_SheafedSpace_glue_data : SheafedSpace.glue_data CommRing := { f_open := D.f_open, to_glue_data := 𝖣 .map_glue_data forget_to_SheafedSpace } /-- The gluing as locally ringed spaces is isomorphic to the gluing as ringed spaces. -/ abbreviation iso_SheafedSpace : 𝖣 .glued.to_SheafedSpace ≅ D.to_SheafedSpace_glue_data.to_glue_data.glued := 𝖣 .glued_iso forget_to_SheafedSpace lemma ι_iso_SheafedSpace_inv (i : D.J) : D.to_SheafedSpace_glue_data.to_glue_data.ι i ≫ D.iso_SheafedSpace.inv = (𝖣 .ι i).1 := 𝖣 .ι_glued_iso_inv forget_to_SheafedSpace i instance ι_is_open_immersion (i : D.J) : is_open_immersion (𝖣 .ι i) := by { delta is_open_immersion, rw ← D.ι_iso_SheafedSpace_inv, apply PresheafedSpace.is_open_immersion.comp } instance (i j k : D.J) : preserves_limit (cospan (𝖣 .f i j) (𝖣 .f i k)) forget_to_SheafedSpace := infer_instance lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ (i : D.J) (y : D.U i), (𝖣 .ι i).1.base y = x := 𝖣 .ι_jointly_surjective ((LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget _) ⋙ forget Top) x /-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`. Vᵢⱼ ⟶ Uᵢ | | ↓ ↓ Uⱼ ⟶ X -/ def V_pullback_cone_is_limit (i j : D.J) : is_limit (𝖣 .V_pullback_cone i j) := 𝖣 .V_pullback_cone_is_limit_of_map forget_to_SheafedSpace i j (D.to_SheafedSpace_glue_data.V_pullback_cone_is_limit _ _) end glue_data end LocallyRingedSpace end algebraic_geometry
fb9e79a1b6d2cce3940e98a92c408d5cd31ed56b
1f6fe2f89976b14a4567ab298c35792b21f2e50b
/homotopy/pushout.hlean
fde01fb51fd713c106beec045fef6850bce9711c
[ "Apache-2.0" ]
permissive
jonas-frey/Spectral
e5c1c2f7bcac26aa55f7b1e041a81272a146198d
72d521091525a4bc9a31cac859840efe9461cf66
refs/heads/master
1,610,235,743,345
1,505,417,795,000
1,505,417,795,000
102,653,342
0
0
null
1,504,728,483,000
1,504,728,483,000
null
UTF-8
Lean
false
false
34,660
hlean
import ..algebra.exactness homotopy.cofiber homotopy.wedge open eq function is_trunc sigma prod lift is_equiv equiv pointed sum unit bool cofiber namespace pushout section variables {TL BL TR : Type*} {f : TL →* BL} {g : TL →* TR} {TL' BL' TR' : Type*} {f' : TL' →* BL'} {g' : TL' →* TR'} (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) definition ppushout_functor [constructor] (tl : TL → TL') (bl : BL →* BL') (tr : TR → TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g →* ppushout f' g' := begin fconstructor, { exact pushout.functor tl bl tr fh gh }, { exact ap inl (respect_pt bl) }, end definition ppushout_pequiv (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g ≃* ppushout f' g' := pequiv_of_equiv (pushout.equiv _ _ _ _ tl bl tr fh gh) (ap inl (respect_pt bl)) end /- WIP: proving that satisfying the universal property of the pushout is equivalent to being equivalent to the pushout -/ universe variables u₁ u₂ u₃ u₄ variables {A : Type.{u₁}} {B : Type.{u₂}} {C : Type.{u₃}} {D D' : Type.{u₄}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) -- (f : A → B) (g : A → C) (h : B → D) (k : C → D) include p definition is_pushout : Type := Π⦃X : Type.{max u₁ u₂ u₃ u₄}⦄ (h' : B → X) (k' : C → X) (p' : h' ∘ f ~ k' ∘ g), is_contr (Σ(l : D → X) (v : l ∘ h ~ h' × l ∘ k ~ k'), Πa, square (prod.pr1 v (f a)) (prod.pr2 v (g a)) (ap l (p a)) (p' a)) definition cocone [reducible] (X : Type) : Type := Σ(v : (B → X) × (C → X)), prod.pr1 v ∘ f ~ prod.pr2 v ∘ g definition cocone_of_map [constructor] (X : Type) (l : D → X) : cocone p X := ⟨(l ∘ h, l ∘ k), λa, ap l (p a)⟩ -- definition cocone_of_map (X : Type) (l : D → X) : Σ(h' : B → X) (k' : C → X), -- h' ∘ f ~ k' ∘ g := -- ⟨l ∘ h, l ∘ k, λa, ap l (p a)⟩ omit p definition is_pushout2 [reducible] : Type := Π(X : Type.{max u₁ u₂ u₃ u₄}), is_equiv (cocone_of_map p X) section open sigma.ops protected definition inv_left (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ h ~ prod.pr1 v.1 := ap10 (ap prod.pr1 (right_inv (cocone_of_map p X) v)..1) protected definition inv_right (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ k ~ prod.pr2 v.1 := ap10 (ap prod.pr2 (right_inv (cocone_of_map p X) v)..1) end section local attribute is_pushout [reducible] definition is_prop_is_pushout : is_prop (is_pushout p) := _ local attribute is_pushout2 [reducible] definition is_prop_is_pushout2 : is_prop (is_pushout2 p) := _ end definition ap_eq_apd10_ap {A B : Type} {C : B → Type} (f : A → Πb, C b) {a a' : A} (p : a = a') (b : B) : ap (λa, f a b) p = apd10 (ap f p) b := by induction p; reflexivity variables (f g) definition is_pushout2_pushout : @is_pushout2 _ _ _ _ f g inl inr glue := λX, to_is_equiv (pushout_arrow_equiv f g X ⬝e assoc_equiv_prod _) definition is_equiv_of_is_pushout2_simple [constructor] {A B C D : Type.{u₁}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) (H : is_pushout2 p) : D ≃ pushout f g := begin fapply equiv.MK, { exact (cocone_of_map p _)⁻¹ᶠ ⟨(inl, inr), glue⟩ }, { exact pushout.elim h k p }, { intro x, exact sorry }, { apply ap10, apply eq_of_fn_eq_fn (equiv.mk _ (H D)), fapply sigma_eq, { esimp, fapply prod_eq, apply eq_of_homotopy, intro b, exact ap (pushout.elim h k p) (pushout.inv_left p H ⟨(inl, inr), glue⟩ b), apply eq_of_homotopy, intro c, exact ap (pushout.elim h k p) (pushout.inv_right p H ⟨(inl, inr), glue⟩ c) }, { apply pi.pi_pathover_constant, intro a, apply eq_pathover, refine !ap_eq_apd10_ap ⬝ph _ ⬝hp !ap_eq_apd10_ap⁻¹, refine ap (λx, apd10 x _) (ap_compose (λx, x ∘ f) pr1 _ ⬝ ap02 _ !prod_eq_pr1) ⬝ph _ ⬝hp ap (λx, apd10 x _) (ap_compose (λx, x ∘ g) pr2 _ ⬝ ap02 _ !prod_eq_pr2)⁻¹, refine apd10 !apd10_ap_precompose_dependent a ⬝ph _ ⬝hp apd10 !apd10_ap_precompose_dependent⁻¹ a, refine apd10 !apd10_eq_of_homotopy (f a) ⬝ph _ ⬝hp apd10 !apd10_eq_of_homotopy⁻¹ (g a), refine ap_compose (pushout.elim h k p) _ _ ⬝pv _, refine aps (pushout.elim h k p) _ ⬝vp (!elim_glue ⬝ !ap_id⁻¹), esimp, exact sorry }, } end -- definition is_equiv_of_is_pushout2 [constructor] (H : is_pushout2 p) : D ≃ pushout f g := -- begin -- fapply equiv.MK, -- { exact down.{_ u₄} ∘ (cocone_of_map p _)⁻¹ᶠ ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ }, -- { exact pushout.elim h k p }, -- { intro x, exact sorry -- }, -- { intro d, apply eq_of_fn_eq_fn (equiv_lift D), esimp, revert d, -- apply ap10, -- apply eq_of_fn_eq_fn (equiv.mk _ (H (lift.{_ (max u₁ u₂ u₃)} D))), -- fapply sigma_eq, -- { esimp, fapply prod_eq, -- apply eq_of_homotopy, intro b, apply ap up, esimp, -- exact ap (pushout.elim h k p ∘ down.{_ u₄}) -- (pushout.inv_left p H ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ b), -- exact sorry }, -- { exact sorry }, -- -- note q := @eq_of_is_contr _ H'' -- -- ⟨up ∘ pushout.elim h k p ∘ down ∘ (center' H').1, -- -- (λb, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr1 (center' H').2 b), -- -- λc, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr2 (center' H').2 c))⟩ -- -- ⟨up, (λx, idp, λx, idp)⟩, -- -- exact ap down (ap10 q..1 d) -- } -- end /- composing pushouts -/ definition pushout_vcompose_to [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout h (@inl _ _ _ f g)) : pushout (h ∘ f) g := begin induction x with d y b, { exact inl d }, { induction y with b c a, { exact inl (h b) }, { exact inr c }, { exact glue a }}, { reflexivity } end definition pushout_vcompose_from [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout (h ∘ f) g) : pushout h (@inl _ _ _ f g) := begin induction x with d c a, { exact inl d }, { exact inr (inr c) }, { exact glue (f a) ⬝ ap inr (glue a) } end definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := begin fapply equiv.MK, { exact pushout_vcompose_to }, { exact pushout_vcompose_from }, { intro x, induction x with d c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_vcompose_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ !ap_compose'⁻¹ ⬝ !idp_con ⬝ _, esimp, apply elim_glue }}, { intro x, induction x with d y b, { reflexivity }, { induction y with b c a, { exact glue b }, { reflexivity }, { apply eq_pathover, refine ap_compose pushout_vcompose_from _ _ ⬝ph _, esimp, refine ap02 _ !elim_glue ⬝ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }}, { apply eq_pathover_id_right, esimp, refine ap_compose pushout_vcompose_from _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }} end definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := calc pushout (@inr _ _ _ f g) h ≃ pushout h (@inr _ _ _ f g) : pushout.symm ... ≃ pushout h (@inl _ _ _ g f) : pushout.equiv _ _ _ _ erfl erfl (pushout.symm f g) (λa, idp) (λa, idp) ... ≃ pushout (h ∘ g) f : pushout_vcompose ... ≃ pushout f (h ∘ g) : pushout.symm definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : pushout h k ≃ pushout hf g := begin refine _ ⬝e pushout_vcompose f g h ⬝e _, { fapply pushout.equiv, reflexivity, reflexivity, exact e, reflexivity, exact homotopy_of_homotopy_inv_post e _ _ p }, { fapply pushout.equiv, reflexivity, reflexivity, reflexivity, exact q, reflexivity }, end definition pushout_hcompose_equiv {A B C D E : Type} {f : A → B} (g : A → C) {h : C → E} {hg : A → E} {k : C → D} (e : D ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inr) (q : h ∘ g ~ hg) : pushout k h ≃ pushout f hg := calc pushout k h ≃ pushout h k : pushout.symm ... ≃ pushout hg f : by exact pushout_vcompose_equiv _ (e ⬝e pushout.symm f g) p q ... ≃ pushout f hg : pushout.symm definition pushout_of_equiv_left_to [unfold 6] {A B C : Type} {f : A ≃ B} {g : A → C} (x : pushout f g) : C := begin induction x with b c a, { exact g (f⁻¹ b) }, { exact c }, { exact ap g (left_inv f a) } end definition pushout_of_equiv_left [constructor] {A B C : Type} (f : A ≃ B) (g : A → C) : pushout f g ≃ C := begin fapply equiv.MK, { exact pushout_of_equiv_left_to }, { exact inr }, { intro c, reflexivity }, { intro x, induction x with b c a, { exact (glue (f⁻¹ b))⁻¹ ⬝ ap inl (right_inv f b) }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose inr _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply move_top_of_left, apply move_left_of_bot, refine ap02 _ (adj f _) ⬝ !ap_compose⁻¹ ⬝pv _ ⬝vp !ap_compose, apply natural_square_tr }} end definition pushout_of_equiv_right [constructor] {A B C : Type} (f : A → B) (g : A ≃ C) : pushout f g ≃ B := calc pushout f g ≃ pushout g f : pushout.symm f g ... ≃ B : pushout_of_equiv_left g f -- todo: define pushout.equiv (renamed to pushout_equiv_pushout) using this variables {A₁ B₁ C₁ A₂ B₂ C₂ A₃ B₃ C₃ : Type} {f₁ : A₁ → B₁} {g₁ : A₁ → C₁} {f₂ : A₂ → B₂} {g₂ : A₂ → C₂} {f₃ : A₃ → B₃} {g₃ : A₃ → C₃} {h₂ : A₂ → A₃} {h₁ : A₁ → A₂} {i₂ : B₂ → B₃} {i₁ : B₁ → B₂} {j₂ : C₂ → C₃} {j₁ : C₁ → C₂} (p₂ : i₂ ∘ f₂ ~ f₃ ∘ h₂) (q₂ : j₂ ∘ g₂ ~ g₃ ∘ h₂) (p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁) (q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁) definition pushout_functor_compose : pushout.functor (h₂ ∘ h₁) (i₂ ∘ i₁) (j₂ ∘ j₁) (p₁ ⬝htyv p₂) (q₁ ⬝htyv q₂) ~ pushout.functor h₂ i₂ j₂ p₂ q₂ ∘ pushout.functor h₁ i₁ j₁ p₁ q₁ := begin intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, refine !elim_glue ⬝ whisker_right _ (!ap_con ⬝ !ap_compose'⁻¹ ◾ idp) ◾ (ap02 _ !con_inv ⬝ !ap_con ⬝ whisker_left _ (ap02 _ !ap_inv⁻¹ ⬝ !ap_compose'⁻¹)) ⬝ _ ⬝ (ap_compose (pushout.functor h₂ i₂ j₂ p₂ q₂) _ _ ⬝ ap02 _ !elim_glue)⁻¹, refine _ ⬝ (!ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ !ap_compose'⁻¹)⁻¹ᵖ, refine !con.assoc⁻¹ ⬝ whisker_right _ _, exact whisker_right _ !con.assoc ⬝ !con.assoc } end variables {p₁ q₁} definition pushout_functor_homotopy_constant {p₁' : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁' : j₁ ∘ g₁ ~ g₂ ∘ h₁} (p : p₁ ~ p₁') (q : q₁ ~ q₁') : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₁ i₁ j₁ p₁' q₁' := begin induction p, induction q, reflexivity end definition pushout_functor_homotopy {h₁ h₂ : A₁ → A₂} {i₁ i₂ : B₁ → B₂} {j₁ j₂ : C₁ → C₂} {p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁} {p₂ : i₂ ∘ f₁ ~ f₂ ∘ h₂} {q₂ : j₂ ∘ g₁ ~ g₂ ∘ h₂} (r : h₁ ~ h₂) (s : i₁ ~ i₂) (t : j₁ ~ j₂) (u : r ⬝htyh p₁ ~ p₂ ⬝htyh s) (v : r ⬝htyh q₁ ~ q₂ ⬝htyh t) : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₂ i₂ j₂ p₂ q₂ := begin induction r, induction s, induction t, apply pushout_functor_homotopy_constant, { exact (rfl_hhconcat p₁)⁻¹ʰᵗʸ ⬝hty u ⬝hty hhconcat_rfl p₂ }, exact (rfl_hhconcat q₁)⁻¹ʰᵗʸ ⬝hty v ⬝hty hhconcat_rfl q₂ end /- pushout where one map is constant is a cofiber -/ definition pushout_const_equiv_to [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : pushout f (const A c₀)) : cofiber (sum_functor f (const unit c₀)) := begin induction x with b c a, { exact !cod (sum.inl b) }, { exact !cod (sum.inr c) }, { exact glue (sum.inl a) ⬝ (glue (sum.inr ⋆))⁻¹ } end definition pushout_const_equiv_from [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : cofiber (sum_functor f (const unit c₀))) : pushout f (const A c₀) := begin induction x with v v, { induction v with b c, exact inl b, exact inr c }, { exact inr c₀ }, { induction v with a u, exact glue a, reflexivity } end definition pushout_const_equiv [constructor] {A B C : Type} (f : A → B) (c₀ : C) : pushout f (const A c₀) ≃ cofiber (sum_functor f (const unit c₀)) := begin fapply equiv.MK, { exact pushout_const_equiv_to }, { exact pushout_const_equiv_from }, { intro x, induction x with v v, { induction v with b c, reflexivity, reflexivity }, { exact glue (sum.inr ⋆) }, { apply eq_pathover_id_right, refine ap_compose pushout_const_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction v with a u, { refine !elim_glue ⬝ph _, apply whisker_bl, exact hrfl }, { induction u, exact square_of_eq idp }}}, { intro x, induction x with c b a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_const_equiv_from _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) }} end /- wedge is the cofiber of the map 2 -> A + B -/ -- move to sum definition sum_of_bool [unfold 3] (A B : Type*) (b : bool) : A + B := by induction b; exact sum.inl pt; exact sum.inr pt definition psum_of_pbool [constructor] (A B : Type*) : pbool →* (A +* B) := pmap.mk (sum_of_bool A B) idp -- move to wedge definition wedge_equiv_pushout_sum [constructor] (A B : Type*) : wedge A B ≃ cofiber (sum_of_bool A B) := begin refine pushout_const_equiv _ _ ⬝e _, fapply pushout.equiv, exact bool_equiv_unit_sum_unit⁻¹ᵉ, reflexivity, reflexivity, intro x, induction x: reflexivity, intro x, induction x with u u: induction u; reflexivity end section open prod.ops /- products preserve pushouts -/ definition pushout_prod_equiv_to [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (xd : pushout f g × D) : pushout (prod_functor f (@id D)) (prod_functor g id) := begin induction xd with x d, induction x with b c a, { exact inl (b, d) }, { exact inr (c, d) }, { exact glue (a, d) } end definition pushout_prod_equiv_from [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (x : pushout (prod_functor f (@id D)) (prod_functor g id)) : pushout f g × D := begin induction x with bd cd ad, { exact (inl bd.1, bd.2) }, { exact (inr cd.1, cd.2) }, { exact prod_eq (glue ad.1) idp } end definition pushout_prod_equiv {A B C D : Type} (f : A → B) (g : A → C) : pushout f g × D ≃ pushout (prod_functor f (@id D)) (prod_functor g id) := begin fapply equiv.MK, { exact pushout_prod_equiv_to }, { exact pushout_prod_equiv_from }, { intro x, induction x with bd cd ad, { induction bd, reflexivity }, { induction cd, reflexivity }, { induction ad with a d, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_prod_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, esimp, exact !ap_prod_elim ⬝ !idp_con ⬝ !elim_glue }}, { intro xd, induction xd with x d, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose (pushout_prod_equiv_from ∘ pushout_prod_equiv_to) _ _ ⬝ _, refine ap02 _ !ap_prod_mk_left ⬝ !ap_compose ⬝ _, refine ap02 _ (!ap_prod_elim ⬝ !idp_con ⬝ !elim_glue) ⬝ _, refine !elim_glue ⬝ !ap_prod_mk_left⁻¹ }} end end /- interaction of pushout and sums -/ definition pushout_to_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout f g) : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin induction x with b c a, { exact inl (sum.inl b) }, { exact inr c }, { exact glue (sum.inl a) } end definition pushout_from_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀))) : pushout f g := begin induction x with x c x, { induction x with b d, exact inl b, exact inr c₀ }, { exact inr c }, { induction x with a d, exact glue a, reflexivity } end /- The pushout of B <-- A --> C is the same as the pushout of B + D <-- A + D --> C -/ definition pushout_sum_cancel_equiv [constructor] {A B C : Type} (f : A → B) (g : A → C) (D : Type) (c₀ : C) : pushout f g ≃ pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin fapply equiv.MK, { exact pushout_to_sum D c₀ }, { exact pushout_from_sum D c₀ }, { intro x, induction x with x c x, { induction x with b d, reflexivity, esimp, exact (glue (sum.inr d))⁻¹ }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose (pushout_to_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with a d: esimp, { exact hdeg_square !elim_glue }, { exact square_of_eq !con.left_inv }}}, { intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (pushout_from_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ !elim_glue }} end end pushout namespace pushout variables {A A' B B' C C' : Type} {f : A → B} {g : A → C} {f' : A' → B'} {g' : A' → C'} definition sum_pushout_of_pushout_sum [unfold 11] (x : pushout (sum_functor f f') (sum_functor g g')) : pushout f g ⊎ pushout f' g' := begin induction x with b c a, { exact sum_functor inl inl b }, { exact sum_functor inr inr c }, { induction a with a a', exact ap sum.inl (glue a), exact ap sum.inr (glue a') } end definition pushout_sum_of_sum_pushout [unfold 11] (x : pushout f g ⊎ pushout f' g') : pushout (sum_functor f f') (sum_functor g g') := begin induction x with x x, { exact pushout.functor sum.inl sum.inl sum.inl homotopy.rfl homotopy.rfl x }, { exact pushout.functor sum.inr sum.inr sum.inr homotopy.rfl homotopy.rfl x } end variables (f g f' g') /- do we want to define this in terms of sigma_pushout? One possible disadvantage is that the computation on glue is less convenient -/ definition pushout_sum_equiv_sum_pushout [constructor] : pushout (sum_functor f f') (sum_functor g g') ≃ pushout f g ⊎ pushout f' g' := equiv.MK sum_pushout_of_pushout_sum pushout_sum_of_sum_pushout abstract begin intro x, induction x with x x, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, end end abstract begin intro x, induction x with b c a, { induction b: reflexivity }, { induction c: reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sum_of_sum_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': (apply hdeg_square; refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con) } end end variables {f g f' g'} variables {D E F D' E' F' : Type} {h : D → E} {i : D → F} {h' : D' → E'} {i' : D' → F'} {j : A → D} {k : B → E} {l : C → F} {j' : A' → D'} {k' : B' → E'} {l' : C' → F'} {j₂ : A' → D} {k₂ : B' → E} {l₂ : C' → F} (s : hsquare f h j k) (t : hsquare g i j l) (s' : hsquare f' h' j' k') (t' : hsquare g' i' j' l') (s₂ : hsquare f' h j₂ k₂) (t₂ : hsquare g' i j₂ l₂) definition sum_rec_pushout_sum_equiv_sum_pushout : sum.rec (pushout.functor j k l s t) (pushout.functor j₂ k₂ l₂ s₂ t₂) ∘ pushout_sum_equiv_sum_pushout f g f' g' ~ pushout.functor (sum.rec j j₂) (sum.rec k k₂) (sum.rec l l₂) (sum_rec_hsquare s s₂) (sum_rec_hsquare t t₂) := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': exact hdeg_square (!ap_compose'⁻¹ ⬝ !elim_glue ⬝ !elim_glue⁻¹) end end } end definition pushout_sum_equiv_sum_pushout_natural : hsquare (pushout.functor (j +→ j') (k +→ k') (l +→ l') (sum_functor_hsquare s s') (sum_functor_hsquare t t')) (pushout.functor j k l s t +→ pushout.functor j' k' l' s' t') (pushout_sum_equiv_sum_pushout f g f' g') (pushout_sum_equiv_sum_pushout h i h' i') := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _ ⬝hp (!ap_compose ⬝ ap02 _ !elim_glue)⁻¹, refine !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ !ap_inv) ⬝ph _, induction a with a a', { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inl _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inl _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inl _ _) ⬝ !ap_con⁻¹ }, { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inr _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inr _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inr _ _) ⬝ !ap_con⁻¹ } end end } end end pushout namespace pushout open sigma sigma.ops variables {X : Type} {A B C : X → Type} {f : Πx, A x → B x} {g : Πx, A x → C x} definition sigma_pushout_of_pushout_sigma [unfold 7] (x : pushout (total f) (total g)) : Σx, pushout (f x) (g x) := begin induction x with b c a, { exact total (λx, inl) b }, { exact total (λx, inr) c }, { exact sigma_eq_right (glue a.2) } end definition pushout_sigma_of_sigma_pushout [unfold 7] (x : Σx, pushout (f x) (g x)) : pushout (total f) (total g) := pushout.functor (dpair x.1) (dpair x.1) (dpair x.1) homotopy.rfl homotopy.rfl x.2 variables (f g) definition pushout_sigma_equiv_sigma_pushout [constructor] : pushout (total f) (total g) ≃ Σx, pushout (f x) (g x) := equiv.MK sigma_pushout_of_pushout_sigma pushout_sigma_of_sigma_pushout abstract begin intro x, induction x with x y, induction y with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sigma_pushout_of_pushout_sigma _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue } end end abstract begin intro x, induction x with b c a, { induction b, reflexivity }, { induction c, reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sigma_of_sigma_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a', apply hdeg_square, refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con } end end variables {f g} variables {X' : Type} {A' B' C' : X' → Type} {f' : Πx, A' x → B' x} {g' : Πx, A' x → C' x} {s : X → X'} {h₁ : Πx, A x → A' (s x)} {h₂ : Πx, B x → B' (s x)} {h₃ : Πx, C x → C' (s x)} (p : Πx, h₂ x ∘ f x ~ f' (s x) ∘ h₁ x) (q : Πx, h₃ x ∘ g x ~ g' (s x) ∘ h₁ x) definition pushout_sigma_equiv_sigma_pushout_natural : hsquare (pushout.functor (sigma_functor s h₁) (sigma_functor s h₂) (sigma_functor s h₃) (λa, sigma_eq_right (p a.1 a.2)) (λa, sigma_eq_right (q a.1 a.2))) (sigma_functor s (λx, pushout.functor (h₁ x) (h₂ x) (h₃ x) (p x) (q x))) (pushout_sigma_equiv_sigma_pushout f g) (pushout_sigma_equiv_sigma_pushout f' g') := begin intro x, induction x with b c a, { reflexivity }, { reflexivity }, { exact abstract begin apply eq_pathover, apply hdeg_square, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_compose'⁻¹) ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ ap02 _ !ap_inv⁻¹ ⬝ !ap_compose'⁻¹) ⬝ _, exact (ap_compose (sigma_functor s (λ x, pushout.functor (h₁ x) (h₂ x) (h₃ x) (p x) (q x))) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_compose'⁻¹ ⬝ ap_compose (dpair _) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ idp) ◾ !ap_compose'⁻¹)⁻¹ end end } end /- an induction principle for the cofiber of f : A → B if A is a pushout where the second map has a section. The Pgluer is modified to get the right coherence See https://github.com/HoTT/HoTT-Agda/blob/master/theorems/homotopy/elims/CofPushoutSection.agda -/ open sigma.ops definition cofiber_pushout_helper' {A : Type} {B : A → Type} {a₀₀ a₀₂ a₂₀ a₂₂ : A} {p₀₁ : a₀₀ = a₀₂} {p₁₀ : a₀₀ = a₂₀} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂} {s : square p₀₁ p₂₁ p₁₀ p₁₂} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ b₂₂' : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂'} {q₁₂ : b₀₂ =[p₁₂] b₂₂} : Σ(r : b₂₂' = b₂₂), squareover B s q₀₁ (r ▸ q₂₁) q₁₀ q₁₂ := begin induction s, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₀ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idp, idso⟩ end definition cofiber_pushout_helper {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} {Pcod : Πd, P (cofiber.cod h d)} {Pbase : P (cofiber.base h)} (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (a : A) : Σ(p : Pbase = Pbase), squareover P (natural_square cofiber.glue (glue a)) (Pgluel (f a)) (p ▸ Pgluer (g a)) (pathover_ap P (λa, cofiber.cod h (h a)) (apd (λa, Pcod (h a)) (glue a))) (pathover_ap P (λa, cofiber.base h) (apd (λa, Pbase) (glue a))) := !cofiber_pushout_helper' definition cofiber_pushout_rec {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} (Pcod : Πd, P (cofiber.cod h d)) (Pbase : P (cofiber.base h)) (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (r : C → A) (p : Πa, r (g a) = a) (x : cofiber h) : P x := begin induction x with d x, { exact Pcod d }, { exact Pbase }, { induction x with b c a, { exact Pgluel b }, { exact (cofiber_pushout_helper Pgluel Pgluer (r c)).1 ▸ Pgluer c }, { apply pathover_pathover, rewrite [p a], exact (cofiber_pushout_helper Pgluel Pgluer a).2 }} end /- universal property of cofiber -/ definition cofiber_exact_1 {X Y Z : Type*} (f : X →* Y) (g : pcofiber f →* Z) : (g ∘* pcod f) ∘* f ~* pconst X Z := !passoc ⬝* pwhisker_left _ !pcod_pcompose ⬝* !pcompose_pconst protected definition pcofiber.elim [constructor] {X Y Z : Type*} {f : X →* Y} (g : Y →* Z) (p : g ∘* f ~* pconst X Z) : pcofiber f →* Z := begin fapply pmap.mk, { intro w, induction w with y x, exact g y, exact pt, exact p x }, { reflexivity } end protected definition pcofiber.elim_pcod {X Y Z : Type*} {f : X →* Y} {g : Y →* Z} (p : g ∘* f ~* pconst X Z) : pcofiber.elim g p ∘* pcod f ~* g := begin fapply phomotopy.mk, { intro y, reflexivity }, { esimp, refine !idp_con ⬝ _, refine _ ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_inv) ◾ !elim_glue)⁻¹, apply eq_inv_con_of_con_eq, exact (to_homotopy_pt p)⁻¹ } end /- The maps Z^{C_f} --> Z^Y --> Z^X are exact at Z^Y. Here Y^X means pointed maps from X to Y and C_f is the cofiber of f. The maps are given by precomposing with (pcod f) and f. -/ definition cofiber_exact {X Y Z : Type*} (f : X →* Y) : is_exact_t (@ppcompose_right _ _ Z (pcod f)) (ppcompose_right f) := begin constructor, { intro g, apply eq_of_phomotopy, apply cofiber_exact_1 }, { intro g p, note q := phomotopy_of_eq p, exact fiber.mk (pcofiber.elim g q) (eq_of_phomotopy (pcofiber.elim_pcod q)) } end /- cofiber of pcod is suspension -/ definition pcofiber_pcod {A B : Type*} (f : A →* B) : pcofiber (pcod f) ≃* susp A := begin fapply pequiv_of_equiv, { refine !pushout.symm ⬝e _, exact pushout_vcompose_equiv f equiv.rfl homotopy.rfl homotopy.rfl }, reflexivity end -- definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : -- pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := -- definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : -- pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := -- definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} -- {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : -- pushout h k ≃ pushout hf g := end pushout namespace pushout /- define the quotient using pushout -/ section open quotient sigma.ops variables {A B : Type} (R : A → A → Type) {Q : B → B → Type} (f : A → B) (k : Πa a' : A, R a a' → Q (f a) (f a')) definition pushout_quotient {A : Type} (R : A → A → Type) : Type := @pushout ((Σa a', R a a') ⊎ (Σa a', R a a')) A (Σa a', R a a') (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) variable {R} definition pushout_quotient_of_quotient [unfold 3] (x : quotient R) : pushout_quotient R := begin induction x with a a a' r, { exact inl a }, { exact glue (sum.inl ⟨a, a', r⟩) ⬝ (glue (sum.inr ⟨a, a', r⟩))⁻¹ } end definition quotient_of_pushout_quotient [unfold 3] (x : pushout_quotient R) : quotient R := begin induction x with a x x, { exact class_of R a }, { exact class_of R x.2.1 }, { induction x with x x, exact eq_of_rel R x.2.2, reflexivity } end variable (R) definition quotient_equiv_pushout [constructor] : quotient R ≃ pushout_quotient R := equiv.MK pushout_quotient_of_quotient quotient_of_pushout_quotient abstract begin intro x, induction x with a x x, { reflexivity }, { exact glue (sum.inr x) }, { apply eq_pathover_id_right, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with x x, { refine !elim_eq_of_rel ⬝ph _, induction x with a x, induction x with a' r, exact whisker_bl _ hrfl }, { exact square_of_eq idp }} end end abstract begin intro x, induction x, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose quotient_of_pushout_quotient _ _ ⬝ ap02 _ !elim_eq_of_rel ⬝ _, exact !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) } end end variable {R} definition sigma_functor2 [unfold 7] : (Σ a a', R a a') → (Σ b b', Q b b') := sigma_functor f (λa, sigma_functor f (k a)) definition pushout_quotient_functor [unfold 7] : pushout_quotient R → pushout_quotient Q := let tf := sigma_functor2 f k in pushout.functor (sum_functor tf tf) f tf begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end definition quotient_equiv_pushout_natural : hsquare (quotient.functor _ _ f k) (pushout_quotient_functor f k) (quotient_equiv_pushout R) (quotient_equiv_pushout Q) := begin intro x, induction x with a a a' r, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ _ ⬝ (ap_compose (pushout.functor _ _ _ _ _) _ _)⁻¹, refine ap02 _ !elim_eq_of_rel ⬝ _ ⬝ (ap02 _ !elim_eq_of_rel)⁻¹, refine !elim_eq_of_rel ⬝ _, exact (!ap_con ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con) ◾ (!ap_inv ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con)⁻²))⁻¹ } end end end pushout
f44ce250f2d7957bb22c456b62a723e40ad74c3d
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/tidy/rewrite_search/metric/trivial.lean
170289297b9a4b9fe2aff2e39b3a426e484a63f7
[ "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
1,031
lean
import tidy.rewrite_search.core -- The trivial metric: I just report that every vertex is distance zero from every other. open tidy.rewrite_search namespace tidy.rewrite_search.metric.trivial variables {α δ : Type} (g : search_state α unit unit δ) meta def trivial_init : tactic (init_result unit) := init_result.pure () meta def trivial_update (itr : ℕ) : tactic (search_state α unit unit δ) := return g meta def trivial_init_bound (_ : search_state α unit unit δ) (l r : vertex) : bound_progress unit := bound_progress.exactly 0 () meta def trivial_improve_estimate_over (_ : search_state α unit unit δ) (m : ℚ) (l r : vertex) (bnd : bound_progress unit) : bound_progress unit := bound_progress.exactly 0 () end tidy.rewrite_search.metric.trivial namespace tidy.rewrite_search.metric open tidy.rewrite_search.metric.trivial meta def trivial : metric_constructor unit unit := λ α δ, ⟨ trivial_init, trivial_update, trivial_init_bound, trivial_improve_estimate_over ⟩ end tidy.rewrite_search.metric
42815de860280fc64ad15d85e6845863bd47bd1e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/hlist.lean
e200129674dbd2a555ef5921a161970f6cbeeb27
[ "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
2,928
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 Heterogeneous lists -/ import data.list logic.cast open list inductive hlist {A : Type} (B : A → Type) : list A → Type := | nil {} : hlist B [] | cons : ∀ {a : A}, B a → ∀ {l : list A}, hlist B l → hlist B (a::l) namespace hlist variables {A : Type} {B : A → Type} definition head : Π {a l}, hlist B (a :: l) → B a | a l (cons b h) := b lemma head_cons : ∀ {a l} (b : B a) (h : hlist B l), head (cons b h) = b := sorry -- by intros; reflexivity definition tail : Π {a l}, hlist B (a :: l) → hlist B l | a l (cons b h) := h lemma tail_cons : ∀ {a l} (b : B a) (h : hlist B l), tail (cons b h) = h := sorry -- by intros; reflexivity lemma eta_cons : ∀ {a l} (h : hlist B (a::l)), h = cons (head h) (tail h) := sorry -- begin intros, cases h, esimp end lemma eta_nil : ∀ (h : hlist B []), h = nil := sorry -- begin intros, cases h, esimp end definition append : Π {l₁ l₂}, hlist B l₁ → hlist B l₂ → hlist B (l₁++l₂) | [] l₂ nil h₂ := h₂ | (a::l) l₂ (cons b h₁) h₂ := cons b (append h₁ h₂) lemma append_nil_left : ∀ {l} (h : hlist B l), append nil h = h := sorry -- by intros; reflexivity lemma eq_rec_on_cons : ∀ {a₁ a₂ l₁ l₂} (b : B a₁) (h : hlist B l₁) (e : a₁::l₁ = a₂::l₂), eq.rec_on e (cons b h) = cons (eq.rec_on (head_eq_of_cons_eq e) b) (eq.rec_on (tail_eq_of_cons_eq e) h) := sorry /- begin intros, injection e with e₁ e₂, revert e, subst a₂, subst l₂, intro e, esimp end -/ local attribute list.append [reducible] lemma append_nil_right : ∀ {l} (h : hlist B l), append h nil = eq.rec_on (eq.symm (list.append_nil_right l)) h := sorry /- | [] nil := by esimp | (a::l) (cons b h) := begin change (cons b (append h nil)) = (eq.symm (list.append_nil_right (a :: l))) ▹ cons b h, rewrite [append_nil_right h], xrewrite eq_rec_on_cons end -/ lemma append_nil_right_heq {l} (h : hlist B l) : append h nil == h := sorry -- by rewrite append_nil_right; apply eq_rec_heq section get variables [decA : decidable_eq A] include decA definition get {a : A} : ∀ {l : list A}, hlist B l → a ∈ l → B a | [] nil e := absurd e (not_mem_nil a) | (t::l) (cons b h) e := or.by_cases (eq_or_mem_of_mem_cons e) (suppose a = t, eq.rec_on (eq.symm this) b) (suppose a ∈ l, get h this) end get section map variable {C : A → Type} variable (f : Π ⦃a⦄, B a → C a) definition map : ∀ {l}, hlist B l → hlist C l | [] nil := nil | (a::l) (cons b h) := cons (f b) (map h) lemma map_nil : map f nil = nil := rfl lemma map_cons : ∀ {a l} (b : B a) (h : hlist B l), map f (cons b h) = cons (f b) (map f h) := sorry -- by intros; reflexivity end map end hlist
496ba9f0028efd837a62afa5a8b2e2974cf13895
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/linear_algebra/basis.lean
b892c31ded9031a1f5aeba906a1b7b31eb1120bc
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
53,572
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, Alexander Bentkamp -/ import linear_algebra.finsupp import order.zorn import data.fintype.card /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type*} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, s.sum (λ i, g i • v i) = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (s.sum $ λ i, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = s.sum (λ j, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j))) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = s.sum (λ j, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma ne_zero_of_linear_independent {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' l.support.to_set : set s) l.support.to_set, { apply bij_on.mk, { unfold maps_to }, { apply subtype.val_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_val], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' finset.to_set (l.support)) (finset.to_set (l.support)), { apply bij_on.mk, { unfold maps_to }, { apply (linear_independent.injective zero_eq_one hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ subtype.val : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent_union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin haveI := classical.dec (nonempty η), by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], apply linear_independent_union, { apply hl }, { apply ih }, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' s.to_set), exact finite_preimage (assume i j _ _, plift.up.inj) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim (ne_zero_of_linear_independent zero_eq_one (hindep x₁) h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent_inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin apply linear_independent_union, exact (hs.image_subtype $ by simp), exact (ht.image_subtype $ by simp), rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact injective_comp prod.injective_inl inj_v }, { exact injective_comp prod.injective_inr inj_v' }, { intros, simp [ne_zero_of_linear_independent zero_eq_one hv] } }, { rw sum.elim_range, apply linear_independent_union, { apply linear_independent.to_subtype_range, apply linear_independent.image hv, simp [ker_inl] }, { apply linear_independent.to_subtype_range, apply linear_independent.image hv', simp [ker_inr] }, { apply disjoint_inl_inr.mono _ _, { rw [set.range_comp, span_image], apply linear_map.map_le_range }, { rw [set.range_comp, span_image], apply linear_map.map_le_range } } } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. s.sum (λ i, ((g i * i x - g i * a x) • i : G → L)) y = s.sum (λ i, (g i * i x - g i * a x) * i y) : pi.finset_sum_apply _ _ _ ... = s.sum (λ i, g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = s.sum (λ i, g i * i x * i y) - s.sum (λ i, g i * a x * i y) : finset.sum_sub_distrib ... = (g a * a x * a y + s.sum (λ i, g i * i x * i y)) - (g a * a x * a y + s.sum (λ i, g i * a x * i y)) : by rw add_sub_add_left_eq_sub ... = (insert a s).sum (λ i, g i * i x * i y) - (insert a s).sum (λ i, g i * a x * i y) : by rw [finset.sum_insert has, finset.sum_insert has] ... = (insert a s).sum (λ i, g i * i (x * y)) - (insert a s).sum (λ i, a x * (g i * i y)) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (insert a s).sum (λ i, (g i • i : G → L)) (x * y) - a x * (insert a s).sum (λ i, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (insert a s).sum (λ i, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} {f : M → M'} {g : M' → M} (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, add := λ x y, by ext; exact finsupp.add_apply, smul := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) : (equiv_fun_basis h).symm x = finset.sum finset.univ (λi, x i • v i) := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = finset.sum finset.univ (λi, x i • v i), dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply linear_independent_union hs (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, haveI := classical.dec (x ∈ span K b), by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (λ i : b, i.val) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i : b, i.val) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one K _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin letI := classical.dec_pred (λx, x ∈ s), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp *, finish }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : V →ₗ[K] V'} (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), have h₂ : range (λ (i : B), i.val) = B := subtype.range_val B, rwa h₂ at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hB, intros b, rw image_subset_iff at BC, simp, have := BC (subtype.mem b), rw mem_preimage at this, have : f (b.val) = (subtype.mk (f ↑b) (begin rw ←mem_preimage, exact BC (subtype.mem b) end) : C).val, by simp; unfold_coes, rw this, rw [constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _, end lemma exists_right_inverse_linear_map_of_surjective {f : V →ₗ[K] V'} (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hC, intros c, simp [constr_basis hC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := begin haveI := classical.dec_eq (quotient p), rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.coprod p.subtype) (p.mkq.prod (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa [sub_eq_add_neg, add_left_comm] using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end open fintype theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := begin apply exists.elim (exists_is_basis K V), intros b hb, haveI := classical.dec_pred (λ x, x ∈ b), use card b, exact module.card_fintype hb, end end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), (λ _, unit) j), (std_basis R (λ (i : η), R) (ji.fst)) 1) := begin haveI := classical.dec_eq, apply @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _), end lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply is_basis.comp (is_basis_fun₀ R η) (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use (λ x, x.1), simp [function.left_inverse, function.right_inverse], intros _ b, rw [unique.eq_default b, unique.eq_default punit.star] end end end module end pi
ca04bf179340aa9e034ad83b5c8691f97455f493
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/nested_match_bug.lean
7f37810f5bb853f8bfbf7a6b64127e521d9ae00d
[ "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
376
lean
inductive Term : Type | app : List Term -> Term namespace Term instance : Inhabited Term := ⟨app []⟩ partial def transform (f : Term -> Option Term) : Term -> Term | t => match f t with | some u => transform f u | none => match t with | app args => let newArgs := args.map (fun arg => transform f arg); transform f (app newArgs) end Term
881e1c28107d46c8ca04b95b39c06a85e58d3d68
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/data/string/basic.lean
42929583f08f1ea7102e8ee22e39a98ace30a903
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
8,455
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic import init.data.char.basic /- In the VM, strings are implemented using a dynamic array and UTF-8 encoding. TODO: we currently cannot mark string_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure string_imp := (data : list char) def string := string_imp def list.as_string (s : list char) : string := ⟨s⟩ namespace string instance : has_lt string := ⟨λ s₁ s₂, s₁.data < s₂.data⟩ /- Remark: this function has a VM builtin efficient implementation. -/ instance has_decidable_lt (s₁ s₂ : string) : decidable (s₁ < s₂) := list.has_decidable_lt s₁.data s₂.data def empty : string := ⟨[]⟩ def length : string → nat | ⟨s⟩ := s.length /- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def push : string → char → string | ⟨s⟩ c := ⟨s ++ [c]⟩ /- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def append : string → string → string | ⟨a⟩ ⟨b⟩ := ⟨a ++ b⟩ /- O(n) in the VM, where n is the length of the string -/ def to_list : string → list char | ⟨s⟩ := s def fold {α} (a : α) (f : α → char → α) (s : string) : α := s.to_list.foldl f a /- In the VM, the string iterator is implemented as a pointer to the string being iterated + index. TODO: we currently cannot mark interator_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure iterator_imp := (fst : list char) (snd : list char) def iterator := iterator_imp def mk_iterator : string → iterator | ⟨s⟩ := ⟨[], s⟩ namespace iterator def curr : iterator → char | ⟨p, c::n⟩ := c | _ := default char /- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time if it is. -/ def set_curr : iterator → char → iterator | ⟨p, c::n⟩ c' := ⟨p, c'::n⟩ | it c' := it def next : iterator → iterator | ⟨p, c::n⟩ := ⟨c::p, n⟩ | ⟨p, []⟩ := ⟨p, []⟩ def prev : iterator → iterator | ⟨c::p, n⟩ := ⟨p, c::n⟩ | ⟨[], n⟩ := ⟨[], n⟩ def has_next : iterator → bool | ⟨p, []⟩ := ff | _ := tt def has_prev : iterator → bool | ⟨[], n⟩ := ff | _ := tt def insert : iterator → string → iterator | ⟨p, n⟩ ⟨s⟩ := ⟨p, s++n⟩ def remove : iterator → nat → iterator | ⟨p, n⟩ m := ⟨p, n.drop m⟩ /- In the VM, `to_string` is a constant time operation. -/ def to_string : iterator → string | ⟨p, n⟩ := ⟨p.reverse ++ n⟩ def to_end : iterator → iterator | ⟨p, n⟩ := ⟨n.reverse ++ p, []⟩ def next_to_string : iterator → string | ⟨p, n⟩ := ⟨n⟩ def prev_to_string : iterator → string | ⟨p, n⟩ := ⟨p.reverse⟩ protected def extract_core : list char → list char → option (list char) | [] cs := none | (c::cs₁) cs₂ := if cs₁ = cs₂ then some [c] else match extract_core cs₁ cs₂ with | none := none | some r := some (c::r) end def extract : iterator → iterator → option string | ⟨p₁, n₁⟩ ⟨p₂, n₂⟩ := if p₁.reverse ++ n₁ ≠ p₂.reverse ++ n₂ then none else if n₁ = n₂ then some "" else match iterator.extract_core n₁ n₂ with | none := none | some r := some ⟨r⟩ end end iterator end string /- The following definitions do not have builtin support in the VM -/ instance : inhabited string := ⟨string.empty⟩ instance : has_sizeof string := ⟨string.length⟩ instance : has_append string := ⟨string.append⟩ namespace string def str : string → char → string := push def is_empty (s : string) : bool := to_bool (s.length = 0) def front (s : string) : char := s.mk_iterator.curr def back (s : string) : char := s.mk_iterator.to_end.prev.curr def join (l : list string) : string := l.foldl (λ r s, r ++ s) "" def singleton (c : char) : string := empty.push c def intercalate (s : string) (ss : list string) : string := (list.intercalate s.to_list (ss.map to_list)).as_string namespace iterator def nextn : iterator → nat → iterator | it 0 := it | it (i+1) := nextn it.next i def prevn : iterator → nat → iterator | it 0 := it | it (i+1) := prevn it.prev i end iterator def pop_back (s : string) : string := s.mk_iterator.to_end.prev.prev_to_string def popn_back (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).prev_to_string def backn (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).next_to_string end string protected def char.to_string (c : char) : string := string.singleton c private def to_nat_core : string.iterator → nat → nat → nat | it 0 r := r | it (i+1) r := let c := it.curr in let r := r*10 + c.to_nat - '0'.to_nat in to_nat_core it.next i r def string.to_nat (s : string) : nat := to_nat_core s.mk_iterator s.length 0 namespace string private lemma nil_ne_append_singleton : ∀ (c : char) (l : list char), [] ≠ l ++ [c] | c [] := λ h, list.no_confusion h | c (d::l) := λ h, list.no_confusion h lemma empty_ne_str : ∀ (c : char) (s : string), empty ≠ str s c | c ⟨l⟩ := λ h : string_imp.mk [] = string_imp.mk (l ++ [c]), string_imp.no_confusion h $ λ h, nil_ne_append_singleton _ _ h lemma str_ne_empty (c : char) (s : string) : str s c ≠ empty := (empty_ne_str c s).symm private lemma str_ne_str_left_aux : ∀ {c₁ c₂ : char} (l₁ l₂ : list char), c₁ ≠ c₂ → l₁ ++ [c₁] ≠ l₂ ++ [c₂] | c₁ c₂ [] [] h₁ h₂ := list.no_confusion h₂ (λ h _, absurd h h₁) | c₁ c₂ (d₁::l₁) [] h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = [c₂], from h₂, have l₁ ++ [c₁] = [], from list.no_confusion this (λ _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ c₂ [] (d₂::l₂) h₁ h₂ := have [c₁] = d₂ :: (l₂ ++ [c₂]), from h₂, have [] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ c₂ (d₁::l₁) (d₂::l₂) h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = d₂ :: (l₂ ++ [c₂]), from h₂, have l₁ ++ [c₁] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (str_ne_str_left_aux l₁ l₂ h₁) lemma str_ne_str_left : ∀ {c₁ c₂ : char} (s₁ s₂ : string), c₁ ≠ c₂ → str s₁ c₁ ≠ str s₂ c₂ | c₁ c₂ (string_imp.mk l₁) (string_imp.mk l₂) h₁ h₂ := have l₁ ++ [c₁] = l₂ ++ [c₂], from string_imp.no_confusion h₂ id, absurd this (str_ne_str_left_aux l₁ l₂ h₁) private lemma str_ne_str_right_aux : ∀ (c₁ c₂ : char) {l₁ l₂ : list char}, l₁ ≠ l₂ → l₁ ++ [c₁] ≠ l₂ ++ [c₂] | c₁ c₂ [] [] h₁ h₂ := absurd rfl h₁ | c₁ c₂ (d₁::l₁) [] h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = [c₂], from h₂, have l₁ ++ [c₁] = [], from list.no_confusion this (λ _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ c₂ [] (d₂::l₂) h₁ h₂ := have [c₁] = d₂ :: (l₂ ++ [c₂]), from h₂, have [] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ c₂ (d₁::l₁) (d₂::l₂) h₁ h₂ := have aux₁ : d₁ :: (l₁ ++ [c₁]) = d₂ :: (l₂ ++ [c₂]), from h₂, have d₁ = d₂, from list.no_confusion aux₁ (λ h _, h), have aux₂ : l₁ ≠ l₂, from λ h, have d₁ :: l₁ = d₂ :: l₂, from eq.subst h (eq.subst this rfl), absurd this h₁, have l₁ ++ [c₁] = l₂ ++ [c₂], from list.no_confusion aux₁ (λ _ h, h), absurd this (str_ne_str_right_aux c₁ c₂ aux₂) lemma str_ne_str_right : ∀ (c₁ c₂ : char) {s₁ s₂ : string}, s₁ ≠ s₂ → str s₁ c₁ ≠ str s₂ c₂ | c₁ c₂ (string_imp.mk l₁) (string_imp.mk l₂) h₁ h₂ := have aux : l₁ ≠ l₂, from λ h, have string_imp.mk l₁ = string_imp.mk l₂, from eq.subst h rfl, absurd this h₁, have l₁ ++ [c₁] = l₂ ++ [c₂], from string_imp.no_confusion h₂ id, absurd this (str_ne_str_right_aux c₁ c₂ aux) end string
e6de7428c6a3b1eaf397c2186eec649c3df98a3a
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Meta/Tactic/Apply.lean
75b96d0dd950c1a60cd0ff7db852e02892f94e80
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,288
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindMVar import Lean.Meta.ExprDefEq import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Util namespace Lean.Meta /- Compute the number of expected arguments and whether the result type is of the form (?m ...) where ?m is an unassigned metavariable. -/ private def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) := withReducible $ forallTelescopeReducing e fun xs body => pure (xs.size, body.getAppFn.isMVar) private def getExpectedNumArgs (e : Expr) : MetaM Nat := do let (numArgs, _) ← getExpectedNumArgsAux e pure numArgs private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α := throwTacticEx `apply mvarId m!"failed to unify{indentExpr eType}\nwith{indentExpr targetType}" def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := newMVars.size.forM fun i => do if binderInfos[i].isInstImplicit then let mvar := newMVars[i] let mvarType ← inferType mvar let mvarVal ← synthInstance mvarType unless (← isDefEq mvar mvarVal) do throwTacticEx tacticName mvarId "failed to assign synthesized instance" def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do let parentTag ← getMVarTag mvarId if newMVars.size == 1 then -- if there is only one subgoal, we inherit the parent tag setMVarTag newMVars[0].mvarId! parentTag else unless parentTag.isAnonymous do newMVars.size.forM fun i => do let newMVarId := newMVars[i].mvarId! unless (← isExprMVarAssigned newMVarId) do unless binderInfos[i].isInstImplicit do let currTag ← getMVarTag newMVarId setMVarTag newMVarId (appendTag parentTag currTag) def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do synthAppInstances tacticName mvarId newMVars binderInfos -- TODO: default and auto params appendParentTag mvarId newMVars binderInfos private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool := otherMVars.anyM fun otherMVar => do if mvar == otherMVar then pure false else let otherMVarType ← inferType otherMVar return (otherMVarType.findMVar? fun mvarId => mvarId == mvar.mvarId!).isSome private def reorderNonDependentFirst (newMVars : Array Expr) : MetaM (List MVarId) := do let (nonDeps, deps) ← newMVars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do let currMVarId := mvar.mvarId! if (← dependsOnOthers mvar newMVars) then pure (nonDeps, deps.push currMVarId) else pure (nonDeps.push currMVarId, deps) return nonDeps.toList ++ deps.toList inductive ApplyNewGoals where | nonDependentFirst | nonDependentOnly | all def apply (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := withMVarContext mvarId do checkNotAssigned mvarId `apply let targetType ← getMVarType mvarId let eType ← inferType e let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType if hasMVarHead then let targetTypeNumArgs ← getExpectedNumArgs targetType numArgs := numArgs - targetTypeNumArgs let (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs) unless (← isDefEq eType targetType) do throwApplyError mvarId eType targetType postprocessAppMVars `apply mvarId newMVars binderInfos let e ← instantiateMVars e assignExprMVar mvarId (mkAppN e newMVars) let newMVars ← newMVars.filterM fun mvar => not <$> isExprMVarAssigned mvar.mvarId! let otherMVarIds ← getMVarsNoDelayed e -- TODO: add option `ApplyNewGoals` and implement other orders let newMVarIds ← reorderNonDependentFirst newMVars let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId let result := newMVarIds ++ otherMVarIds.toList result.forM headBetaMVarType return result end Lean.Meta
712092b8c3e749ec96d5161829d9a541aa56f7f5
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/calculus/fderiv_analytic.lean
d05088dc5487c336b2dd391433e1ed3af1faad77
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
2,861
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 analysis.calculus.deriv import analysis.analytic.basic /-! # Frechet derivatives of analytic functions. A function expressible as a power series at a point has a Frechet derivative there. Also the special case in terms of `deriv` when the domain is 1-dimensional. -/ open filter asymptotics open_locale ennreal variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] section fderiv variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞} variables {f : E → F} {x : E} {s : set E} lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) : has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := begin refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _), refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩, refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _, rw [_root_.id, sub_self, norm_zero] end lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := h.has_strict_fderiv_at.has_fderiv_at lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x | ⟨p, hp⟩ := hp.differentiable_at lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma has_fpower_series_at.fderiv (h : has_fpower_series_at f p x) : fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) := h.has_fderiv_at.fderiv lemma has_fpower_series_on_ball.differentiable_on [complete_space F] (h : has_fpower_series_on_ball f p x r) : differentiable_on 𝕜 f (emetric.ball x r) := λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at end fderiv section deriv variables {p : formal_multilinear_series 𝕜 𝕜 F} {r : ℝ≥0∞} variables {f : 𝕜 → F} {x : 𝕜} protected lemma has_fpower_series_at.has_strict_deriv_at (h : has_fpower_series_at f p x) : has_strict_deriv_at f (p 1 (λ _, 1)) x := h.has_strict_fderiv_at.has_strict_deriv_at protected lemma has_fpower_series_at.has_deriv_at (h : has_fpower_series_at f p x) : has_deriv_at f (p 1 (λ _, 1)) x := h.has_strict_deriv_at.has_deriv_at protected lemma has_fpower_series_at.deriv (h : has_fpower_series_at f p x) : deriv f x = p 1 (λ _, 1) := h.has_deriv_at.deriv end deriv
870afbb6517863fedb9b4aba3fb3630e1374bafb
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/algebra/ordered.lean
44f4dbdc8118063064f1fa3c3c4661a6acdefcca
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
44,537
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 ordered topology. -/ import order.liminf_limsup import data.set.intervals import topology.algebra.group import topology.constructions open classical set lattice filter topological_space local attribute [instance] classical.prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- (Partially) ordered topology Also called: partially ordered spaces (pospaces). Usually ordered topology is used for a topology on linear ordered spaces, where the open intervals are open sets. This is a generalization as for each linear order where open interals are open sets, the order relation is closed. -/ class ordered_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed (λp:α×α, p.1 ≤ p.2)) instance {α : Type*} : Π [topological_space α], topological_space (order_dual α) := id section ordered_topology section preorder variables [topological_space α] [preorder α] [t : ordered_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id instance : ordered_topology (order_dual α) := ⟨continuous_swap _ (@ordered_topology.is_closed_le' α _ _ _)⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter (is_closed_ge' a) (is_closed_le' b) lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) (h : {b | f b ≤ g b} ∈ b) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (nhds (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from mem_of_closed_of_tendsto hb this t.is_closed_le' h lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | c ≤ b} ∈ x) : a ≤ b := le_of_tendsto_of_tendsto nt lim tendsto_const_nhds h lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | b ≤ c} ∈ x) : b ≤ a := le_of_tendsto_of_tendsto nt tendsto_const_nhds lim h @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := closure_eq_iff_is_closed.mpr $ is_closed_le hf hg end preorder section partial_order variables [topological_space α] [partial_order α] [t : ordered_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) instance ordered_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [t : ordered_topology α] include t lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf lemma is_open_Ioo {a b : α} : is_open (Ioo a b) := is_open_and (is_open_lt continuous_const continuous_id) (is_open_lt continuous_id continuous_const) lemma is_open_Iio {a : α} : is_open (Iio a) := is_open_lt continuous_id continuous_const end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [t : ordered_topology α] [topological_space β] {f g : β → α} include t section variables (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := assume b ⟨hb₁, hb₂⟩, le_antisymm (by simpa [closure_le_eq hf hg] using hb₁) (not_lt.1 $ assume hb : f b < g b, have {b | f b < g b} ⊆ interior {b | f b ≤ g b}, from (subset_interior_iff_subset_of_open $ is_open_lt hf hg).mpr $ assume x, le_of_lt, have b ∈ interior {b | f b ≤ g b}, from this hb, by exact hb₂ this) lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous_max : continuous (λb, max (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, g b = f b, from assume b hb, (frontier_le_subset_eq hf hg hb).symm, continuous_if this hg hf lemma continuous_min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg end lemma tendsto_max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, max (f b) (g b)) b (nhds (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (max a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_max continuous_fst continuous_snd) _ end (hf.prod_mk hg) lemma tendsto_min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, min (f b) (g b)) b (nhds (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (min a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_min continuous_fst continuous_snd) _ end (hf.prod_mk hg) end decidable_linear_order end ordered_topology /-- Topologies generated by the open intervals. This is restricted to linear orders. Only then it is guaranteed that they are also a ordered topology. -/ class orderable_topology (α : Type*) [t : topological_space α] [partial_order α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}}) section orderable_topology instance {α : Type*} [topological_space α] [partial_order α] [orderable_topology α] : orderable_topology (order_dual α) := ⟨by convert @orderable_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : orderable_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : {b | a < b} ∈ nhds b := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : {b | a ≤ b} ∈ nhds b := (nhds b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : {a | a < b} ∈ nhds a := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : {a | a ≤ b} ∈ nhds a := (nhds a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_orderable {a : α} : nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_orderable {f : β → α} {a : α} {x : filter β} : tendsto f x (nhds a) ↔ (∀a'<a, {b | a' < f b} ∈ x) ∧ (∀a'>a, {b | a' > f b} ∈ x) := by simp [@nhds_eq_orderable α _ _, tendsto_inf, tendsto_infi, tendsto_principal] /-- Also known as squeeze or sandwich theorem. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (nhds a)) (hh : tendsto h b (nhds a)) (hgf : {b | g b ≤ f b} ∈ b) (hfh : {b | f b ≤ h b} ∈ b) : tendsto f b (nhds a) := tendsto_orderable.2 ⟨assume a' h', have {b : β | a' < g b} ∈ b, from (tendsto_orderable.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have {b : β | h b < a'} ∈ b, from (tendsto_orderable.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ lemma nhds_orderable_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : nhds a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal {x | l < x ∧ x < u }) := let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in calc nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) : nhds_eq_orderable ... = (⨅b<a, principal {c | b < c} ⊓ (⨅b>a, principal {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, principal {c | c < u} ⊓ principal {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_orderable_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → {b | l < f b ∧ f b < u } ∈ x) : tendsto f x (nhds a) := by rw [nhds_orderable_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_orderable_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @orderable_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, @nhds_eq_orderable β _ _], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_orderable_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @orderable_topology _ (induced f ta) _ := induced_orderable_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) lemma nhds_top_orderable [topological_space α] [order_top α] [orderable_topology α] : nhds (⊤:α) = (⨅l (h₂ : l < ⊤), principal {x | l < x}) := by rw [@nhds_eq_orderable α _ _]; simp [(>)] lemma nhds_bot_orderable [topological_space α] [order_bot α] [orderable_topology α] : nhds (⊥:α) = (⨅l (h₂ : ⊥ < l), principal {x | x < l}) := by rw [@nhds_eq_orderable α _ _]; simp section linear_order variables [topological_space α] [linear_order α] [t : orderable_topology α] include t lemma mem_nhds_orderable_dest {a : α} {s : set α} (hs : s ∈ nhds a) : ((∃u, u>a) → ∃u, a < u ∧ ∀b, a ≤ b → b < u → b ∈ s) ∧ ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ≤ a → b ∈ s) := let ⟨t₁, ht₁, t₂, ht₂, hts⟩ := mem_inf_sets.mp $ by rw [@nhds_eq_orderable α _ _ _] at hs; exact hs in have ht₁ : ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ∈ t₁) ∧ (∀b, a ≤ b → b ∈ t₁), from infi_sets_induct ht₁ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' < a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨max u a', max_lt hu₁ h, assume b hb, ⟨hs₁ $ lt_of_le_of_lt (le_max_right _ _) hb, hu₂ _ $ lt_of_le_of_lt (le_max_left _ _) hb⟩⟩, assume b hb, ⟨hs₁ $ lt_of_lt_of_le h hb, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), have ht₂ : ((∃u, u>a) → ∃u, a < u ∧ ∀b, b < u → b ∈ t₂) ∧ (∀b, b ≤ a → b ∈ t₂), from infi_sets_induct ht₂ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' > a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨min u a', lt_min hu₁ h, assume b hb, ⟨hs₁ $ lt_of_lt_of_le hb (min_le_right _ _), hu₂ _ $ lt_of_lt_of_le hb (min_le_left _ _)⟩⟩, assume b hb, ⟨hs₁ $ lt_of_le_of_lt hb h, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), and.intro (assume hx, let ⟨u, hu, h⟩ := ht₂.left hx in ⟨u, hu, assume b hb hbu, hts ⟨ht₁.right b hb, h _ hbu⟩⟩) (assume hx, let ⟨l, hl, h⟩ := ht₁.left hx in ⟨l, hl, assume b hbl hb, hts ⟨h _ hbl, ht₂.right b hb⟩⟩) lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ nhds a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have nhds a = (⨅p : {l // l < a} × {u // a < u}, principal {x | p.1.val < x ∧ x < p.2.val }), by simp [nhds_orderable_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete h with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end instance orderable_topology.to_ordered_topology : ordered_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } instance orderable_topology.t2_space : t2_space α := by apply_instance instance orderable_topology.regular_space : regular_space α := { regular := assume s a hs ha, have -s ∈ nhds a, from mem_nhds_sets hs ha, let ⟨h₁, h₂⟩ := mem_nhds_orderable_dest this in have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := h₂ h in match dense_or_discrete hl with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h c (lt_of_lt_of_le hb₁ hbc) (le_of_lt hca) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := h₁ h in match dense_or_discrete hu with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h c (le_of_lt hca) (lt_of_le_of_lt hbc hb₂) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [←sup_principal, inf_sup_left, ht₁a, ht₂a, bot_sup_eq]⟩, ..orderable_topology.t2_space } end linear_order lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_comm_group α] [orderable_topology α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg') $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : mono_image $ image_closure_subset_closure_image continuous_neg' ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [orderable_topology α] [orderable_topology β] lemma nhds_principal_ne_bot_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : nhds a ⊓ principal s ≠ ⊥ := let ⟨a', ha'⟩ := exists_mem_of_ne_empty hs in forall_sets_neq_empty_iff_neq_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in let ⟨hu, hl⟩ := mem_nhds_orderable_dest ht₁ in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ne_empty_iff_exists_mem.mpr ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := hl ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right _ this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ _ ‹l < a'› $ ha.left _ ha', ne_empty_iff_exists_mem.mpr ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma nhds_principal_ne_bot_of_is_glb : ∀ {a : α} {s : set α}, is_glb s a → s ≠ ∅ → nhds a ⊓ principal s ≠ ⊥ := @nhds_principal_ne_bot_of_is_lub (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) (hfa : f ⊓ nhds a ≠ ⊥) : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ nhds a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := inhabited_of_mem_sets hfa this in have b < b, from lt_of_lt_of_le hxb $ hb _ hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → f ⊓ nhds a ≠ ⊥ → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s ≠ ∅) (hb : tendsto f (nhds a ⊓ principal s) (nhds b)) : is_lub (f '' s) b := have hnbot : (nhds a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have {x | x < f a'} ∈ nhds b, from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ha') h.symm, have {x | a' < x} ∈ nhds a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ nhds a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ nhds a ⊓ principal s, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', le_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' _ $ mem_image_of_mem _ hx) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_lub (f '' s) b := @is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_lub ha hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) (sc : is_closed s) : a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_glb ha hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) (sc : is_closed s) : a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma bdd_below_of_compact {α : Type u} [topological_space α] [linear_order α] [ordered_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases @compact_elim_finite_subcover_image α _ _ _ s (λ x, {b | x < b}) hs (λ x _, is_open_lt continuous_const continuous_id) _ with ⟨t, st, ft, ht⟩, { refine H ((bdd_below_finite ft).imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC _ hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma bdd_above_of_compact {α : Type u} [topological_space α] [linear_order α] [orderable_topology α] : Π [nonempty α] {s : set α}, compact s → bdd_above s := @bdd_below_of_compact (order_dual α) _ _ _ end order_topology section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] [complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Sup s ∈ closure s := mem_closure_of_is_lub is_lub_Sup hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Inf s ∈ closure s := mem_closure_of_is_glb is_glb_Inf hs lemma Sup_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed is_lub_Sup hs hc lemma Inf_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed is_glb_Inf hs hc /-- A continuous monotone function sends supremum to supremum for nonempty sets. -/ lemma Sup_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_iff_Sup_eq.1 (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Cf xy) is_lub_Sup hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending bot to bot sends supremum to supremum. -/ lemma Sup_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (fbot : f ⊥ = ⊥) {s : set α} : f (Sup s) = Sup (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Sup_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed supremum to indexed supremum. -/ lemma supr_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (supr g) = supr (f ∘ g) := by rw [supr, Sup_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum for nonempty sets. -/ lemma Inf_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Inf s) = Inf (f '' s) := (is_glb_iff_Inf_eq.1 (is_glb_of_is_glb_of_tendsto (λ x hx y hy xy, Cf xy) is_glb_Inf hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending top to top sends infimum to infimum. -/ lemma Inf_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (ftop : f ⊤ = ⊤) {s : set α} : f (Inf s) = Inf (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Inf_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed infimum to indexed infimum. -/ lemma infi_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (infi g) = infi (f ∘ g) := by rw [infi, Inf_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] [conditionally_complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma cSup_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma cSup_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma cInf_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- A continuous monotone function sends supremum to supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma cSup_of_cSup_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine (is_lub_iff_eq_of_is_lub _).1 (is_lub_cSup (mt image_eq_empty.1 ne) (bdd_above_of_bdd_above_of_monotone Cf H)), refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Cf xy) (is_lub_cSup ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed supremum to indexed supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma csupr_of_csupr_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_above (range g)) : f (supr g) = supr (f ∘ g) := by rw [supr, cSup_of_cSup_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cInf_of_cInf_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := begin refine (is_glb_iff_eq_of_is_glb _).1 (is_glb_cInf (mt image_eq_empty.1 ne) (bdd_below_of_bdd_below_of_monotone Cf H)), refine is_glb_of_is_glb_of_tendsto (λx hx y hy xy, Cf xy) (is_glb_cInf ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cinfi_of_cinfi_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_below (range g)) : f (infi g) = infi (f ∘ g) := by rw [infi, cInf_of_cInf_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma exists_forall_le_of_compact_of_continuous {α : Type u} [topological_space α] (f : α → β) (hf : continuous f) (s : set α) (hs : compact s) (ne_s : s ≠ ∅) : ∃x∈s, ∀y∈s, f x ≤ f y := begin have C : compact (f '' s) := compact_image hs hf, haveI := has_Inf_to_nonempty β, have B : bdd_below (f '' s) := bdd_below_of_compact C, have : Inf (f '' s) ∈ f '' s := cInf_mem_of_is_closed (mt image_eq_empty.1 ne_s) (closed_of_compact _ C) B, rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩, exact ⟨x, xs, λ y hy, hx.symm ▸ cInf_le B ⟨_, hy, rfl⟩⟩ end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma exists_forall_ge_of_compact_of_continuous {α : Type u} [topological_space α] : ∀ f : α → β, continuous f → ∀ s : set α, compact s → s ≠ ∅ → ∃x∈s, ∀y∈s, f y ≤ f x := @exists_forall_le_of_compact_of_continuous (order_dual β) _ _ _ _ _ end conditionally_complete_linear_order section liminf_limsup section ordered_topology variables [semilattice_sup α] [topological_space α] [orderable_topology α] lemma is_bounded_le_nhds (a : α) : (nhds a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, show {x : α | x ≤ a} ∈ nhds a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma is_bounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≤) u := is_bounded_of_le h (is_bounded_le_nhds a) lemma is_cobounded_ge_nhds (a : α) : (nhds a).is_cobounded (≥) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_le_nhds a) lemma is_cobounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≥) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_le_of_tendsto h) end ordered_topology section ordered_topology variables [semilattice_inf α] [topological_space α] [orderable_topology α] lemma is_bounded_ge_nhds (a : α) : (nhds a).is_bounded (≥) := match forall_le_or_exists_lt_inf a with | or.inl h := ⟨a, show {x : α | a ≤ x} ∈ nhds a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, le_mem_nhds hb⟩ end lemma is_bounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≥) u := is_bounded_of_le h (is_bounded_ge_nhds a) lemma is_cobounded_le_nhds (a : α) : (nhds a).is_cobounded (≤) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_ge_nhds a) lemma is_cobounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≤) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_ge_of_tendsto h) end ordered_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : {a | a < b} ∈ f := let ⟨c, (h : {a : α | a ≤ c} ∈ f), hcb⟩ := exists_lt_of_cInf_lt (ne_empty_iff_exists_mem.2 h) l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → f.Liminf > b → {a | a > b} ∈ f := @lt_mem_sets_of_Limsup_lt (order_dual α) _ _ _ /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ nhds a := tendsto_orderable.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (nhds a) = a := cInf_intro (ne_empty_iff_exists_mem.2 $ is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ nhds a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ nhds a), c < b, from match dense_or_discrete hba with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (nhds a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (nhds a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a), have hb_le : is_bounded (≤) f, from is_bounded_of_le h (is_bounded_le_nhds a), le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hf hb_le hb_ge ... ≤ (nhds a).Limsup : Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (nhds a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) (is_cobounded_of_is_bounded hf hb_le)) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α}, f ≠ ⊥ → f ≤ nhds a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (h : liminf f u = a ∧ limsup f u = a) : tendsto u f (nhds a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot h.2 h.1 /-- If a function has a limit, then its limsup coincides with its limit-/ theorem limsup_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : limsup f u = a := Limsup_eq_of_le_nhds (map_ne_bot hf) h /-- If a function has a limit, then its liminf coincides with its limit-/ theorem liminf_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : liminf f u = a := Liminf_eq_of_le_nhds (map_ne_bot hf) h end complete_linear_order end liminf_limsup end orderable_topology lemma orderable_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_comm_group α] [topological_space α] (h_nhds : ∀a:α, nhds a = (⨅r>0, principal {b | abs (a - b) < r})) : orderable_topology α := orderable_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a + -b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, -sub_eq_add_neg, (sub_eq_add_neg _ _).symm, sub_lt, lt_sub_iff_add_lt, and_comm, sub_lt_iff_lt_add']), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : monotone f) : tendsto f at_top (nhds (⨆i, f i)) := tendsto_orderable.2 $ and.intro (assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩) (assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha)) lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (nhds (⨅i, f i)) := @tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (nhds a) → supr f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_supr_nat f hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (nhds a) → infi f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_infi_nat f hf)
00d71a80ca2e61acd5e24b8e586b03bed1eaa627
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Nat/Log2.lean
0fc581c1015c2269684badee6dc218579067bd50
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,038
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ prelude import Init.NotationExtra import Init.Data.Nat.Linear namespace Nat theorem log2_terminates : ∀ n, n ≥ 2 → n / 2 < n | 2, _ => by decide | 3, _ => by decide | n+4, _ => by rw [div_eq, if_pos] refine succ_lt_succ (Nat.lt_trans ?_ (lt_succ_self _)) exact log2_terminates (n+2) (by simp_arith) simp_arith /-- Computes `⌊max 0 (log₂ n)⌋`. `log2 0 = log2 1 = 0`, `log2 2 = 1`, ..., `log2 (2^i) = i`, etc. -/ @[extern "lean_nat_log2"] def log2 (n : @& Nat) : Nat := if n ≥ 2 then log2 (n / 2) + 1 else 0 decreasing_by exact log2_terminates _ ‹_› theorem log2_le_self (n : Nat) : Nat.log2 n ≤ n := by unfold Nat.log2; split · next h => have := log2_le_self (n / 2) exact Nat.lt_of_le_of_lt this (Nat.div_lt_self (Nat.le_of_lt h) (by decide)) · apply Nat.zero_le decreasing_by exact Nat.log2_terminates _ ‹_›
01ae57c8212b4579f7f2e526704b3fe7c5f5d020
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/add_torsor.lean
31fa8230926f960302002c1e59f2f7a9155eddf9
[ "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
12,568
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import analysis.normed_space.basic import linear_algebra.affine_space.midpoint import topology.instances.real_vector_space /-! # Torsors of additive normed group actions. This file defines torsors of additive normed group actions, with a metric space structure. The motivating case is Euclidean affine spaces. -/ noncomputable theory open_locale nnreal topological_space open filter /-- A `semi_normed_add_torsor V P` is a torsor of an additive seminormed group action by a `semi_normed_group V` on points `P`. We bundle the pseudometric space structure and require the distance to be the same as results from the norm (which in fact implies the distance yields a pseudometric space, but bundling just the distance and using an instance for the pseudometric space results in type class problems). -/ class semi_normed_add_torsor (V : out_param $ Type*) (P : Type*) [out_param $ semi_normed_group V] [pseudo_metric_space P] extends add_torsor V P := (dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥) /-- A `normed_add_torsor V P` is a torsor of an additive normed group action by a `normed_group V` on points `P`. We bundle the metric space structure and require the distance to be the same as results from the norm (which in fact implies the distance yields a metric space, but bundling just the distance and using an instance for the metric space results in type class problems). -/ class normed_add_torsor (V : out_param $ Type*) (P : Type*) [out_param $ normed_group V] [metric_space P] extends add_torsor V P := (dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥) /-- A `normed_add_torsor` is a `semi_normed_add_torsor`. -/ @[priority 100] instance normed_add_torsor.to_semi_normed_add_torsor {V P : Type*} [normed_group V] [metric_space P] [β : normed_add_torsor V P] : semi_normed_add_torsor V P := { ..β } variables {α V P : Type*} [semi_normed_group V] [pseudo_metric_space P] [semi_normed_add_torsor V P] variables {W Q : Type*} [normed_group W] [metric_space Q] [normed_add_torsor W Q] /-- A `semi_normed_group` is a `semi_normed_add_torsor` over itself. -/ @[priority 100] instance semi_normed_group.normed_add_torsor : semi_normed_add_torsor V V := { dist_eq_norm' := dist_eq_norm } /-- A `normed_group` is a `normed_add_torsor` over itself. -/ @[priority 100] instance normed_group.normed_add_torsor : normed_add_torsor W W := { dist_eq_norm' := dist_eq_norm } include V section variables (V W) /-- The distance equals the norm of subtracting two points. In this lemma, it is necessary to have `V` as an explicit argument; otherwise `rw dist_eq_norm_vsub` sometimes doesn't work. -/ lemma dist_eq_norm_vsub (x y : P) : dist x y = ∥(x -ᵥ y)∥ := semi_normed_add_torsor.dist_eq_norm' x y end @[simp] lemma dist_vadd_cancel_left (v : V) (x y : P) : dist (v +ᵥ x) (v +ᵥ y) = dist x y := by rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, vadd_vsub_vadd_cancel_left] @[simp] lemma dist_vadd_cancel_right (v₁ v₂ : V) (x : P) : dist (v₁ +ᵥ x) (v₂ +ᵥ x) = dist v₁ v₂ := by rw [dist_eq_norm_vsub V, dist_eq_norm, vadd_vsub_vadd_cancel_right] @[simp] lemma dist_vadd_left (v : V) (x : P) : dist (v +ᵥ x) x = ∥v∥ := by simp [dist_eq_norm_vsub V _ x] @[simp] lemma dist_vadd_right (v : V) (x : P) : dist x (v +ᵥ x) = ∥v∥ := by rw [dist_comm, dist_vadd_left] @[simp] lemma dist_vsub_cancel_left (x y z : P) : dist (x -ᵥ y) (x -ᵥ z) = dist y z := by rw [dist_eq_norm, vsub_sub_vsub_cancel_left, dist_comm, dist_eq_norm_vsub V] @[simp] lemma dist_vsub_cancel_right (x y z : P) : dist (x -ᵥ z) (y -ᵥ z) = dist x y := by rw [dist_eq_norm, vsub_sub_vsub_cancel_right, dist_eq_norm_vsub V] lemma dist_vadd_vadd_le (v v' : V) (p p' : P) : dist (v +ᵥ p) (v' +ᵥ p') ≤ dist v v' + dist p p' := by simpa using dist_triangle (v +ᵥ p) (v' +ᵥ p) (v' +ᵥ p') lemma dist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : dist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ dist p₁ p₃ + dist p₂ p₄ := by { rw [dist_eq_norm, vsub_sub_vsub_comm, dist_eq_norm_vsub V, dist_eq_norm_vsub V], exact norm_sub_le _ _ } lemma nndist_vadd_vadd_le (v v' : V) (p p' : P) : nndist (v +ᵥ p) (v' +ᵥ p') ≤ nndist v v' + nndist p p' := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vadd_vadd_le] lemma nndist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : nndist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ nndist p₁ p₃ + nndist p₂ p₄ := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vsub_vsub_le] lemma edist_vadd_vadd_le (v v' : V) (p p' : P) : edist (v +ᵥ p) (v' +ᵥ p') ≤ edist v v' + edist p p' := by { simp only [edist_nndist], apply_mod_cast nndist_vadd_vadd_le } lemma edist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : edist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ edist p₁ p₃ + edist p₂ p₄ := by { simp only [edist_nndist], apply_mod_cast nndist_vsub_vsub_le } omit V /-- The pseudodistance defines a pseudometric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def pseudo_metric_space_of_normed_group_of_add_torsor (V P : Type*) [semi_normed_group V] [add_torsor V P] : pseudo_metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } /-- The distance defines a metric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def metric_space_of_normed_group_of_add_torsor (V P : Type*) [normed_group V] [add_torsor V P] : metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, by simpa using h, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } include V lemma lipschitz_with.vadd [pseudo_emetric_space α] {f : α → V} {g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f +ᵥ g) := λ x y, calc edist (f x +ᵥ g x) (f y +ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vadd_vadd_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.vsub [pseudo_emetric_space α] {f g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f -ᵥ g) := λ x y, calc edist (f x -ᵥ g x) (f y -ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vsub_vsub_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma uniform_continuous_vadd : uniform_continuous (λ x : V × P, x.1 +ᵥ x.2) := (lipschitz_with.prod_fst.vadd lipschitz_with.prod_snd).uniform_continuous lemma uniform_continuous_vsub : uniform_continuous (λ x : P × P, x.1 -ᵥ x.2) := (lipschitz_with.prod_fst.vsub lipschitz_with.prod_snd).uniform_continuous @[priority 100] instance semi_normed_add_torsor.has_continuous_vadd : has_continuous_vadd V P := { continuous_vadd := uniform_continuous_vadd.continuous } lemma continuous_vsub : continuous (λ x : P × P, x.1 -ᵥ x.2) := uniform_continuous_vsub.continuous lemma filter.tendsto.vsub {l : filter α} {f g : α → P} {x y : P} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (f -ᵥ g) l (𝓝 (x -ᵥ y)) := (continuous_vsub.tendsto (x, y)).comp (hf.prod_mk_nhds hg) section variables [topological_space α] lemma continuous.vsub {f g : α → P} (hf : continuous f) (hg : continuous g) : continuous (f -ᵥ g) := continuous_vsub.comp (hf.prod_mk hg : _) lemma continuous_at.vsub {f g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (f -ᵥ g) x := hf.vsub hg lemma continuous_within_at.vsub {f g : α → P} {x : α} {s : set α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (f -ᵥ g) s x := hf.vsub hg end section variables {R : Type*} [ring R] [topological_space R] [module R V] [has_continuous_smul R V] lemma filter.tendsto.line_map {l : filter α} {f₁ f₂ : α → P} {g : α → R} {p₁ p₂ : P} {c : R} (h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) (hg : tendsto g l (𝓝 c)) : tendsto (λ x, affine_map.line_map (f₁ x) (f₂ x) (g x)) l (𝓝 $ affine_map.line_map p₁ p₂ c) := (hg.smul (h₂.vsub h₁)).vadd h₁ lemma filter.tendsto.midpoint [invertible (2:R)] {l : filter α} {f₁ f₂ : α → P} {p₁ p₂ : P} (h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) : tendsto (λ x, midpoint R (f₁ x) (f₂ x)) l (𝓝 $ midpoint R p₁ p₂) := h₁.line_map h₂ tendsto_const_nhds end section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [semi_normed_space 𝕜 V] open affine_map @[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₁ (homothety p₁ c p₂) = ∥c∥ * dist p₁ p₂ := by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm] @[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₁ = ∥c∥ * dist p₁ p₂ := by rw [dist_comm, dist_center_homothety] @[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₂ = ∥1 - c∥ * dist p₁ p₂ := by rw [homothety_eq_line_map, ← line_map_apply_one_sub, ← homothety_eq_line_map, dist_homothety_center, dist_comm] @[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₂ (homothety p₁ c p₂) = ∥1 - c∥ * dist p₁ p₂ := by rw [dist_comm, dist_homothety_self] variables [invertible (2:𝕜)] @[simp] lemma dist_left_midpoint (p₁ p₂ : P) : dist p₁ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint, ← homothety_eq_line_map, dist_center_homothety, inv_of_eq_inv, ← normed_field.norm_inv] @[simp] lemma dist_midpoint_left (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₁ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_left_midpoint] @[simp] lemma dist_midpoint_right (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₂ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint_comm, dist_midpoint_left, dist_comm] @[simp] lemma dist_right_midpoint (p₁ p₂ : P) : dist p₂ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_midpoint_right] lemma dist_midpoint_midpoint_le' (p₁ p₂ p₃ p₄ : P) : dist (midpoint 𝕜 p₁ p₂) (midpoint 𝕜 p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / ∥(2 : 𝕜)∥ := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, midpoint_vsub_midpoint]; try { apply_instance }, rw [midpoint_eq_smul_add, norm_smul, inv_of_eq_inv, normed_field.norm_inv, ← div_eq_inv_mul], exact div_le_div_of_le_of_nonneg (norm_add_le _ _) (norm_nonneg _), end end normed_space variables [semi_normed_space ℝ V] [normed_space ℝ W] lemma dist_midpoint_midpoint_le (p₁ p₂ p₃ p₄ : V) : dist (midpoint ℝ p₁ p₂) (midpoint ℝ p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / 2 := by simpa using dist_midpoint_midpoint_le' p₁ p₂ p₃ p₄ include W /-- A continuous map between two normed affine spaces is an affine map provided that it sends midpoints to midpoints. -/ def affine_map.of_map_midpoint (f : P → Q) (h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y)) (hfc : continuous f) : P →ᵃ[ℝ] Q := affine_map.mk' f ↑((add_monoid_hom.of_map_midpoint ℝ ℝ ((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘ (affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp) (λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub, continuous_const, hfc.comp, continuous_id]) (classical.arbitrary P) (λ p, by simp)
17406e039f2de724e9ba3b937e22eb509ac539c0
5382d69a781e8d7e4f53e2358896eb7649c9b298
/inverse.lean
920ffbba86c3f5a47a65566fa877397330f95db8
[]
no_license
evhub/lean-math-examples
c30249747a21fba3bc8793eba4928db47cf28768
dec44bf581a1e9d5bf0b5261803a43fe8fd350e1
refs/heads/master
1,624,170,837,738
1,623,889,725,000
1,623,889,725,000
148,759,369
3
0
null
null
null
null
UTF-8
Lean
false
false
4,730
lean
import .util namespace inverse open function open classical (renaming some → unexists) (renaming some_spec → unexists_prop) open classical (choice prop_decidable) local attribute [instance] prop_decidable open util -- one-sided inverses: class invertible.one_sided {T T': Sort _} (f: T → T') := (g: T' → T) (left_inv: ∀ x: T, g (f x) = x) @[reducible, inline] def inv {T T': Sort _} (f: T → T') [hf: invertible.one_sided f]: T' → T := hf.g @[simp] theorem inv.elim {T T': Sort _} (f: T → T') [hf: invertible.one_sided f]: ∀ x: T, inv f (f x) = x := by apply hf.left_inv instance inv.surjective {T T': Sort _} (f: T → T') [hf: invertible.one_sided f]: surjective (inv f) := begin intro x, apply exists.intro (f x), simp, end instance invertible.one_sided.injective {T T': Sort _} (f: T → T') [hf: invertible.one_sided f]: injective f := begin intros x y hxy, have hinvxy: inv f (f x) = inv f (f y) := congr rfl hxy, simp at hinvxy, assumption, end -- noncomputable inverse: noncomputable def inj_inv {T T': Sort _} [hT: nonempty T] (f: T → T') (y: T'): T := if h: ∃ x: T, f x = y then unexists h else choice hT noncomputable def inj_inv.is_inverse {T T': Sort _} [hT: nonempty T] (f: T → T') [hf: injective f]: invertible.one_sided f := { g := inj_inv f, left_inv := begin intros, rw [inj_inv], cases em (∃ (x' : T), f x' = f x), case or.inl { rw [dif_pos h], apply hf, exact unexists_prop h, }, case or.inr { rw [dif_neg h], apply false.elim, apply h, apply exists.intro x, refl, }, end, } -- two-sided inverses: class invertible {T T': Sort _} (f: T → T') extends invertible.one_sided f := (right_inv: ∀ y: T', f (g y) = y) instance invertible.surjective {T T': Sort _} (f: T → T') [hf: invertible f]: surjective f := begin intro y, apply exists.intro ((inv f) y), rw [hf.right_inv], end instance invertible.bijective {T T': Sort _} (f: T → T') [hf: invertible f]: bijective f := { -- injective: left := by apply invertible.one_sided.injective, -- surjective: right := by apply invertible.surjective, } instance invertible.of_surjective {T T': Sort _} (f: T → T') [hfinv: invertible.one_sided f] [hfsur: surjective f]: invertible f := begin split, intros, have hex := hfsur y, apply exists.elim hex, intros x hx, rw [←hx], exact congr rfl (invertible.one_sided.left_inv f x), end instance inv.invertible {T T': Sort _} (f: T → T') [hf: invertible f]: invertible (inv f) := { g := f, left_inv := hf.right_inv, right_inv := hf.left_inv, } @[simp] theorem inv.elim_of_inv {T T': Sort _} (f: T → T') [hf: invertible f]: inv (inv f) = f := by rw [inv.invertible] theorem inv.uniq {T T': Sort _} (f: T → T') [hf: invertible f]: ∀ {g: T' → T}, (∀ x: T, g (f x) = x) → g = inv f := begin intros g hg, funext, have hfsurx := invertible.surjective f x, apply exists.elim hfsurx, intros y hy, rw [←hy, hg y], rw [inv, hf.left_inv], end instance inv.injective {T T': Sort _} (f: T → T') [hf: invertible f]: injective (inv f) := begin intros x y hxy, have hfx := invertible.surjective f x, have hfy := invertible.surjective f y, apply exists.elim hfx, intros a ha, apply exists.elim hfy, intros b hb, rw [←ha, ←hb] at *, simp at hxy, rw [hxy], end -- id: instance id.invertible {T: Sort _}: invertible (@id T) := { g := id, left_inv := begin intros, refl, end, right_inv := begin intros, refl, end, } end inverse
152e49fec7ec1e7d266ae4412f800fdc001deb7d
c777c32c8e484e195053731103c5e52af26a25d1
/src/combinatorics/derangements/exponential.lean
6ab726aa8a1ce289406416205b3ac45ccb5a2ebf
[ "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
1,883
lean
/- Copyright (c) 2021 Henry Swanson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henry Swanson, Patrick Massot -/ import analysis.special_functions.exponential import combinatorics.derangements.finite import order.filter.basic /-! # Derangement exponential series This file proves that the probability of a permutation on n elements being a derangement is 1/e. The specific lemma is `num_derangements_tendsto_inv_e`. -/ open filter open_locale big_operators open_locale topology theorem num_derangements_tendsto_inv_e : tendsto (λ n, (num_derangements n : ℝ) / n.factorial) at_top (𝓝 (real.exp (-1))) := begin -- we show that d(n)/n! is the partial sum of exp(-1), but offset by 1. -- this isn't entirely obvious, since we have to ensure that asc_factorial and -- factorial interact in the right way, e.g., that k ≤ n always let s : ℕ → ℝ := λ n, ∑ k in finset.range n, (-1 : ℝ)^k / k.factorial, suffices : ∀ n : ℕ, (num_derangements n : ℝ) / n.factorial = s(n+1), { simp_rw this, -- shift the function by 1, and then use the fact that the partial sums -- converge to the infinite sum rw tendsto_add_at_top_iff_nat 1, apply has_sum.tendsto_sum_nat, -- there's no specific lemma for ℝ that ∑ x^k/k! sums to exp(x), but it's -- true in more general fields, so use that lemma rw real.exp_eq_exp_ℝ, exact exp_series_div_has_sum_exp ℝ (-1 : ℝ) }, intro n, rw [← int.cast_coe_nat, num_derangements_sum], push_cast, rw finset.sum_div, -- get down to individual terms refine finset.sum_congr (refl _) _, intros k hk, have h_le : k ≤ n := finset.mem_range_succ_iff.mp hk, rw [nat.asc_factorial_eq_div, add_tsub_cancel_of_le h_le], push_cast [nat.factorial_dvd_factorial h_le], field_simp [nat.factorial_ne_zero], ring, end
c07d7a4f4c3ce6e64adc815055ec58454a67a6ff
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/discrete_valuation_ring.lean
7e44203f3d96f34ac166ca6707698d613305c2ac
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
16,277
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import ring_theory.principal_ideal_domain import order.conditionally_complete_lattice import ring_theory.multiplicity import ring_theory.valuation.basic /-! # Discrete valuation rings This file defines discrete valuation rings (DVRs) and develops a basic interface for them. ## Important definitions There are various definitions of a DVR in the literature; we define a DVR to be a local PID which is not a field (the first definition in Wikipedia) and prove that this is equivalent to being a PID with a unique non-zero prime ideal (the definition in Serre's book "Local Fields"). Let R be an integral domain, assumed to be a principal ideal ring and a local ring. * `discrete_valuation_ring R` : a predicate expressing that R is a DVR ### Definitions * `add_val R : add_valuation R enat` : the additive valuation on a DVR. ## Implementation notes It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible. We do not hence define `uniformizer` at all, because we can use `irreducible` instead. ## Tags discrete valuation ring -/ open_locale classical universe u open ideal local_ring /-- An integral domain is a *discrete valuation ring* (DVR) if it's a local PID which is not a field. -/ class discrete_valuation_ring (R : Type u) [integral_domain R] extends is_principal_ideal_ring R, local_ring R : Prop := (not_a_field' : maximal_ideal R ≠ ⊥) namespace discrete_valuation_ring variables (R : Type u) [integral_domain R] [discrete_valuation_ring R] lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field' variable {R} open principal_ideal_ring /-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the maximal ideal of R -/ theorem irreducible_iff_uniformizer (ϖ : R) : irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} := ⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm, begin intro h, have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R, from h.symm ▸ submodule.mem_span_singleton_self ϖ, refine ⟨h2, _⟩, intros a b hab, by_contra h, push_neg at h, obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h, rw h at ha hb, rw mem_span_singleton' at ha hb, rcases ha with ⟨a, rfl⟩, rcases hb with ⟨b, rfl⟩, rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab, have h3 := eq_zero_of_mul_eq_self_right _ hab.symm, { apply not_a_field R, simp [h, h3] }, { intro hh, apply h2, refine is_unit_of_dvd_one ϖ _, use a * b, exact hh.symm } end⟩ variable (R) /-- Uniformisers exist in a DVR -/ theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ := by {simp_rw [irreducible_iff_uniformizer], exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal} /-- Uniformisers exist in a DVR -/ theorem exists_prime : ∃ ϖ : R, prime ϖ := (exists_irreducible R).imp (λ _, principal_ideal_ring.irreducible_iff_prime.1) /-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/ theorem iff_pid_with_one_nonzero_prime (R : Type u) [integral_domain R] : discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P := begin split, { intro RDVR, rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩, split, assumption, resetI, use local_ring.maximal_ideal R, split, split, { assumption }, { apply_instance } , { rintro Q ⟨hQ1, hQ2⟩, obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1, have hq : q ≠ 0, { rintro rfl, apply hQ1, simp }, erw span_singleton_prime hq at hQ2, replace hQ2 := irreducible_of_prime hQ2, rw irreducible_iff_uniformizer at hQ2, exact hQ2.symm } }, { rintro ⟨RPID, Punique⟩, haveI : local_ring R := local_of_unique_nonzero_prime R Punique, refine {not_a_field' := _}, rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩, have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1), intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM } end lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) : associated a b := begin rw irreducible_iff_uniformizer at ha hb, rw [←span_singleton_eq_span_singleton, ←ha, hb], end end discrete_valuation_ring namespace discrete_valuation_ring variable (R : Type*) /-- Alternative characterisation of discrete valuation rings. -/ def has_unit_mul_pow_irreducible_factorization [integral_domain R] : Prop := ∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x namespace has_unit_mul_pow_irreducible_factorization variables {R} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) include hR lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin rcases hR with ⟨ϖ, hϖ, hR⟩, suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ, { apply associated.trans (this hp) (this hq).symm, }, clear hp hq p q, intros p hp, obtain ⟨n, hn⟩ := hR hp.ne_zero, have : irreducible (ϖ ^ n) := irreducible_of_associated hn.symm hp, rcases lt_trichotomy n 1 with (H|rfl|H), { obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial }, simpa only [not_irreducible_one, pow_zero] using this, }, { simpa only [pow_one] using hn.symm, }, { obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H, rw pow_succ at this, rcases this.is_unit_or_is_unit rfl with H0|H0, { exact (hϖ.not_unit H0).elim, }, { rw [add_comm, pow_succ] at H0, exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } } end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a unique factorization domain. See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/ theorem to_unique_factorization_monoid : unique_factorization_monoid R := let p := classical.some hR in let spec := classical.some_spec hR in unique_factorization_monoid.of_exists_prime_factors $ λ x hx, begin use multiset.repeat p (classical.some (spec.2 hx)), split, { intros q hq, have hpq := multiset.eq_of_mem_repeat hq, rw hpq, refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩, intros a b h, by_cases ha : a = 0, { rw ha, simp only [true_or, dvd_zero], }, by_cases hb : b = 0, { rw hb, simp only [or_true, dvd_zero], }, obtain ⟨m, u, rfl⟩ := spec.2 ha, rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (units.is_unit _)] at h, rw is_unit.dvd_mul_right (units.is_unit _), by_cases hm : m = 0, { simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h }, left, obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm, rw pow_succ, apply dvd_mul_of_dvd_left (dvd_refl _) _ }, { rw [multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), } end omit hR lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : has_unit_mul_pow_irreducible_factorization R := begin obtain ⟨p, hp⟩ := h₁, refine ⟨p, hp, _⟩, intros x hx, cases wf_dvd_monoid.exists_factors x hx with fx hfx, refine ⟨fx.card, _⟩, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, symmetry, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ q hq rfl, rw associates.mk_eq_mk_iff_associated, apply h₂ (hfx.1 _ hq) hp, end end has_unit_mul_pow_irreducible_factorization lemma aux_pid_of_ufd_of_unique_irreducible (R : Type u) [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : is_principal_ideal_ring R := begin constructor, intro I, by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], }, obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0, obtain ⟨p, hp, H⟩ := has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂, have ex : ∃ n : ℕ, p ^ n ∈ I, { obtain ⟨n, u, rfl⟩ := H hx0, refine ⟨n, _⟩, simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hxI, }, constructor, use p ^ (nat.find ex), show I = ideal.span _, apply le_antisymm, { intros r hr, by_cases hr0 : r = 0, { simp only [hr0, submodule.zero_mem], }, obtain ⟨n, u, rfl⟩ := H hr0, simp only [mem_span_singleton, units.is_unit, is_unit.dvd_mul_right], apply pow_dvd_pow, apply nat.find_min', simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hr, }, { erw submodule.span_singleton_le_iff_mem, exact nat.find_spec ex, }, end /-- A unique factorization domain with at least one irreducible element in which all irreducible elements are associated is a discrete valuation ring. -/ lemma of_ufd_of_unique_irreducible {R : Type u} [integral_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : discrete_valuation_ring R := begin rw iff_pid_with_one_nonzero_prime, haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂, obtain ⟨p, hp⟩ := h₁, refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩, { rw submodule.ne_bot_iff, refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, }, { rwa [ideal.span_singleton_prime hp.ne_zero, ← unique_factorization_monoid.irreducible_iff_prime], }, { intro I, rw ← submodule.is_principal.span_singleton_generator I, rintro ⟨I0, hI⟩, apply span_singleton_eq_span_singleton.mpr, apply h₂ _ hp, erw [ne.def, span_singleton_eq_bot] at I0, rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0], }, end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a discrete valuation ring. -/ lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [integral_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) : discrete_valuation_ring R := begin letI : unique_factorization_monoid R := hR.to_unique_factorization_monoid, apply of_ufd_of_unique_irreducible _ hR.unique_irreducible, unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, }, end section variables [integral_domain R] [discrete_valuation_ring R] variable {R} lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ), associated x (ϖ ^ n) := begin have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid, cases wf_dvd_monoid.exists_factors x hx with fx hfx, unfreezingI { use fx.card }, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat], congr' 1, rw multiset.eq_repeat, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ _ _ rfl, rw associates.mk_eq_mk_iff_associated, refine associated_of_irreducible _ _ hirr, apply hfx.1, assumption end lemma eq_unit_mul_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ) (u : units R), x = u * ϖ ^ n := begin obtain ⟨n, hn⟩ := associated_pow_irreducible hx hirr, obtain ⟨u, rfl⟩ := hn.symm, use [n, u], apply mul_comm, end open submodule.is_principal lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) : ∃ n : ℕ, s = ideal.span {ϖ ^ n} := begin have gen_ne_zero : generator s ≠ 0, { rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption }, rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩, use n, have : span _ = _ := span_singleton_generator s, rw [← this, ← hnu, span_singleton_eq_span_singleton], use u end lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q) (u v : units R) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) : m = n := begin have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod, { rw [multiset.prod_repeat, multiset.prod_repeat, associated], refine ⟨u * v⁻¹, _⟩, simp only [units.coe_mul], rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], }, have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key), { simpa only [multiset.card_repeat] }, all_goals { intros x hx, replace hx := multiset.eq_of_mem_repeat hx, unfreezingI { subst hx, assumption } }, end lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : units R) (m n : ℕ) (h : ↑u * ϖ ^ m = v * ϖ ^ n) : u = v := begin obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h, rw ← sub_eq_zero at h, rw [← sub_mul, mul_eq_zero] at h, cases h, { rw sub_eq_zero at h, exact_mod_cast h }, { apply (hirr.ne_zero (pow_eq_zero h)).elim, } end /-! ## The additive valuation on a DVR -/ open multiplicity /-- The `enat`-valued additive valuation on a DVR -/ noncomputable def add_val (R : Type u) [integral_domain R] [discrete_valuation_ring R] : add_valuation R enat := add_valuation (classical.some_spec (exists_prime R)) lemma add_val_def (r : R) (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) (hr : r = u * ϖ ^ n) : add_val R r = n := by rw [add_val, add_valuation_apply, hr, eq_of_associated_left (associated_of_irreducible R hϖ (irreducible_of_prime (classical.some_spec (exists_prime R)))), eq_of_associated_right (associated.symm ⟨u, mul_comm _ _⟩), multiplicity_pow_self_of_prime (principal_ideal_ring.irreducible_iff_prime.1 hϖ)] lemma add_val_def' (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) : add_val R ((u : R) * ϖ ^ n) = n := add_val_def _ u hϖ n rfl @[simp] lemma add_val_zero : add_val R 0 = ⊤ := (add_val R).map_zero @[simp] lemma add_val_one : add_val R 1 = 0 := (add_val R).map_one @[simp] lemma add_val_uniformizer {ϖ : R} (hϖ : irreducible ϖ) : add_val R ϖ = 1 := add_val_def ϖ 1 hϖ 1 (by simp) @[simp] lemma add_val_mul {a b : R} : add_val R (a * b) = add_val R a + add_val R b := (add_val R).map_mul _ _ lemma add_val_pow (a : R) (n : ℕ) : add_val R (a ^ n) = n • add_val R a := (add_val R).map_pow _ _ lemma add_val_eq_top_iff {a : R} : add_val R a = ⊤ ↔ a = 0 := begin have hi := (irreducible_of_prime (classical.some_spec (exists_prime R))), split, { contrapose, intro h, obtain ⟨n, ha⟩ := associated_pow_irreducible h hi, obtain ⟨u, rfl⟩ := ha.symm, rw [mul_comm, add_val_def' u hi n], exact enat.coe_ne_top _ }, { rintro rfl, exact add_val_zero } end lemma add_val_le_iff_dvd {a b : R} : add_val R a ≤ add_val R b ↔ a ∣ b := begin have hp := classical.some_spec (exists_prime R), split; intro h, { by_cases ha0 : a = 0, { rw [ha0, add_val_zero, top_le_iff, add_val_eq_top_iff] at h, rw h, apply dvd_zero }, obtain ⟨n, ha⟩ := associated_pow_irreducible ha0 (irreducible_of_prime hp), rw [add_val, add_valuation_apply, add_valuation_apply, multiplicity_le_multiplicity_iff] at h, exact dvd.trans (dvd_of_associated ha) (h n (dvd_of_associated ha.symm)), }, { rw [add_val, add_valuation_apply, add_valuation_apply], exact multiplicity_le_multiplicity_of_dvd_right h } end lemma add_val_add {a b : R} : min (add_val R a) (add_val R b) ≤ add_val R (a + b) := (add_val R).map_add _ _ end end discrete_valuation_ring
d4c829f38e43de3c0dd97a6b2b41aac773fc8b24
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0215.lean
ae8eab92d767b807a420d717e427cbcc60de21f7
[]
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
100
lean
example (x y : ℕ) (h : x = y) : y = x := begin revert x, intros, symmetry, assumption end
77222ea7bcd3bc3d897fc95ffdd9ee1b0d9f8d84
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/basic.lean
2153340a48399d6d9e54e85448ba3a11a641dfd9
[ "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
56,025
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.order.ring /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `le_rec_on'`, `decreasing_induction'`: versions with slightly weaker assumptions * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, nsmul := λ m n, m * n, nsmul_zero' := nat.zero_mul, nsmul_succ' := λ n x, by rw [nat.succ_eq_add_one, nat.add_comm, nat.right_distrib, nat.one_mul] } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} instance : ordered_comm_semiring ℕ := { .. nat.comm_semiring, .. nat.linear_ordered_semiring } /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := λ a b, ⟨λ h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, λ ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred (∈ s)] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.nsmul_eq_mul (m n : ℕ) : m • n = m * n := rfl theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero nat.succ_ne_zero nat.succ_ne_self nat.zero_ne_one nat.one_ne_zero nat.zero_ne_bit1 nat.bit1_ne_zero nat.bit0_ne_one nat.one_ne_bit0 nat.bit0_ne_bit1 nat.bit1_ne_bit0 /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := ⟨n.succ_pos⟩ instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := ⟨lt_trans zero_lt_one h.1⟩ end facts variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (λ ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (λ h, h.symm ▸ ⟨1, rfl⟩) instance unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } instance unique_add_units : unique (add_units ℕ) := { default := 0, uniq := nat.add_units_eq_zero } /-! ### Equalities and inequalities involving zero and one -/ lemma one_le_iff_ne_zero {n : ℕ} : 1 ≤ n ↔ n ≠ 0 := (show 1 ≤ n ↔ 0 < n, from iff.rfl).trans pos_iff_ne_zero lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, λ h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) @[simp] lemma min_eq_zero_iff {m n : ℕ} : min m n = 0 ↔ m = 0 ∨ n = 0 := begin split, { intro h, cases le_total n m with H H, { simpa [H] using or.inr h }, { simpa [H] using or.inl h } }, { rintro (rfl|rfl); simp } end @[simp] lemma max_eq_zero_iff {m n : ℕ} : max m n = 0 ↔ m = 0 ∧ n = 0 := begin split, { intro h, cases le_total n m with H H, { simp only [H, max_eq_left] at h, exact ⟨h, le_antisymm (H.trans h.le) (zero_le _)⟩ }, { simp only [H, max_eq_right] at h, exact ⟨le_antisymm (H.trans h.le) (zero_le _), h⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end lemma add_eq_max_iff {n m : ℕ} : n + m = max n m ↔ n = 0 ∨ m = 0 := begin rw ←min_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma add_eq_min_iff {n m : ℕ} : n + m = min n m ↔ n = 0 ∧ m = 0 := begin rw ←max_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ lemma succ_eq_one_add (n : ℕ) : n.succ = 1 + n := by rw [nat.succ_eq_add_one, nat.add_comm] theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj lemma succ_ne_succ {n m : ℕ} : succ n ≠ succ m ↔ n ≠ m := succ_injective.ne_iff @[simp] lemma succ_succ_ne_one (n : ℕ) : n.succ.succ ≠ 1 := succ_ne_succ.mpr n.succ_ne_zero @[simp] lemma one_lt_succ_succ (n : ℕ) : 1 < n.succ.succ := succ_lt_succ $ succ_pos n theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := ⟨le_of_lt_succ, lt_succ_of_le⟩ lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := H.lt_or_eq_dec.imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ @[simp] lemma lt_one_iff {n : ℕ} : n < 1 ↔ n = 0 := lt_succ_iff.trans le_zero_iff lemma div_le_iff_le_mul_add_pred {m n k : ℕ} (n0 : 0 < n) : m / n ≤ k ↔ m ≤ n * k + (n - 1) := begin rw [← lt_succ_iff, div_lt_iff_lt_mul _ _ n0, succ_mul, mul_comm], cases n, {cases n0}, exact lt_succ_iff, end /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨λ h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (λ h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma le_and_le_add_one_iff {x a : ℕ} : a ≤ x ∧ x ≤ a + 1 ↔ x = a ∨ x = a + 1 := begin rw [le_add_one_iff, and_or_distrib_left, ←le_antisymm_iff, eq_comm, and_iff_right_of_imp], rintro rfl, exact a.le_succ, end lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← nat.sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := ⟨le_succ_of_pred_le, by { cases n, { exact λ h, zero_le m }, exact le_of_succ_le_succ }⟩ /-! ### `sub` Most lemmas come from the `has_ordered_sub` instance on `ℕ`. -/ instance : has_ordered_sub ℕ := begin constructor, intros m n k, induction n with n ih generalizing k, { simp }, { simp only [sub_succ, add_succ, succ_add, ih, pred_le_iff] } end lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := show n < m - 1 ↔ n + 1 < m, from lt_sub_iff_right lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) lemma le_or_le_of_add_eq_add_pred {a b c d : ℕ} (h : c + d = a + b - 1) : a ≤ c ∨ b ≤ d := begin cases le_or_lt a c with h' h'; [left, right], { exact h', }, { replace h' := add_lt_add_right h' d, rw h at h', cases b.eq_zero_or_pos with hb hb, { rw hb, exact zero_le d, }, rw [a.add_sub_assoc hb, add_lt_add_iff_left] at h', exact nat.le_of_pred_lt h', }, end /-! ### `mul` -/ lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := decidable.mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := decidable.mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := nat.mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact decidable.mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact decidable.mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by { rw [add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt]; simp }) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨ λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], λ h, by simp only [h, mul_one]⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, nat.eq_of_mul_eq_mul_left ha lemma mul_ne_mul_left {a b c : ℕ} (ha : 0 < a) : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective ha).ne_iff lemma mul_ne_mul_right {a b c : ℕ} (ha : 0 < a) : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective ha).ne_iff lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans decidable.le_iff_lt_or_eq theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. For a version where the assumption is only made when `k ≥ n`, see `le_rec_on'`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (nat.eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. For a version assuming only the assumption for `k < n`, see `decreasing_induction'`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k ≥ n`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on' {C : ℕ → Sort*} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π ⦃k⦄, n ≤ k → C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (nat.eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next h $ le_rec_on' h next x) (λ h : n = m + 1, eq.rec_on h x) /-- Decreasing induction: if `P (k+1)` implies `P k` for all `m ≤ k < n`, then `P n` implies `P m`. Also works for functions to `Sort*`. Weakens the assumptions of `decreasing_induction`. -/ @[elab_as_eliminator] def decreasing_induction' {P : ℕ → Sort*} {m n : ℕ} (h : ∀ k < n, m ≤ k → P (k+1) → P k) (mn : m ≤ n) (hP : P n) : P m := begin -- induction mn using nat.le_rec_on' generalizing h hP -- this doesn't work unfortunately refine le_rec_on' mn _ _ h hP; clear h hP mn n, { intros n mn ih h hP, apply ih, { exact λ k hk, h k hk.step }, { exact h n (lt_succ_self n) mn hP } }, { intros h hP, exact hP } end /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (nat.eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (_root_.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : nat.mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div {m n k : ℕ} : m / k < n / k → m < n := lt_imp_lt_of_le_imp_le $ λ h, nat.div_le_div_right h protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact nat.mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-- Alias of `nat.mul_div_mul` -/ --TODO: Update `nat.mul_div_mul` in the core? protected lemma mul_div_mul_left (a b : ℕ) {c : ℕ} (hc : 0 < c) : c * a / (c * b) = a / b := nat.mul_div_mul a b hc protected lemma mul_div_mul_right (a b : ℕ) {c : ℕ} (hc : 0 < c) : a * c / (b * c) = a / b := by rw [mul_comm, mul_comm b, a.mul_div_mul_left b hc] /-! ### `mod`, `dvd` -/ lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw [eq_zero_of_zero_dvd h₁, nat.div_zero, nat.div_zero] | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := begin rcases nat.eq_zero_or_pos b with rfl|hb, { simp }, rcases nat.eq_zero_or_pos c with rfl|hc, { simp }, conv_rhs { rw ← mod_add_div a (b * c) }, rw [mul_assoc, nat.add_mul_div_left _ _ hb, add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hb hc)))] end lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_rfl⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := by { rw [bit1, nat.dvd_add_right two_dvd_bit0, nat.dvd_one], cc } /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) -- TODO: update `nat.dvd_sub` in core lemma dvd_sub' {k m n : ℕ} (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := begin cases le_total n m with H H, { exact dvd_sub H h₁ h₂ }, { rw nat.sub_eq_zero_of_le H, exact dvd_zero k }, end lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases nat.eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := by simp | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← add_sub_add_right_eq_sub' a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le sub_le_self', rw [if_pos h₁, if_pos h₂, add_sub_add_right_eq_sub', nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), add_sub_add_right_eq_sub'], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, sub_eq_of_eq_add_rev (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma add_mod_eq_ite {a b n : ℕ} : (a + b) % n = if n ≤ a % n + b % n then a % n + b % n - n else a % n + b % n := begin cases n, { simp }, rw nat.add_mod, split_ifs with h, { rw [nat.mod_eq_sub_mod h, nat.mod_eq_of_lt], exact (sub_lt_iff_right h).mpr (nat.add_lt_add (a.mod_lt n.zero_lt_succ) (b.mod_lt n.zero_lt_succ)) }, { exact nat.mod_eq_of_lt (lt_of_not_ge h) } end lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ @[simp] lemma dvd_div_iff {a b c : ℕ} (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := ⟨λ h, mul_dvd_of_dvd_div hbc h, λ h, dvd_div_of_mul_dvd h⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (nat.mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end lemma lt_iff_le_pred : ∀ {m n : ℕ}, 0 < n → (m < n ↔ m ≤ n - 1) | m (n+1) _ := lt_succ_iff lemma div_eq_sub_mod_div {m n : ℕ} : m / n = (m - m % n) / n := begin by_cases n0 : n = 0, { rw [n0, nat.div_zero, nat.div_zero] }, { rw [← mod_add_div m n] { occs := occurrences.pos [2] }, rw [nat.add_sub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] } end lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := begin cases nat.eq_zero_or_pos n with n0 h, { rw [n0, zero_mul], exact m.zero_le }, { rw [mul_comm, ← nat.le_div_iff_mul_le' h] }, end lemma lt_mul_div_succ (m : ℕ) {n : ℕ} (n0 : 0 < n) : m < n * ((m / n) + 1) := begin rw [mul_comm, ← nat.div_lt_iff_lt_mul' n0], exact lt_succ_self _ end @[simp] lemma mod_div_self (m n : ℕ) : m % n / n = 0 := begin cases n, { exact (m % 0).div_zero }, { exact nat.div_eq_zero (m.mod_lt n.succ_pos) } end /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-- Two natural numbers are equal if and only if the have the same multiples. -/ lemma dvd_right_iff_eq {m n : ℕ} : (∀ a : ℕ, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mpr dvd_rfl) ((h _).mp dvd_rfl), λ h n, by rw h⟩ /-- Two natural numbers are equal if and only if the have the same divisors. -/ lemma dvd_left_iff_eq {m n : ℕ} : (∀ a : ℕ, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mp dvd_rfl) ((h _).mpr dvd_rfl), λ h n, by rw h⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : function.injective ((∣) : ℕ → ℕ → Prop) := λ m n h, dvd_right_iff_eq.mp $ λ a, iff_of_eq (congr_fun h a) /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, ne, nat.find_eq_zero] theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### decidability of predicates -/ instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (le_of_lt_succ h').lt_or_eq_dec.elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (lt_sub_iff_left.mp h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) end nat
6feeb12d971a1f402a59843b667eff8a1b6bae2a
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/RecursorInfo.lean
f4db964d26359a149bd9f72a8b7005e8281101e6
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,519
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.AuxRecursor import Lean.Util.FindExpr import Lean.Meta.ExprDefEq namespace Lean.Meta inductive RecursorUnivLevelPos where | motive -- marks where the universe of the motive should go | majorType (idx : Nat) -- marks where the #idx universe of the major premise type goes instance : ToString RecursorUnivLevelPos := ⟨fun | RecursorUnivLevelPos.motive => "<motive-univ>" | RecursorUnivLevelPos.majorType idx => toString idx⟩ structure RecursorInfo where recursorName : Name typeName : Name univLevelPos : List RecursorUnivLevelPos depElim : Bool recursive : Bool numArgs : Nat -- Total number of arguments majorPos : Nat paramsPos : List (Option Nat) -- Position of the recursor parameters in the major premise, instance implicit arguments are `none` indicesPos : List Nat -- Position of the recursor indices in the major premise produceMotive : List Bool -- If the i-th element is true then i-th minor premise produces the motive namespace RecursorInfo def numParams (info : RecursorInfo) : Nat := info.paramsPos.length def numIndices (info : RecursorInfo) : Nat := info.indicesPos.length def motivePos (info : RecursorInfo) : Nat := info.numParams def firstIndexPos (info : RecursorInfo) : Nat := info.majorPos - info.numIndices def isMinor (info : RecursorInfo) (pos : Nat) : Bool := if pos ≤ info.motivePos then false else if info.firstIndexPos ≤ pos && pos ≤ info.majorPos then false else true def numMinors (info : RecursorInfo) : Nat := let r := info.numArgs let r := r - info.motivePos - 1 r - (info.majorPos + 1 - info.firstIndexPos) instance : ToString RecursorInfo := ⟨fun info => "{\n" ++ " name := " ++ toString info.recursorName ++ "\n" ++ " type := " ++ toString info.typeName ++ "\n" ++ " univs := " ++ toString info.univLevelPos ++ "\n" ++ " depElim := " ++ toString info.depElim ++ "\n" ++ " recursive := " ++ toString info.recursive ++ "\n" ++ " numArgs := " ++ toString info.numArgs ++ "\n" ++ " numParams := " ++ toString info.numParams ++ "\n" ++ " numIndices := " ++ toString info.numIndices ++ "\n" ++ " numMinors := " ++ toString info.numMinors ++ "\n" ++ " major := " ++ toString info.majorPos ++ "\n" ++ " motive := " ++ toString info.motivePos ++ "\n" ++ " paramsAtMajor := " ++ toString info.paramsPos ++ "\n" ++ " indicesAtMajor := " ++ toString info.indicesPos ++ "\n" ++ " produceMotive := " ++ toString info.produceMotive ++ "\n" ++ "}"⟩ end RecursorInfo private def mkRecursorInfoForKernelRec (declName : Name) (val : RecursorVal) : MetaM RecursorInfo := do let ival ← getConstInfoInduct val.getInduct let numLParams := ival.levelParams.length let univLevelPos := (List.range numLParams).map RecursorUnivLevelPos.majorType let univLevelPos := if val.levelParams.length == numLParams then univLevelPos else RecursorUnivLevelPos.motive :: univLevelPos let produceMotive := List.replicate val.numMinors true let paramsPos := (List.range val.numParams).map some let indicesPos := (List.range val.numIndices).map fun pos => val.numParams + pos let numArgs := val.numIndices + val.numParams + val.numMinors + val.numMotives + 1 pure { recursorName := declName, typeName := val.getInduct, univLevelPos := univLevelPos, majorPos := val.getMajorIdx, depElim := true, recursive := ival.isRec, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := numArgs } private def getMajorPosIfAuxRecursor? (declName : Name) (majorPos? : Option Nat) : MetaM (Option Nat) := if majorPos?.isSome then pure majorPos? else do let env ← getEnv if !isAuxRecursor env declName then pure none else match declName with | Name.str p s _ => if s != recOnSuffix && s != casesOnSuffix && s != brecOnSuffix then pure none else do let val ← getConstInfoRec (mkRecName p) pure $ some (val.numParams + val.numIndices + (if s == casesOnSuffix then 1 else val.numMotives)) | _ => pure none private def checkMotive (declName : Name) (motive : Expr) (motiveArgs : Array Expr) : MetaM Unit := unless motive.isFVar && motiveArgs.all Expr.isFVar do throwError! "invalid user defined recursor '{declName}', result type must be of the form (C t), where C is a bound variable, and t is a (possibly empty) sequence of bound variables" /- Compute number of parameters for (user-defined) recursor. We assume a parameter is anything that occurs before the motive -/ private partial def getNumParams (xs : Array Expr) (motive : Expr) (i : Nat) : Nat := if h : i < xs.size then let x := xs.get ⟨i, h⟩ if motive == x then i else getNumParams xs motive (i+1) else i private def getMajorPosDepElim (declName : Name) (majorPos? : Option Nat) (xs : Array Expr) (motive : Expr) (motiveArgs : Array Expr) : MetaM (Expr × Nat × Bool) := do match majorPos? with | some majorPos => if h : majorPos < xs.size then let major := xs.get ⟨majorPos, h⟩ let depElim := motiveArgs.contains major pure (major, majorPos, depElim) else throwError! "invalid major premise position for user defined recursor, recursor has only {xs.size} arguments" | none => do if motiveArgs.isEmpty then throwError! "invalid user defined recursor, '{declName}' does not support dependent elimination, and position of the major premise was not specified (solution: set attribute '[recursor <pos>]', where <pos> is the position of the major premise)" let major := motiveArgs.back match xs.getIdx? major with | some majorPos => pure (major, majorPos, true) | none => throwError! "ill-formed recursor '{declName}'" private def getParamsPos (declName : Name) (xs : Array Expr) (numParams : Nat) (Iargs : Array Expr) : MetaM (List (Option Nat)) := do let mut paramsPos := #[] for i in [:numParams] do let x := xs[i] match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with | some j => paramsPos := paramsPos.push (some j) | none => do let localDecl ← getLocalDecl x.fvarId! if localDecl.binderInfo.isInstImplicit then paramsPos := paramsPos.push none else throwError!"invalid user defined recursor '{declName}', type of the major premise does not contain the recursor parameter" pure paramsPos.toList private def getIndicesPos (declName : Name) (xs : Array Expr) (majorPos numIndices : Nat) (Iargs : Array Expr) : MetaM (List Nat) := do let mut indicesPos := #[] for i in [:numIndices] do let i := majorPos - numIndices + i let x := xs[i] match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with | some j => indicesPos := indicesPos.push j | none => throwError! "invalid user defined recursor '{declName}', type of the major premise does not contain the recursor index" pure indicesPos.toList private def getMotiveLevel (declName : Name) (motiveResultType : Expr) : MetaM Level := match motiveResultType with | Expr.sort u@(Level.zero _) _ => pure u | Expr.sort u@(Level.param _ _) _ => pure u | _ => throwError! "invalid user defined recursor '{declName}', motive result sort must be Prop or (Sort u) where u is a universe level parameter" private def getUnivLevelPos (declName : Name) (lparams : List Name) (motiveLvl : Level) (Ilevels : List Level) : MetaM (List RecursorUnivLevelPos) := do let Ilevels := Ilevels.toArray let mut univLevelPos := #[] for p in lparams do if motiveLvl == mkLevelParam p then univLevelPos := univLevelPos.push RecursorUnivLevelPos.motive else match Ilevels.findIdx? fun u => u == mkLevelParam p with | some i => univLevelPos := univLevelPos.push (RecursorUnivLevelPos.majorType i) | none => throwError! "invalid user defined recursor '{declName}', major premise type does not contain universe level parameter '{p}'" pure univLevelPos.toList private def getProduceMotiveAndRecursive (xs : Array Expr) (numParams numIndices majorPos : Nat) (motive : Expr) : MetaM (List Bool × Bool) := do let mut produceMotive := #[] let mut recursor := false for i in [:xs.size] do if i < numParams + 1 then continue --skip parameters and motive if majorPos - numIndices ≤ i && i ≤ majorPos then continue -- skip indices and major premise -- process minor premise let x := xs[i] let xType ← inferType x (produceMotive, recursor) ← forallTelescopeReducing xType fun minorArgs minorResultType => minorResultType.withApp fun res _ => do let produceMotive := produceMotive.push (res == motive) let recursor ← if recursor then pure recursor else minorArgs.anyM fun minorArg => do let minorArgType ← inferType minorArg pure (minorArgType.find? fun e => e == motive).isSome pure (produceMotive, recursor) pure (produceMotive.toList, recursor) private def checkMotiveResultType (declName : Name) (motiveArgs : Array Expr) (motiveResultType : Expr) (motiveTypeParams : Array Expr) : MetaM Unit := do if !motiveResultType.isSort || motiveArgs.size != motiveTypeParams.size then throwError! "invalid user defined recursor '{declName}', motive must have a type of the form (C : Pi (i : B A), I A i -> Type), where A is (possibly empty) sequence of variables (aka parameters), (i : B A) is a (possibly empty) telescope (aka indices), and I is a constant" private def mkRecursorInfoAux (cinfo : ConstantInfo) (majorPos? : Option Nat) : MetaM RecursorInfo := do let declName := cinfo.name let majorPos? ← getMajorPosIfAuxRecursor? declName majorPos? forallTelescopeReducing cinfo.type fun xs type => type.withApp fun motive motiveArgs => do checkMotive declName motive motiveArgs let numParams := getNumParams xs motive 0 let (major, majorPos, depElim) ← getMajorPosDepElim declName majorPos? xs motive motiveArgs let numIndices := if depElim then motiveArgs.size - 1 else motiveArgs.size if majorPos < numIndices then throwError! "invalid user defined recursor '{declName}', indices must occur before major premise" let majorType ← inferType major majorType.withApp fun I Iargs => match I with | Expr.const Iname Ilevels _ => do let paramsPos ← getParamsPos declName xs numParams Iargs let indicesPos ← getIndicesPos declName xs majorPos numIndices Iargs let motiveType ← inferType motive forallTelescopeReducing motiveType fun motiveTypeParams motiveResultType => do checkMotiveResultType declName motiveArgs motiveResultType motiveTypeParams let motiveLvl ← getMotiveLevel declName motiveResultType let univLevelPos ← getUnivLevelPos declName cinfo.levelParams motiveLvl Ilevels let (produceMotive, recursive) ← getProduceMotiveAndRecursive xs numParams numIndices majorPos motive pure { recursorName := declName, typeName := Iname, univLevelPos := univLevelPos, majorPos := majorPos, depElim := depElim, recursive := recursive, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := xs.size } | _ => throwError! "invalid user defined recursor '{declName}', type of the major premise must be of the form (I ...), where I is a constant" /- @[builtinAttrParser] def «recursor» := parser! "recursor " >> numLit -/ def Attribute.Recursor.getMajorPos (stx : Syntax) : AttrM Nat := do if stx.getKind == `Lean.Parser.Attr.recursor then let pos := stx[1].isNatLit?.getD 0 if pos == 0 then throwErrorAt! stx "major premise position must be greater than zero" return pos - 1 else throwErrorAt! stx "unexpected attribute argument, numeral expected" private def mkRecursorInfoCore (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do let cinfo ← getConstInfo declName match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => mkRecursorInfoAux cinfo majorPos? builtin_initialize recursorAttribute : ParametricAttribute Nat ← registerParametricAttribute { name := `recursor, descr := "user defined recursor, numerical parameter specifies position of the major premise", getParam := fun _ stx => Attribute.Recursor.getMajorPos stx afterSet := fun declName majorPos => do discard <| mkRecursorInfoCore declName (some majorPos) |>.run' } def getMajorPos? (env : Environment) (declName : Name) : Option Nat := recursorAttribute.getParam env declName def mkRecursorInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do let cinfo ← getConstInfo declName match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => match majorPos? with | none => do mkRecursorInfoAux cinfo (getMajorPos? (← getEnv) declName) | _ => mkRecursorInfoAux cinfo majorPos? end Lean.Meta
d5369f9bdf3b81005ec67bb1ecb2db27db398be6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/control/traversable/derive.lean
3bd145a69f05fcf9dda12edcf818c89a099e328c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
17,051
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Automation to construct `traversable` instances -/ import tactic.basic import control.traversable.lemmas namespace tactic.interactive open tactic list monad functor meta def with_prefix : option name → name → name | none n := n | (some p) n := p ++ n /-- similar to `nested_traverse` but for `functor` -/ meta def nested_map (f v : expr) : expr → tactic expr | t := do t ← instantiate_mvars t, mcond (succeeds $ is_def_eq t v) (pure f) (if ¬ v.occurs (t.app_fn) then do cl ← mk_app ``functor [t.app_fn], _inst ← mk_instance cl, f' ← nested_map t.app_arg, mk_mapp ``functor.map [t.app_fn,_inst,none,none,f'] else fail format!"type {t} is not a functor with respect to variable {v}") /-- similar to `traverse_field` but for `functor` -/ meta def map_field (n : name) (cl f α β e : expr) : tactic expr := do t ← infer_type e >>= whnf, if t.get_app_fn.const_name = n then fail "recursive types not supported" else if α =ₐ e then pure β else if α.occurs t then do f' ← nested_map f α t, pure $ f' e else (is_def_eq t.app_fn cl >> mk_app ``comp.mk [e]) <|> pure e /-- similar to `traverse_constructor` but for `functor` -/ meta def map_constructor (c n : name) (f α β : expr) (args₀ : list expr) (args₁ : list (bool × expr)) (rec_call : list expr) : tactic expr := do g ← target, (_, args') ← mmap_accuml (λ (x : list expr) (y : bool × expr), if y.1 then pure (x.tail,x.head) else prod.mk rec_call <$> map_field n g.app_fn f α β y.2) rec_call args₁, constr ← mk_const c, let r := constr.mk_app (args₀ ++ args'), return r /-- derive the `map` definition of a `functor` -/ meta def mk_map (type : name) := do ls ← local_context, [α,β,f,x] ← tactic.intro_lst [`α,`β,`f,`x], et ← infer_type x, xs ← tactic.induction x, xs.mmap' (λ (x : name × list expr × list (name × expr)), do let (c,args,_) := x, (args,rec_call) ← args.mpartition $ λ e, (bnot ∘ β.occurs) <$> infer_type e, args₀ ← args.mmap $ λ a, do { b ← et.occurs <$> infer_type a, pure (b,a) }, map_constructor c type f α β (ls ++ [β]) args₀ rec_call >>= tactic.exact) meta def mk_mapp_aux' : expr → expr → list expr → tactic expr | fn (expr.pi n bi d b) (a::as) := do infer_type a >>= unify d, fn ← head_beta (fn a), t ← whnf (b.instantiate_var a), mk_mapp_aux' fn t as | fn _ _ := pure fn meta def mk_mapp' (fn : expr) (args : list expr) : tactic expr := do t ← infer_type fn >>= whnf, mk_mapp_aux' fn t args /-- derive the equations for a specific `map` definition -/ meta def derive_map_equations (pre : option name) (n : name) (vs : list expr) (tgt : expr) : tactic unit := do e ← get_env, ((e.constructors_of n).enum_from 1).mmap' $ λ ⟨i,c⟩, do { mk_meta_var tgt >>= set_goals ∘ pure, vs ← intro_lst $ vs.map expr.local_pp_name, [α,β,f] ← tactic.intro_lst [`α,`β,`f] >>= mmap instantiate_mvars, c' ← mk_mapp c $ vs.map some ++ [α], tgt' ← infer_type c' >>= pis vs, mk_meta_var tgt' >>= set_goals ∘ pure, vs ← tactic.intro_lst $ vs.map expr.local_pp_name, vs' ← tactic.intros, c' ← mk_mapp c $ vs.map some ++ [α], arg ← mk_mapp' c' vs', n_map ← mk_const (with_prefix pre n <.> "map"), let call_map := λ x, mk_mapp' n_map (vs ++ [α,β,f,x]), lhs ← call_map arg, args ← vs'.mmap $ λ a, do { t ← infer_type a, pure ((expr.const_name (expr.get_app_fn t) = n : bool),a) }, let rec_call := args.filter_map $ λ ⟨b, e⟩, guard b >> pure e, rec_call ← rec_call.mmap call_map, rhs ← map_constructor c n f α β (vs ++ [β]) args rec_call, monad.join $ unify <$> infer_type lhs <*> infer_type rhs, eqn ← mk_app ``eq [lhs,rhs], let ws := eqn.list_local_consts, eqn ← pis ws.reverse eqn, eqn ← instantiate_mvars eqn, (_,pr) ← solve_aux eqn (tactic.intros >> refine ``(rfl)), let eqn_n := (with_prefix pre n <.> "map" <.> "equations" <.> "_eqn").append_after i, pr ← instantiate_mvars pr, add_decl $ declaration.thm eqn_n eqn.collect_univ_params eqn (pure pr), return () }, set_goals [], return () meta def derive_functor (pre : option name) : tactic unit := do vs ← local_context, `(functor %%f) ← target, env ← get_env, let n := f.get_app_fn.const_name, d ← get_decl n, refine ``( { functor . map := _ , .. } ), tgt ← target, extract_def (with_prefix pre n <.> "map") d.is_trusted $ mk_map n, when (d.is_trusted) $ do tgt ← pis vs tgt, derive_map_equations pre n vs tgt /-- `seq_apply_constructor f [x,y,z]` synthesizes `f <*> x <*> y <*> z` -/ private meta def seq_apply_constructor : expr → list (expr ⊕ expr) → tactic (list (tactic expr) × expr) | e (sum.inr x :: xs) := prod.map (cons intro1) id <$> (to_expr ``(%%e <*> %%x) >>= flip seq_apply_constructor xs) | e (sum.inl x :: xs) := prod.map (cons $ pure x) id <$> seq_apply_constructor e xs | e [] := return ([],e) /-- ``nested_traverse f α (list (array n (list α)))`` synthesizes the expression `traverse (traverse (traverse f))`. `nested_traverse` assumes that `α` appears in `(list (array n (list α)))` -/ meta def nested_traverse (f v : expr) : expr → tactic expr | t := do t ← instantiate_mvars t, mcond (succeeds $ is_def_eq t v) (pure f) (if ¬ v.occurs (t.app_fn) then do cl ← mk_app ``traversable [t.app_fn], _inst ← mk_instance cl, f' ← nested_traverse t.app_arg, mk_mapp ``traversable.traverse [t.app_fn,_inst,none,none,none,none,f'] else fail format!"type {t} is not traversable with respect to variable {v}") /-- For a sum type `inductive foo (α : Type) | foo1 : list α → ℕ → foo | ...` ``traverse_field `foo appl_inst f `α `(x : list α)`` synthesizes `traverse f x` as part of traversing `foo1`. -/ meta def traverse_field (n : name) (appl_inst cl f v e : expr) : tactic (expr ⊕ expr) := do t ← infer_type e >>= whnf, if t.get_app_fn.const_name = n then fail "recursive types not supported" else if v.occurs t then do f' ← nested_traverse f v t, pure $ sum.inr $ f' e else (is_def_eq t.app_fn cl >> sum.inr <$> mk_app ``comp.mk [e]) <|> pure (sum.inl e) /-- For a sum type `inductive foo (α : Type) | foo1 : list α → ℕ → foo | ...` ``traverse_constructor `foo1 `foo appl_inst f `α `β [`(x : list α), `(y : ℕ)]`` synthesizes `foo1 <$> traverse f x <*> pure y.` -/ meta def traverse_constructor (c n : name) (appl_inst f α β : expr) (args₀ : list expr) (args₁ : list (bool × expr)) (rec_call : list expr) : tactic expr := do g ← target, args' ← mmap (traverse_field n appl_inst g.app_fn f α) args₀, (_, args') ← mmap_accuml (λ (x : list expr) (y : bool × _), if y.1 then pure (x.tail, sum.inr x.head) else prod.mk x <$> traverse_field n appl_inst g.app_fn f α y.2) rec_call args₁, constr ← mk_const c, v ← mk_mvar, constr' ← to_expr ``(@pure _ (%%appl_inst).to_has_pure _ %%v), (vars_intro,r) ← seq_apply_constructor constr' (args₀.map sum.inl ++ args'), gs ← get_goals, set_goals [v], vs ← vars_intro.mmap id, tactic.exact (constr.mk_app vs), done, set_goals gs, return r /-- derive the `traverse` definition of a `traversable` instance -/ meta def mk_traverse (type : name) := do do ls ← local_context, [m,appl_inst,α,β,f,x] ← tactic.intro_lst [`m,`appl_inst,`α,`β,`f,`x], et ← infer_type x, reset_instance_cache, xs ← tactic.induction x, xs.mmap' (λ (x : name × list expr × list (name × expr)), do let (c,args,_) := x, (args,rec_call) ← args.mpartition $ λ e, (bnot ∘ β.occurs) <$> infer_type e, args₀ ← args.mmap $ λ a, do { b ← et.occurs <$> infer_type a, pure (b,a) }, traverse_constructor c type appl_inst f α β (ls ++ [β]) args₀ rec_call >>= tactic.exact) open applicative /-- derive the equations for a specific `traverse` definition -/ meta def derive_traverse_equations (pre : option name) (n : name) (vs : list expr) (tgt : expr) : tactic unit := do e ← get_env, ((e.constructors_of n).enum_from 1).mmap' $ λ ⟨i,c⟩, do { mk_meta_var tgt >>= set_goals ∘ pure, vs ← intro_lst $ vs.map expr.local_pp_name, [m,appl_inst,α,β,f] ← tactic.intro_lst [`m,`appl_inst,`α,`β,`f] >>= mmap instantiate_mvars, c' ← mk_mapp c $ vs.map some ++ [α], tgt' ← infer_type c' >>= pis vs, mk_meta_var tgt' >>= set_goals ∘ pure, vs ← tactic.intro_lst $ vs.map expr.local_pp_name, c' ← mk_mapp c $ vs.map some ++ [α], vs' ← tactic.intros, arg ← mk_mapp' c' vs', n_map ← mk_const (with_prefix pre n <.> "traverse"), let call_traverse := λ x, mk_mapp' n_map (vs ++ [m,appl_inst,α,β,f,x]), lhs ← call_traverse arg, args ← vs'.mmap $ λ a, do { t ← infer_type a, pure ((expr.const_name (expr.get_app_fn t) = n : bool),a) }, let rec_call := args.filter_map $ λ ⟨b, e⟩, guard b >> pure e, rec_call ← rec_call.mmap call_traverse, rhs ← traverse_constructor c n appl_inst f α β (vs ++ [β]) args rec_call, monad.join $ unify <$> infer_type lhs <*> infer_type rhs, eqn ← mk_app ``eq [lhs,rhs], let ws := eqn.list_local_consts, eqn ← pis ws.reverse eqn, eqn ← instantiate_mvars eqn, (_,pr) ← solve_aux eqn (tactic.intros >> refine ``(rfl)), let eqn_n := (with_prefix pre n <.> "traverse" <.> "equations" <.> "_eqn").append_after i, pr ← instantiate_mvars pr, add_decl $ declaration.thm eqn_n eqn.collect_univ_params eqn (pure pr), return () }, set_goals [], return () meta def derive_traverse (pre : option name) : tactic unit := do vs ← local_context, `(traversable %%f) ← target, env ← get_env, let n := f.get_app_fn.const_name, d ← get_decl n, constructor, tgt ← target, extract_def (with_prefix pre n <.> "traverse") d.is_trusted $ mk_traverse n, when (d.is_trusted) $ do tgt ← pis vs tgt, derive_traverse_equations pre n vs tgt meta def mk_one_instance (n : name) (cls : name) (tac : tactic unit) (namesp : option name) (mk_inst : name → expr → tactic expr := λ n arg, mk_app n [arg]) : tactic unit := do decl ← get_decl n, cls_decl ← get_decl cls, env ← get_env, guard (env.is_inductive n) <|> fail format!"failed to derive '{cls}', '{n}' is not an inductive type", let ls := decl.univ_params.map $ λ n, level.param n, -- incrementally build up target expression `Π (hp : p) [cls hp] ..., cls (n.{ls} hp ...)` -- where `p ...` are the inductive parameter types of `n` let tgt : expr := expr.const n ls, ⟨params, _⟩ ← open_pis (decl.type.instantiate_univ_params (decl.univ_params.zip ls)), let params := params.init, let tgt := tgt.mk_app params, tgt ← mk_inst cls tgt, tgt ← params.enum.mfoldr (λ ⟨i, param⟩ tgt, do -- add typeclass hypothesis for each inductive parameter tgt ← do { guard $ i < env.inductive_num_params n, param_cls ← mk_app cls [param], pure $ expr.pi `a binder_info.inst_implicit param_cls tgt } <|> pure tgt, pure $ tgt.bind_pi param ) tgt, () <$ mk_instance tgt <|> do (_, val) ← tactic.solve_aux tgt (do tactic.intros >> tac), val ← instantiate_mvars val, let trusted := decl.is_trusted ∧ cls_decl.is_trusted, let inst_n := with_prefix namesp n ++ cls, add_decl (declaration.defn inst_n decl.univ_params tgt val reducibility_hints.abbrev trusted), set_basic_attribute `instance inst_n namesp.is_none open interactive meta def get_equations_of (n : name) : tactic (list pexpr) := do e ← get_env, let pre := n <.> "equations", let x := e.fold [] $ λ d xs, if pre.is_prefix_of d.to_name then d.to_name :: xs else xs, x.mmap resolve_name meta def derive_lawful_functor (pre : option name) : tactic unit := do `(@is_lawful_functor %%f %%d) ← target, refine ``( { .. } ), let n := f.get_app_fn.const_name, let rules := λ r, [simp_arg_type.expr r, simp_arg_type.all_hyps], let goal := loc.ns [none], solve1 (do vs ← tactic.intros, try $ dunfold [``functor.map] (loc.ns [none]), dunfold [with_prefix pre n <.> "map",``id] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp none none ff (rules ``(functor.map_id)) [] goal), focus1 (do vs ← tactic.intros, try $ dunfold [``functor.map] (loc.ns [none]), dunfold [with_prefix pre n <.> "map",``id] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp none none ff (rules ``(functor.map_comp_map)) [] goal), return () meta def simp_functor (rs : list simp_arg_type := []) : tactic unit := simp none none ff rs [`functor_norm] (loc.ns [none]) meta def traversable_law_starter (rs : list simp_arg_type) := do vs ← tactic.intros, resetI, dunfold [``traversable.traverse,``functor.map] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp_functor rs meta def derive_lawful_traversable (pre : option name) : tactic unit := do `(@is_lawful_traversable %%f %%d) ← target, let n := f.get_app_fn.const_name, eqns ← get_equations_of (with_prefix pre n <.> "traverse"), eqns' ← get_equations_of (with_prefix pre n <.> "map"), let def_eqns := eqns.map simp_arg_type.expr ++ eqns'.map simp_arg_type.expr ++ [simp_arg_type.all_hyps], let comp_def := [ simp_arg_type.expr ``(function.comp) ], let tr_map := list.map simp_arg_type.expr [``(traversable.traverse_eq_map_id')], let natur := λ (η : expr), [simp_arg_type.expr ``(traversable.naturality_pf %%η)], let goal := loc.ns [none], constructor; [ traversable_law_starter def_eqns; refl, traversable_law_starter def_eqns; (refl <|> simp_functor (def_eqns ++ comp_def)), traversable_law_starter def_eqns; (refl <|> simp none none tt tr_map [] goal ), traversable_law_starter def_eqns; (refl <|> do η ← get_local `η <|> do { t ← mk_const ``is_lawful_traversable.naturality >>= infer_type >>= pp, fail format!"expecting an `applicative_transformation` called `η` in\nnaturality : {t}"}, simp none none tt (natur η) [] goal) ]; refl, return () open function meta def guard_class (cls : name) (hdl : derive_handler) : derive_handler := λ p n, if p.is_constant_of cls then hdl p n else pure ff meta def higher_order_derive_handler (cls : name) (tac : tactic unit) (deps : list derive_handler := []) (namesp : option name) (mk_inst : name → expr → tactic expr := λ n arg, mk_app n [arg]) : derive_handler := λ p n, do mmap' (λ f : derive_handler, f p n) deps, mk_one_instance n cls tac namesp mk_inst, pure tt meta def functor_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``functor (derive_functor nspace) [] nspace @[derive_handler] meta def functor_derive_handler : derive_handler := guard_class ``functor functor_derive_handler' meta def traversable_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``traversable (derive_traverse nspace) [functor_derive_handler' nspace] nspace @[derive_handler] meta def traversable_derive_handler : derive_handler := guard_class ``traversable traversable_derive_handler' meta def lawful_functor_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``is_lawful_functor (derive_lawful_functor nspace) [traversable_derive_handler' nspace] nspace (λ n arg, mk_mapp n [arg,none]) @[derive_handler] meta def lawful_functor_derive_handler : derive_handler := guard_class ``is_lawful_functor lawful_functor_derive_handler' meta def lawful_traversable_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``is_lawful_traversable (derive_lawful_traversable nspace) [traversable_derive_handler' nspace, lawful_functor_derive_handler' nspace] nspace (λ n arg, mk_mapp n [arg,none]) @[derive_handler] meta def lawful_traversable_derive_handler : derive_handler := guard_class ``is_lawful_traversable lawful_traversable_derive_handler' end tactic.interactive
0d9c265a71f1840b487a437b88e8bb7e9c04cfbb
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/complex/removable_singularity.lean
2e52005a61a26c40378a8f7d405942161fc74173
[ "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
9,563
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.fderiv_analytic import analysis.asymptotics.specific_asymptotics import analysis.complex.cauchy_integral /-! # Removable singularity theorem In this file we prove Riemann's removable singularity theorem: if `f : ℂ → E` is complex differentiable in a punctured neighborhood of a point `c` and is bounded in a punctured neighborhood of `c` (or, more generally, $f(z) - f(c)=o((z-c)^{-1})$), then it has a limit at `c` and the function `function.update f c (lim (𝓝[≠] c) f)` is complex differentiable in a neighborhood of `c`. -/ open topological_space metric set filter asymptotics function open_locale topology filter nnreal real universe u variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] [complete_space E] namespace complex /-- **Removable singularity** theorem, weak version. If `f : ℂ → E` is differentiable in a punctured neighborhood of a point and is continuous at this point, then it is analytic at this point. -/ lemma analytic_at_of_differentiable_on_punctured_nhds_of_continuous_at {f : ℂ → E} {c : ℂ} (hd : ∀ᶠ z in 𝓝[≠] c, differentiable_at ℂ f z) (hc : continuous_at f c) : analytic_at ℂ f c := begin rcases (nhds_within_has_basis nhds_basis_closed_ball _).mem_iff.1 hd with ⟨R, hR0, hRs⟩, lift R to ℝ≥0 using hR0.le, replace hc : continuous_on f (closed_ball c R), { refine λ z hz, continuous_at.continuous_within_at _, rcases eq_or_ne z c with rfl | hne, exacts [hc, (hRs ⟨hz, hne⟩).continuous_at] }, exact (has_fpower_series_on_ball_of_differentiable_off_countable (countable_singleton c) hc (λ z hz, hRs (diff_subset_diff_left ball_subset_closed_ball hz)) hR0).analytic_at end lemma differentiable_on_compl_singleton_and_continuous_at_iff {f : ℂ → E} {s : set ℂ} {c : ℂ} (hs : s ∈ 𝓝 c) : differentiable_on ℂ f (s \ {c}) ∧ continuous_at f c ↔ differentiable_on ℂ f s := begin refine ⟨_, λ hd, ⟨hd.mono (diff_subset _ _), (hd.differentiable_at hs).continuous_at⟩⟩, rintro ⟨hd, hc⟩ x hx, rcases eq_or_ne x c with rfl | hne, { refine (analytic_at_of_differentiable_on_punctured_nhds_of_continuous_at _ hc) .differentiable_at.differentiable_within_at, refine eventually_nhds_within_iff.2 ((eventually_mem_nhds.2 hs).mono $ λ z hz hzx, _), exact hd.differentiable_at (inter_mem hz (is_open_ne.mem_nhds hzx)) }, { simpa only [differentiable_within_at, has_fderiv_within_at, hne.nhds_within_diff_singleton] using hd x ⟨hx, hne⟩ } end lemma differentiable_on_dslope {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) : differentiable_on ℂ (dslope f c) s ↔ differentiable_on ℂ f s := ⟨λ h, h.of_dslope, λ h, (differentiable_on_compl_singleton_and_continuous_at_iff hc).mp $ ⟨iff.mpr (differentiable_on_dslope_of_nmem $ λ h, h.2 rfl) (h.mono $ diff_subset _ _), continuous_at_dslope_same.2 $ h.differentiable_at hc⟩⟩ /-- **Removable singularity** theorem: if `s` is a neighborhood of `c : ℂ`, a function `f : ℂ → E` is complex differentiable on `s \ {c}`, and $f(z) - f(c)=o((z-c)^{-1})$, then `f` redefined to be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `s`. -/ lemma differentiable_on_update_lim_of_is_o {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) (hd : differentiable_on ℂ f (s \ {c})) (ho : (λ z, f z - f c) =o[𝓝[≠] c] (λ z, (z - c)⁻¹)) : differentiable_on ℂ (update f c (lim (𝓝[≠] c) f)) s := begin set F : ℂ → E := λ z, (z - c) • f z with hF, suffices : differentiable_on ℂ F (s \ {c}) ∧ continuous_at F c, { rw [differentiable_on_compl_singleton_and_continuous_at_iff hc, ← differentiable_on_dslope hc, dslope_sub_smul] at this; try { apply_instance }, have hc : tendsto f (𝓝[≠] c) (𝓝 (deriv F c)), from continuous_at_update_same.mp (this.continuous_on.continuous_at hc), rwa hc.lim_eq }, refine ⟨(differentiable_on_id.sub_const _).smul hd, _⟩, rw ← continuous_within_at_compl_self, have H := ho.tendsto_inv_smul_nhds_zero, have H' : tendsto (λ z, (z - c) • f c) (𝓝[≠] c) (𝓝 (F c)), from (continuous_within_at_id.tendsto.sub tendsto_const_nhds).smul tendsto_const_nhds, simpa [← smul_add, continuous_within_at] using H.add H' end /-- **Removable singularity** theorem: if `s` is a punctured neighborhood of `c : ℂ`, a function `f : ℂ → E` is complex differentiable on `s`, and $f(z) - f(c)=o((z-c)^{-1})$, then `f` redefined to be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `{c} ∪ s`. -/ lemma differentiable_on_update_lim_insert_of_is_o {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝[≠] c) (hd : differentiable_on ℂ f s) (ho : (λ z, f z - f c) =o[𝓝[≠] c] (λ z, (z - c)⁻¹)) : differentiable_on ℂ (update f c (lim (𝓝[≠] c) f)) (insert c s) := differentiable_on_update_lim_of_is_o (insert_mem_nhds_iff.2 hc) (hd.mono $ λ z hz, hz.1.resolve_left hz.2) ho /-- **Removable singularity** theorem: if `s` is a neighborhood of `c : ℂ`, a function `f : ℂ → E` is complex differentiable and is bounded on `s \ {c}`, then `f` redefined to be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `s`. -/ lemma differentiable_on_update_lim_of_bdd_above {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) (hd : differentiable_on ℂ f (s \ {c})) (hb : bdd_above (norm ∘ f '' (s \ {c}))) : differentiable_on ℂ (update f c (lim (𝓝[≠] c) f)) s := differentiable_on_update_lim_of_is_o hc hd $ is_bounded_under.is_o_sub_self_inv $ let ⟨C, hC⟩ := hb in ⟨C + ‖f c‖, eventually_map.2 $ mem_nhds_within_iff_exists_mem_nhds_inter.2 ⟨s, hc, λ z hz, norm_sub_le_of_le (hC $ mem_image_of_mem _ hz) le_rfl⟩⟩ /-- **Removable singularity** theorem: if a function `f : ℂ → E` is complex differentiable on a punctured neighborhood of `c` and $f(z) - f(c)=o((z-c)^{-1})$, then `f` has a limit at `c`. -/ lemma tendsto_lim_of_differentiable_on_punctured_nhds_of_is_o {f : ℂ → E} {c : ℂ} (hd : ∀ᶠ z in 𝓝[≠] c, differentiable_at ℂ f z) (ho : (λ z, f z - f c) =o[𝓝[≠] c] (λ z, (z - c)⁻¹)) : tendsto f (𝓝[≠] c) (𝓝 $ lim (𝓝[≠] c) f) := begin rw eventually_nhds_within_iff at hd, have : differentiable_on ℂ f ({z | z ≠ c → differentiable_at ℂ f z} \ {c}), from λ z hz, (hz.1 hz.2).differentiable_within_at, have H := differentiable_on_update_lim_of_is_o hd this ho, exact continuous_at_update_same.1 (H.differentiable_at hd).continuous_at end /-- **Removable singularity** theorem: if a function `f : ℂ → E` is complex differentiable and bounded on a punctured neighborhood of `c`, then `f` has a limit at `c`. -/ lemma tendsto_lim_of_differentiable_on_punctured_nhds_of_bounded_under {f : ℂ → E} {c : ℂ} (hd : ∀ᶠ z in 𝓝[≠] c, differentiable_at ℂ f z) (hb : is_bounded_under (≤) (𝓝[≠] c) (λ z, ‖f z - f c‖)) : tendsto f (𝓝[≠] c) (𝓝 $ lim (𝓝[≠] c) f) := tendsto_lim_of_differentiable_on_punctured_nhds_of_is_o hd hb.is_o_sub_self_inv /-- The Cauchy formula for the derivative of a holomorphic function. -/ lemma two_pi_I_inv_smul_circle_integral_sub_sq_inv_smul_of_differentiable {U : set ℂ} (hU : is_open U) {c w₀ : ℂ} {R : ℝ} {f : ℂ → E} (hc : closed_ball c R ⊆ U) (hf : differentiable_on ℂ f U) (hw₀ : w₀ ∈ ball c R) : (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), ((z - w₀) ^ 2)⁻¹ • f z = deriv f w₀ := begin -- We apply the removable singularity theorem and the Cauchy formula to `dslope f w₀` have hR : 0 < R := not_le.mp (ball_eq_empty.not.mp (nonempty_of_mem hw₀).ne_empty), have hf' : differentiable_on ℂ (dslope f w₀) U, from (differentiable_on_dslope (hU.mem_nhds ((ball_subset_closed_ball.trans hc) hw₀))).mpr hf, have h0 := (hf'.diff_cont_on_cl_ball hc).two_pi_I_inv_smul_circle_integral_sub_inv_smul hw₀, rw [← dslope_same, ← h0], congr' 1, transitivity ∮ z in C(c, R), ((z - w₀) ^ 2)⁻¹ • (f z - f w₀), { have h1 : continuous_on (λ (z : ℂ), ((z - w₀) ^ 2)⁻¹) (sphere c R), { refine ((continuous_id'.sub continuous_const).pow 2).continuous_on.inv₀ (λ w hw h, _), exact sphere_disjoint_ball.ne_of_mem hw hw₀ (sub_eq_zero.mp (sq_eq_zero_iff.mp h)) }, have h2 : circle_integrable (λ (z : ℂ), ((z - w₀) ^ 2)⁻¹ • f z) c R, { refine continuous_on.circle_integrable (pos_of_mem_ball hw₀).le _, exact h1.smul (hf.continuous_on.mono (sphere_subset_closed_ball.trans hc)) }, have h3 : circle_integrable (λ (z : ℂ), ((z - w₀) ^ 2)⁻¹ • f w₀) c R, from continuous_on.circle_integrable (pos_of_mem_ball hw₀).le (h1.smul continuous_on_const), have h4 : ∮ (z : ℂ) in C(c, R), ((z - w₀) ^ 2)⁻¹ = 0, by simpa using circle_integral.integral_sub_zpow_of_ne (dec_trivial : (-2 : ℤ) ≠ -1) c w₀ R, simp only [smul_sub, circle_integral.integral_sub h2 h3, h4, circle_integral.integral_smul_const, zero_smul, sub_zero] }, { refine circle_integral.integral_congr (pos_of_mem_ball hw₀).le (λ z hz, _), simp only [dslope_of_ne, metric.sphere_disjoint_ball.ne_of_mem hz hw₀, slope, ← smul_assoc, sq, mul_inv, ne.def, not_false_iff, vsub_eq_sub, algebra.id.smul_eq_mul] } end end complex
ae6d205b92193a166f109ea33cb5dc59748c99f3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/real/division.lean
d0a54beb12779ac14941307d025b92d8123444b6
[ "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
23,997
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability and excluded middle. -/ import data.real.basic data.real.order data.rat data.nat open rat open nat open eq.ops pnat classical namespace rat_seq local postfix ⁻¹ := pnat.inv ----------------------------- -- Facts about absolute values of sequences, to define inverse definition s_abs (s : seq) : seq := λ n, abs (s n) theorem abs_reg_of_reg {s : seq} (Hs : regular s) : regular (s_abs s) := begin intros, apply le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Hs end theorem abs_pos_of_nonzero {s : seq} (Hs : regular s) (Hnz : sep s zero) : ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m) ≥ N⁻¹ := begin rewrite [↑sep at Hnz, ↑s_lt at Hnz], apply or.elim Hnz, intro Hnz1, have H' : pos (sneg s), begin apply pos_of_pos_equiv, rotate 2, apply Hnz1, rotate 1, apply s_zero_add, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end, cases bdd_away_of_pos (reg_neg_reg Hs) H' with [N, HN], existsi N, intro m Hm, apply le.trans, apply HN m Hm, rewrite ↑sneg, apply neg_le_abs_self, intro Hnz2, let H' := pos_of_pos_equiv (reg_add_reg Hs (reg_neg_reg zero_is_reg)) (s_add_zero s Hs) Hnz2, let H'' := bdd_away_of_pos Hs H', cases H'' with [N, HN], existsi N, intro m Hm, apply le.trans, apply HN m Hm, apply le_abs_self end theorem abs_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_abs s ≡ s_abs t := begin rewrite [↑equiv at *], intro n, rewrite ↑s_abs, apply le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Heq end theorem sep_zero_of_pos {s : seq} (Hs : regular s) (Hpos : pos s) : sep s zero := begin apply or.inr, apply pos_of_pos_equiv, rotate 2, apply Hpos, apply Hs, apply equiv.symm, apply s_sub_zero Hs end ------------------------ -- This section could be cleaned up. private noncomputable definition pb {s : seq} (Hs : regular s) (Hpos : pos s) := some (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private noncomputable definition ps {s : seq} (Hs : regular s) (Hsep : sep s zero) := some (abs_pos_of_nonzero Hs Hsep) private theorem pb_spec {s : seq} (Hs : regular s) (Hpos : pos s) : ∀ m : ℕ+, m ≥ (pb Hs Hpos) → abs (s m) ≥ (pb Hs Hpos)⁻¹ := some_spec (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private theorem ps_spec {s : seq} (Hs : regular s) (Hsep : sep s zero) : ∀ m : ℕ+, m ≥ (ps Hs Hsep) → abs (s m) ≥ (ps Hs Hsep)⁻¹ := some_spec (abs_pos_of_nonzero Hs Hsep) noncomputable definition s_inv {s : seq} (Hs : regular s) (n : ℕ+) : ℚ := if H : sep s zero then (if n < (ps Hs H) then 1 / (s ((ps Hs H) * (ps Hs H) * (ps Hs H))) else 1 / (s ((ps Hs H) * (ps Hs H) * n))) else 0 private theorem peq {s : seq} (Hsep : sep s zero) (Hpos : pos s) (Hs : regular s) : pb Hs Hpos = ps Hs Hsep := rfl private theorem s_inv_of_sep_lt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n < (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) := begin apply eq.trans, apply dif_pos Hsep, apply dif_pos Hn end private theorem s_inv_of_sep_gt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n ≥ (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * n) := begin apply eq.trans, apply dif_pos Hsep, apply dif_neg (pnat.not_lt_of_ge Hn) end private theorem s_inv_of_pos_lt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : ℕ+} (Hn : n < (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * (pb Hs Hpos)) := s_inv_of_sep_lt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem s_inv_of_pos_gt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : ℕ+} (Hn : n ≥ (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * n) := s_inv_of_sep_gt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem le_ps {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : ℕ+) : abs (s_inv Hs n) ≤ (rat_of_pnat (ps Hs Hsep)) := if Hn : n < ps Hs Hsep then (begin rewrite [(s_inv_of_sep_lt_p Hs Hsep Hn), abs_one_div], apply div_le_pnat, apply ps_spec, apply pnat.mul_le_mul_left end) else (begin rewrite [(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hn)), abs_one_div], apply div_le_pnat, apply ps_spec, rewrite pnat.mul_assoc, apply pnat.mul_le_mul_right end) theorem s_inv_zero : s_inv zero_is_reg = zero := funext (λ n, dif_neg (!not_sep_self)) private theorem s_inv_of_zero' {s : seq} (Hs : regular s) (Hz : ¬ sep s zero) (n : ℕ+) : s_inv Hs n = 0 := dif_neg Hz theorem s_inv_of_zero {s : seq} (Hs : regular s) (Hz : ¬ sep s zero) : s_inv Hs = zero := begin apply funext, intro n, apply s_inv_of_zero' Hs Hz n end private theorem s_ne_zero_of_ge_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n ≥ (ps Hs Hsep)) : s n ≠ 0 := begin let Hps := ps_spec Hs Hsep, apply ne_zero_of_abs_ne_zero, apply ne_of_gt, apply gt_of_ge_of_gt, apply Hps, apply Hn, apply pnat.inv_pos end theorem reg_inv_reg {s : seq} (Hs : regular s) (Hsep : sep s zero) : regular (s_inv Hs) := begin rewrite ↑regular, intros, have Hsp : s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep !pnat.mul_le_mul_left, have Hspn : s ((ps Hs Hsep) * (ps Hs Hsep) * n) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * n ≥ ps Hs Hsep, by rewrite pnat.mul_assoc; apply pnat.mul_le_mul_right), have Hspm : s ((ps Hs Hsep) * (ps Hs Hsep) * m) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * m ≥ ps Hs Hsep, by rewrite pnat.mul_assoc; apply pnat.mul_le_mul_right), cases em (m < ps Hs Hsep) with [Hmlt, Hmlt], cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_lt_p Hs Hsep Hnlt)], rewrite [sub_self, abs_zero], apply add_invs_nonneg, rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt))], rewrite [(!div_sub_div Hsp Hspn), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hsp Hspn), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hmlt), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply add_le_add_right, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hmlt, cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hnlt), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hsp), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hsp), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hnlt), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply rat.add_le_add_left, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hnlt, rewrite [(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hspn), div_eq_mul_one_div, abs_mul, *one_mul, *mul_one], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hspn), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply le.refl end theorem s_inv_ne_zero {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : ℕ+) : s_inv Hs n ≠ 0 := if H : n ≥ ps Hs Hsep then (begin rewrite (s_inv_of_sep_gt_p Hs Hsep H), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.le_trans, apply H, apply pnat.mul_le_mul_left end) else (begin rewrite (s_inv_of_sep_lt_p Hs Hsep (pnat.lt_of_not_le H)), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.mul_le_mul_left end) protected theorem mul_inv {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul s (s_inv Hs) ≡ one := begin let Rsi := reg_inv_reg Hs Hsep, let Rssi := reg_mul_reg Hs Rsi, apply eq_of_bdd Rssi one_is_reg, intros, existsi max (ps Hs Hsep) j, intro n Hn, have Hnz : s_inv Hs ((K₂ s (s_inv Hs)) * 2 * n) ≠ 0, from s_inv_ne_zero Hs Hsep _, rewrite [↑smul, ↑one, mul.comm, -(mul_one_div_cancel Hnz), -mul_sub_left_distrib, abs_mul], apply le.trans, apply mul_le_mul_of_nonneg_right, apply canon_2_bound_right s, apply Rsi, apply abs_nonneg, have Hp : (K₂ s (s_inv Hs)) * 2 * n ≥ ps Hs Hsep, begin apply pnat.le_trans, apply pnat.max_left, rotate 1, apply pnat.le_trans, apply Hn, apply pnat.mul_le_mul_left end, have Hnz' : s (((ps Hs Hsep) * (ps Hs Hsep)) * ((K₂ s (s_inv Hs)) * 2 * n)) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show ps Hs Hsep ≤ ((ps Hs Hsep) * (ps Hs Hsep)) * ((K₂ s (s_inv Hs)) * 2 * n), by rewrite *pnat.mul_assoc; apply pnat.mul_le_mul_right), rewrite [(s_inv_of_sep_gt_p Hs Hsep Hp), (division_ring.one_div_one_div Hnz')], apply rat.le_trans, apply mul_le_mul_of_nonneg_left, apply Hs, apply le_of_lt, apply rat_of_pnat_is_pos, rewrite [left_distrib, pnat.mul_comm ((ps Hs Hsep) * (ps Hs Hsep)), *pnat.mul_assoc, *(@pnat.inv_mul_eq_mul_inv (K₂ s (s_inv Hs))), -*mul.assoc, *pnat.inv_cancel_left, *one_mul, -(pnat.add_halves j)], apply add_le_add, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, apply pnat.max_right, rotate 1, apply pnat.le_trans, apply Hn, apply pnat.mul_le_mul_right end protected theorem inv_mul {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul (s_inv Hs) s ≡ one := begin apply equiv.trans, rotate 3, apply s_mul_comm, apply rat_seq.mul_inv, repeat (assumption | apply reg_mul_reg | apply reg_inv_reg | apply zero_is_reg) end theorem sep_of_equiv_sep {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) (Hsep : sep s zero) : sep t zero := begin apply or.elim Hsep, intro Hslt, apply or.inl, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, intro Hslt, apply or.inr, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 5, apply equiv.refl, repeat (assumption | apply reg_neg_reg | apply reg_add_reg | apply zero_is_reg) end theorem inv_unique {s t : seq} (Hs : regular s) (Ht : regular t) (Hsep : sep s zero) (Heq : smul s t ≡ one) : s_inv Hs ≡ t := begin apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_one, rotate 1, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply equiv.refl, apply equiv.symm, apply Heq, apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_assoc, rotate 3, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply rat_seq.inv_mul, rotate 1, apply equiv.refl, apply s_one_mul, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg | apply one_is_reg) end theorem inv_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_inv Hs ≡ s_inv Ht := if Hsep : sep s zero then (begin note Hsept := sep_of_equiv_sep Hs Ht Heq Hsep, have Hm : smul t (s_inv Hs) ≡ smul s (s_inv Hs), begin apply mul_well_defined, repeat (assumption | apply reg_inv_reg), apply equiv.symm s t Heq, apply equiv.refl end, apply equiv.symm, apply inv_unique, rotate 2, apply equiv.trans, rotate 3, apply Hm, apply rat_seq.mul_inv, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg), apply one_is_reg end) else (have H : s_inv Hs = zero, from funext (λ n, dif_neg Hsep), have Hsept : ¬ sep t zero, from assume H', Hsep (sep_of_equiv_sep Ht Hs (equiv.symm _ _ Heq) H'), have H' : s_inv Ht = zero, from funext (λ n, dif_neg Hsept), by rewrite [H', H]; apply equiv.refl) theorem s_neg_neg {s : seq} : sneg (sneg s) ≡ s := begin rewrite [↑equiv, ↑sneg], intro n, rewrite [neg_neg, sub_self, abs_zero], apply add_invs_nonneg end theorem s_neg_sub {s t : seq} (Hs : regular s) (Ht : regular t) : sneg (sadd s (sneg t)) ≡ sadd t (sneg s) := begin apply equiv.trans, rotate 3, apply s_neg_add_eq_s_add_neg, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_neg, apply s_add_comm, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_total {s t : seq} (Hs : regular s) (Ht : regular t) : s_le s t ∨ s_le t s := if H : s_le s t then or.inl H else or.inr begin rewrite [↑s_le at *], have H' : ∃ n : ℕ+, -n⁻¹ > sadd t (sneg s) n, begin apply by_contradiction, intro Hex, have Hex' : ∀ n : ℕ+, -n⁻¹ ≤ sadd t (sneg s) n, begin intro m, apply by_contradiction, intro Hm, note Hm' := lt_of_not_ge Hm, note Hex'' := exists.intro m Hm', apply Hex Hex'' end, apply H Hex' end, eapply exists.elim H', intro m Hm, note Hm' := neg_lt_neg Hm, rewrite neg_neg at Hm', apply s_nonneg_of_pos, rotate 1, apply pos_of_pos_equiv, rotate 1, apply s_neg_sub, rotate 2, rewrite [↑pos, ↑sneg], existsi m, apply Hm', repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_not_lt {s t : seq} (Hle : ¬ s_lt s t) : s_le t s := begin rewrite [↑s_le, ↑nonneg, ↑s_lt at Hle, ↑pos at Hle], let Hle' := iff.mp forall_iff_not_exists Hle, intro n, let Hn := neg_le_neg (le_of_not_gt (Hle' n)), rewrite [↑sadd, ↑sneg, add_neg_eq_neg_add_rev], apply Hn end theorem sep_of_nequiv {s t : seq} (Hs : regular s) (Ht : regular t) (Hneq : ¬ equiv s t) : sep s t := begin rewrite ↑sep, apply by_contradiction, intro Hnor, let Hand := iff.mp !not_or_iff_not_and_not Hnor, let Hle1 := s_le_of_not_lt (and.left Hand), let Hle2 := s_le_of_not_lt (and.right Hand), apply Hneq (equiv_of_le_of_ge Hs Ht Hle2 Hle1) end theorem s_zero_inv_equiv_zero : s_inv zero_is_reg ≡ zero := by rewrite s_inv_zero; apply equiv.refl theorem lt_or_equiv_of_le {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : s_le s t) : s_lt s t ∨ s ≡ t := if H : s ≡ t then or.inr H else or.inl (lt_of_le_and_sep Hs Ht (and.intro Hle (sep_of_nequiv Hs Ht H))) theorem s_le_of_equiv_le_left {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : s ≡ t) (Hle : s_le s u) : s_le t u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_equiv_le_right {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : t ≡ u) (Hle : s_le s t) : s_le s u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply Heq, apply equiv.refl, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end ----------------------------- noncomputable definition r_inv (s : reg_seq) : reg_seq := reg_seq.mk (s_inv (reg_seq.is_reg s)) (if H : sep (reg_seq.sq s) zero then reg_inv_reg (reg_seq.is_reg s) H else have Hz : s_inv (reg_seq.is_reg s) = zero, from funext (λ n, dif_neg H), by rewrite Hz; apply zero_is_reg) theorem r_inv_zero : requiv (r_inv r_zero) r_zero := s_zero_inv_equiv_zero theorem r_inv_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_inv s) (r_inv t) := inv_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_le_total (s t : reg_seq) : r_le s t ∨ r_le t s := s_le_total (reg_seq.is_reg s) (reg_seq.is_reg t) theorem r_mul_inv (s : reg_seq) (Hsep : r_sep s r_zero) : requiv (s * (r_inv s)) r_one := rat_seq.mul_inv (reg_seq.is_reg s) Hsep theorem r_sep_of_nequiv (s t : reg_seq) (Hneq : ¬ requiv s t) : r_sep s t := sep_of_nequiv (reg_seq.is_reg s) (reg_seq.is_reg t) Hneq theorem r_lt_or_equiv_of_le (s t : reg_seq) (Hle : r_le s t) : r_lt s t ∨ requiv s t := lt_or_equiv_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle theorem r_le_of_equiv_le_left {s t u : reg_seq} (Heq : requiv s t) (Hle : r_le s u) : r_le t u := s_le_of_equiv_le_left (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle theorem r_le_of_equiv_le_right {s t u : reg_seq} (Heq : requiv t u) (Hle : r_le s t) : r_le s u := s_le_of_equiv_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle definition r_abs (s : reg_seq) : reg_seq := reg_seq.mk (s_abs (reg_seq.sq s)) (abs_reg_of_reg (reg_seq.is_reg s)) theorem r_abs_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_abs s) (r_abs t) := abs_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H end rat_seq namespace real open [class] rat_seq protected noncomputable definition inv (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (rat_seq.r_inv a)) (λ a b H, quot.sound (rat_seq.r_inv_well_defined H)) attribute [instance, priority real.prio] noncomputable definition real_has_inv : has_inv real := has_inv.mk real.inv protected noncomputable definition div (x y : ℝ) : ℝ := x * y⁻¹ noncomputable definition real_has_div : has_div real := has_div.mk real.div local attribute real_has_div [instance, priority real.prio] protected theorem le_total (x y : ℝ) : x ≤ y ∨ y ≤ x := quot.induction_on₂ x y (λ s t, rat_seq.r_le_total s t) protected theorem mul_inv_cancel' (x : ℝ) : x ≢ 0 → x * x⁻¹ = 1 := quot.induction_on x (λ s H, quot.sound (rat_seq.r_mul_inv s H)) protected theorem inv_mul_cancel' (x : ℝ) : x ≢ 0 → x⁻¹ * x = 1 := by rewrite real.mul_comm; apply real.mul_inv_cancel' theorem neq_of_sep {x y : ℝ} (H : x ≢ y) : ¬ x = y := assume Heq, !not_sep_self (Heq ▸ H) theorem sep_of_neq {x y : ℝ} : ¬ x = y → x ≢ y := quot.induction_on₂ x y (λ s t H, rat_seq.r_sep_of_nequiv s t (assume Heq, H (quot.sound Heq))) theorem sep_is_neq (x y : ℝ) : (x ≢ y) = (¬ x = y) := propext (iff.intro neq_of_sep sep_of_neq) protected theorem mul_inv_cancel (x : ℝ) : x ≠ 0 → x * x⁻¹ = 1 := !sep_is_neq ▸ !real.mul_inv_cancel' protected theorem inv_mul_cancel (x : ℝ) : x ≠ 0 → x⁻¹ * x = 1 := !sep_is_neq ▸ !real.inv_mul_cancel' protected theorem inv_zero : (0 : ℝ)⁻¹ = 0 := quot.sound (rat_seq.r_inv_zero) protected theorem lt_or_eq_of_le (x y : ℝ) : x ≤ y → x < y ∨ x = y := quot.induction_on₂ x y (λ s t H, or.elim (rat_seq.r_lt_or_equiv_of_le s t H) (assume H1, or.inl H1) (assume H2, or.inr (quot.sound H2))) protected theorem le_iff_lt_or_eq (x y : ℝ) : x ≤ y ↔ x < y ∨ x = y := iff.intro (real.lt_or_eq_of_le x y) (real.le_of_lt_or_eq x y) noncomputable definition dec_lt : decidable_rel real.lt := begin rewrite ↑decidable_rel, intros, apply prop_decidable end attribute [trans_instance] protected noncomputable definition discrete_linear_ordered_field : discrete_linear_ordered_field ℝ := ⦃ discrete_linear_ordered_field, real.comm_ring, real.ordered_ring, le_total := real.le_total, mul_inv_cancel := real.mul_inv_cancel, inv_mul_cancel := real.inv_mul_cancel, zero_lt_one := real.zero_lt_one, inv_zero := real.inv_zero, le_iff_lt_or_eq := real.le_iff_lt_or_eq, decidable_lt := dec_lt ⦄ theorem of_rat_divide (x y : ℚ) : of_rat (x / y) = of_rat x / of_rat y := by_cases (assume yz : y = 0, by krewrite [yz, div_zero, +of_rat_zero, div_zero]) (assume ynz : y ≠ 0, have ynz' : of_rat y ≠ 0, from assume yz', ynz (of_rat.inj yz'), !eq_div_of_mul_eq ynz' (by krewrite [-of_rat_mul, !div_mul_cancel ynz])) open int theorem of_int_div (x y : ℤ) (H : y ∣ x) : of_int (x / y) = of_int x / of_int y := by rewrite [of_int_eq, rat.of_int_div H, of_rat_divide] theorem of_nat_div (x y : ℕ) (H : y ∣ x) : of_nat (x / y) = of_nat x / of_nat y := by rewrite [of_nat_eq, rat.of_nat_div H, of_rat_divide] /- useful for proving equalities -/ theorem eq_zero_of_nonneg_of_forall_lt {x : ℝ} (xnonneg : x ≥ 0) (H : ∀ ε : ℝ, ε > 0 → x < ε) : x = 0 := decidable.by_contradiction (suppose x ≠ 0, have x > 0, from lt_of_le_of_ne xnonneg (ne.symm this), have x < x, from H x this, show false, from !lt.irrefl this) theorem eq_zero_of_nonneg_of_forall_le {x : ℝ} (xnonneg : x ≥ 0) (H : ∀ ε : ℝ, ε > 0 → x ≤ ε) : x = 0 := have ∀ ε : ℝ, ε > 0 → x < ε, from take ε, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, have ε / 2 < ε, from div_two_lt_of_pos `ε > 0`, begin apply lt_of_le_of_lt, apply H _ e2pos, apply this end, eq_zero_of_nonneg_of_forall_lt xnonneg this theorem eq_zero_of_forall_abs_le {x : ℝ} (H : ∀ ε : ℝ, ε > 0 → abs x ≤ ε) : x = 0 := by_contradiction (suppose x ≠ 0, have abs x = 0, from eq_zero_of_nonneg_of_forall_le !abs_nonneg H, show false, from `x ≠ 0` (eq_zero_of_abs_eq_zero this)) theorem eq_of_forall_abs_sub_le {x y : ℝ} (H : ∀ ε : ℝ, ε > 0 → abs (x - y) ≤ ε) : x = y := have x - y = 0, from eq_zero_of_forall_abs_le H, eq_of_sub_eq_zero this end real
d2777849a9b95f954133524daddc1e701ad1f7ca
02fbe05a45fda5abde7583464416db4366eedfbf
/tests/lean/run/psum_wf_rec.lean
9b849e4553a7a072cc79ff50a39dd9d99a29e540
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
826
lean
def psum.alt.sizeof {α β} [has_sizeof α] [has_sizeof β] : psum α β → nat | (psum.inl a) := 2*sizeof a + 2 | (psum.inr b) := 2*sizeof b + 1 def sum_has_sizeof_2 {α β} [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) := ⟨psum.alt.sizeof⟩ local attribute [instance] sum_has_sizeof_2 local attribute [simp] nat.add_comm nat.add_left_comm nat.add_assoc nat.mul_assoc nat.mul_comm nat.one_mul mutual def f, g with f : ℕ → ℕ | n := g n + 1 with g : ℕ → ℕ | 0 := 0 | (n+1) := /- The following is a hint for the equation compiler. We will be able to delete it as soon as we have decision procedures for arithmetic -/ have 2 + n * 2 < 1 + 2 * (n + 1), from begin rw [nat.left_distrib], simp, well_founded_tactics.cancel_nat_add_lt, tactic.comp_val end, f n
a0b4d69c67e303556ad58973d30546b145a90984
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/group_action/embedding.lean
25553f746f4f858d97b1973354b72c0f00a910d3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,898
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.group_action.group import group_theory.group_action.pi /-! # Group actions on embeddings This file provides a `mul_action G (α ↪ β)` instance that agrees with the `mul_action G (α → β)` instances defined by `pi.mul_action`. Note that unlike the `pi` instance, this requires `G` to be a group. -/ universes u v w variables {G G' α β : Type*} namespace function.embedding @[to_additive function.embedding.has_vadd] instance [group G] [mul_action G β] : has_scalar G (α ↪ β) := ⟨λ g f, f.trans (mul_action.to_perm g).to_embedding⟩ @[to_additive] lemma smul_def [group G] [mul_action G β] (g : G) (f : α ↪ β) : g • f = f.trans (mul_action.to_perm g).to_embedding := rfl @[simp, to_additive] lemma smul_apply [group G] [mul_action G β] (g : G) (f : α ↪ β) (a : α) : (g • f) a = g • f a := rfl @[to_additive] lemma coe_smul [group G] [mul_action G β] (g : G) (f : α ↪ β) : ⇑(g • f) = g • f := rfl instance [group G] [group G'] [has_scalar G G'] [mul_action G β] [mul_action G' β] [is_scalar_tower G G' β] : is_scalar_tower G G' (α ↪ β) := ⟨λ x y z, function.embedding.ext $ λ i, smul_assoc x y (z i)⟩ @[to_additive] instance [group G] [group G'] [mul_action G β] [mul_action G' β] [smul_comm_class G G' β] : smul_comm_class G G' (α ↪ β) := ⟨λ x y z, function.embedding.ext $ λ i, smul_comm x y (z i)⟩ instance [group G] [mul_action G β] [mul_action Gᵐᵒᵖ β] [is_central_scalar G β] : is_central_scalar G (α ↪ β) := ⟨λ r m, function.embedding.ext $ λ i, op_smul_eq_smul _ _⟩ @[to_additive] instance [group G] [mul_action G β] : mul_action G (α ↪ β) := fun_like.coe_injective.mul_action _ coe_smul end function.embedding
ff070e06a66e9d8b16380b80bc0a9d5efb4637e1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/num/prime_auto.lean
92aae515cff47070488daf91d75c89d26386d358
[]
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,882
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.num.lemmas import Mathlib.data.nat.prime import Mathlib.tactic.ring import Mathlib.PostPort namespace Mathlib /-! # Primality for binary natural numbers This file defines versions of `nat.min_fac` and `nat.prime` for `num` and `pos_num`. As with other `num` definitions, they are not intended for general use (`nat` should be used instead of `num` in most cases) but they can be used in contexts where kernel computation is required, such as proofs by `rfl` and `dec_trivial`, as well as in `#reduce`. The default decidable instance for `nat.prime` is optimized for VM evaluation, so it should be preferred within `#eval` or in tactic execution, while for proofs the `norm_num` tactic can be used to construct primality and non-primality proofs more efficiently than kernel computation. Nevertheless, sometimes proof by computational reflection requires natural number computations, and `num` implements algorithms directly on binary natural numbers for this purpose. -/ namespace pos_num /-- Auxiliary function for computing the smallest prime factor of a `pos_num`. Unlike `nat.min_fac_aux`, we use a natural number `fuel` variable that is set to an upper bound on the number of iterations. It is initialized to the number `n` we are determining primality for. Even though this is exponential in the input (since it is a `nat`, not a `num`), it will get lazily evaluated during kernel reduction, so we will only require about `sqrt n` unfoldings, for the `sqrt n` iterations of the loop. -/ def min_fac_aux (n : pos_num) : ℕ → pos_num → pos_num := sorry theorem min_fac_aux_to_nat {fuel : ℕ} {n : pos_num} {k : pos_num} (h : nat.sqrt ↑n < fuel + ↑(bit1 k)) : ↑(min_fac_aux n fuel k) = nat.min_fac_aux ↑n ↑(bit1 k) := sorry /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : pos_num → pos_num := sorry @[simp] theorem min_fac_to_nat (n : pos_num) : ↑(min_fac n) = nat.min_fac ↑n := sorry /-- Primality predicate for a `pos_num`. -/ @[simp] def prime (n : pos_num) := nat.prime ↑n protected instance decidable_prime : decidable_pred prime := sorry end pos_num namespace num /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : num → pos_num := sorry @[simp] theorem min_fac_to_nat (n : num) : ↑(min_fac n) = nat.min_fac ↑n := num.cases_on n (idRhs (↑(min_fac 0) = ↑(min_fac 0)) rfl) fun (n : pos_num) => idRhs (↑(pos_num.min_fac n) = nat.min_fac ↑n) (pos_num.min_fac_to_nat n) /-- Primality predicate for a `num`. -/ @[simp] def prime (n : num) := nat.prime ↑n protected instance decidable_prime : decidable_pred prime := sorry end Mathlib
4a4057b8bd587a9a4532b56334206650eed8bb3f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/field/basic.lean
78eb496fa6ecaf6088a5894f1a7215d50512a70b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
13,309
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.field.defs import algebra.group_with_zero.units.lemmas import algebra.hom.ring import algebra.ring.inj_surj /-! # Lemmas about division (semi)rings and (semi)fields -/ open function order_dual set set_option old_structure_cmd true universe u variables {α β K : Type*} section division_semiring variables [division_semiring α] {a b c : α} lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := by simp_rw [div_eq_mul_inv, add_mul] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := (add_div _ _ _).symm lemma same_add_div (h : b ≠ 0) : (b + a) / b = 1 + a / b := by rw [←div_self h, add_div] lemma div_add_same (h : b ≠ 0) : (a + b) / b = a / b + 1 := by rw [←div_self h, add_div] lemma one_add_div (h : b ≠ 0 ) : 1 + a / b = (b + a) / b := (same_add_div h).symm lemma div_add_one (h : b ≠ 0) : a / b + 1 = (a + b) / b := (div_add_same h).symm lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [mul_add, one_div_mul_cancel ha, add_mul, one_mul, mul_assoc, mul_one_div_cancel hb, mul_one, add_comm] lemma add_div_eq_mul_add_div (a b : α) (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by rw [add_div, mul_div_cancel _ hc] @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] end division_semiring section division_monoid variables [division_monoid K] [has_distrib_neg K] {a b : K} lemma one_div_neg_one_eq_neg_one : (1:K) / (-1) = -1 := have (-1) * (-1) = (1:K), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one_right this) lemma one_div_neg_eq_neg_one_div (a : K) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg, mul_one] lemma div_neg_eq_neg_div (a b : K) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b / a) : by rw mul_one_div lemma neg_div (a b : K) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' (a b : K) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : K) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma div_neg (a : K) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv end division_monoid section division_ring variables [division_ring K] {a b : K} @[simp] lemma div_neg_self {a : K} (h : a ≠ 0) : a / -a = -1 := by rw [div_neg_eq_neg_div, div_self h] @[simp] lemma neg_div_self {a : K} (h : a ≠ 0) : (-a) / a = -1 := by rw [neg_div, div_self h] lemma div_sub_div_same (a b c : K) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma same_sub_div {a b : K} (h : b ≠ 0) : (b - a) / b = 1 - a / b := by simpa only [← @div_self _ _ b h] using (div_sub_div_same b a b).symm lemma one_sub_div {a b : K} (h : b ≠ 0) : 1 - a / b = (b - a) / b := (same_sub_div h).symm lemma div_sub_same {a b : K} (h : b ≠ 0) : (a - b) / b = a / b - 1 := by simpa only [← @div_self _ _ b h] using (div_sub_div_same a b b).symm lemma div_sub_one {a b : K} (h : b ≠ 0) : a / b - 1 = (a - b) / b := (div_sub_same h).symm lemma sub_div (a b c : K) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm /-- See `inv_sub_inv` for the more convenient version when `K` is commutative. -/ lemma inv_sub_inv' {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = a⁻¹ * (b - a) * b⁻¹ := by rw [mul_sub, sub_mul, mul_inv_cancel_right₀ hb, inv_mul_cancel ha, one_mul] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] @[priority 100] -- see Note [lower instance priority] instance division_ring.is_domain : is_domain K := { ..‹division_ring K›, ..(by apply_instance : no_zero_divisors K) } end division_ring section semifield variables [semifield α] {a b c d : α} lemma div_add_div (a : α) (c : α) (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] lemma one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [div_add_div _ _ ha hb, one_mul, mul_one, add_comm] lemma inv_add_inv (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] end semifield section field variable [field K] local attribute [simp] mul_assoc mul_comm mul_left_comm @[field_simps] lemma div_sub_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_sub_inv {a b : K} (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] @[field_simps] lemma sub_div' (a b c : K) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_sub' (a b c : K) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.is_domain : is_domain K := { ..division_ring.is_domain } end field namespace ring_hom protected lemma injective [division_ring α] [semiring β] [nontrivial β] (f : α →+* β) : injective f := (injective_iff_map_eq_zero f).2 $ λ x, (map_eq_zero f).1 end ring_hom section noncomputable_defs variables {R : Type*} [nontrivial R] /-- Constructs a `division_ring` structure on a `ring` consisting only of units and 0. -/ noncomputable def division_ring_of_is_unit_or_eq_zero [hR : ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : division_ring R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } /-- Constructs a `field` structure on a `comm_ring` consisting only of units and 0. See note [reducible non-instances]. -/ @[reducible] noncomputable def field_of_is_unit_or_eq_zero [hR : comm_ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : field R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } end noncomputable_defs /-- Pullback a `division_semiring` along an injective function. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.division_semiring [division_semiring β] [has_zero α] [has_mul α] [has_add α] [has_one α] [has_inv α] [has_div α] [has_smul ℕ α] [has_pow α ℕ] [has_pow α ℤ] [has_nat_cast α] (f : α → β) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : division_semiring α := { .. hf.group_with_zero f zero one mul inv div npow zpow, .. hf.semiring f zero one add mul nsmul npow nat_cast } /-- Pullback a `division_ring` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.division_ring [division_ring K] {K'} [has_zero K'] [has_one K'] [has_add K'] [has_mul K'] [has_neg K'] [has_sub K'] [has_inv K'] [has_div K'] [has_smul ℕ K'] [has_smul ℤ K'] [has_smul ℚ K'] [has_pow K' ℕ] [has_pow K' ℤ] [has_nat_cast K'] [has_int_cast K'] [has_rat_cast K'] (f : K' → K) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (qsmul : ∀ x (n : ℚ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (rat_cast : ∀ n : ℚ, f n = n) : division_ring K' := { rat_cast := coe, rat_cast_mk := λ a b h1 h2, hf (by erw [rat_cast, mul, inv, int_cast, nat_cast]; exact division_ring.rat_cast_mk a b h1 h2), qsmul := (•), qsmul_eq_mul' := λ a x, hf (by erw [qsmul, mul, rat.smul_def, rat_cast]), .. hf.group_with_zero f zero one mul inv div npow zpow, .. hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } /-- Pullback a `field` along an injective function. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.semifield [semifield β] [has_zero α] [has_mul α] [has_add α] [has_one α] [has_inv α] [has_div α] [has_smul ℕ α] [has_pow α ℕ] [has_pow α ℤ] [has_nat_cast α] (f : α → β) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : semifield α := { .. hf.comm_group_with_zero f zero one mul inv div npow zpow, .. hf.comm_semiring f zero one add mul nsmul npow nat_cast } /-- Pullback a `field` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.field [field K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] [has_smul ℕ K'] [has_smul ℤ K'] [has_smul ℚ K'] [has_pow K' ℕ] [has_pow K' ℤ] [has_nat_cast K'] [has_int_cast K'] [has_rat_cast K'] (f : K' → K) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (qsmul : ∀ x (n : ℚ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (rat_cast : ∀ n : ℚ, f n = n) : field K' := { rat_cast := coe, rat_cast_mk := λ a b h1 h2, hf (by erw [rat_cast, mul, inv, int_cast, nat_cast]; exact division_ring.rat_cast_mk a b h1 h2), qsmul := (•), qsmul_eq_mul' := λ a x, hf (by erw [qsmul, mul, rat.smul_def, rat_cast]), .. hf.comm_group_with_zero f zero one mul inv div npow zpow, .. hf.comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } /-! ### Order dual -/ instance [h : has_rat_cast α] : has_rat_cast αᵒᵈ := h instance [h : division_semiring α] : division_semiring αᵒᵈ := h instance [h : division_ring α] : division_ring αᵒᵈ := h instance [h : semifield α] : semifield αᵒᵈ := h instance [h : field α] : field αᵒᵈ := h @[simp] lemma to_dual_rat_cast [has_rat_cast α] (n : ℚ) : to_dual (n : α) = n := rfl @[simp] lemma of_dual_rat_cast [has_rat_cast α] (n : ℚ) : (of_dual n : α) = n := rfl /-! ### Lexicographic order -/ instance [h : has_rat_cast α] : has_rat_cast (lex α) := h instance [h : division_semiring α] : division_semiring (lex α) := h instance [h : division_ring α] : division_ring (lex α) := h instance [h : semifield α] : semifield (lex α) := h instance [h : field α] : field (lex α) := h @[simp] lemma to_lex_rat_cast [has_rat_cast α] (n : ℚ) : to_lex (n : α) = n := rfl @[simp] lemma of_lex_rat_cast [has_rat_cast α] (n : ℚ) : (of_lex n : α) = n := rfl
0fc2832483ae0143b08e6b61213a980e7b07327f
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/analysis/topology/topological_space.lean
0749d003f135816ca0f68849095d0b61ddcff446
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
65,568
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of topological spaces. Parts of the formalization is based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.set.countable tactic open set filter lattice classical local attribute [instance] prop_decidable universes u v w structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[extensionality] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set α) : Prop := is_open (-s) @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by unfold is_closed; rw compl_empty; exact is_open_univ @[simp] lemma is_closed_univ : is_closed (univ : set α) := by unfold is_closed; rw compl_univ; exact is_open_empty lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂ lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i @[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂ lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_imp [topological_space α] {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := interior_eq_of_open is_open_empty @[simp] lemma interior_univ : interior (univ : set α) = univ := interior_eq_of_open is_open_univ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := interior_eq_of_open is_open_interior @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩ lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := closure_eq_of_is_closed is_closed_empty lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := begin split; intro h, { rw set.eq_empty_iff_forall_not_mem, intros x H, simpa only [h] using subset_closure H }, { exact (eq.symm h) ▸ closure_empty }, end @[simp] lemma closure_univ : closure (univ : set α) = univ := closure_eq_of_is_closed is_closed_univ @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := closure_eq_of_is_closed is_closed_closure @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure) (union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _)) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) := begin unfold interior closure is_closed, rw [compl_sUnion, compl_image_set_of], simp only [compl_subset_compl] end @[simp] lemma interior_compl {s : set α} : interior (- s) = - closure s := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure (- s) = - interior s := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ := ⟨λ h o oo ao os, have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩ lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U ≠ ∅ → U ∩ s ≠ ∅ := begin split ; intro h, { intros U U_op U_ne, cases exists_mem_of_ne_empty U_ne with x x_in, exact mem_closure_iff.1 (by simp only [h]) U U_op x_in }, { apply eq_univ_of_forall, intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op (ne_empty_of_mem x_in) }, end /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure (- s) := by rw [closure_compl, frontier, diff_eq] @[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s := by simp only [frontier_eq_closure_inter_closure, lattice.neg_neg, inter_comm] /-- neighbourhood filter -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s) lemma tendsto_nhds {m : β → α} {f : filter β} (h : ∀s, a ∈ s → is_open s → m ⁻¹' s ∈ f.sets) : tendsto m f (nhds a) := show map m f ≤ (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s), from le_infi $ assume s, le_infi $ assume ⟨ha, hs⟩, le_principal_iff.mpr $ h s ha hs lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) := tendsto_nhds $ assume s ha hs, univ_mem_sets' $ assume _, ha lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} := calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, le_principal_iff.2 (inter_subset_left _ _), le_principal_iff.2 (inter_subset_right _ _)⟩) ⟨univ, mem_univ _, is_open_univ⟩ ... = {s | ∃t⊆s, is_open t ∧ a ∈ t} : le_antisymm (supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩) (assume t ⟨i, hi₁, hi₂, hi₃⟩, mem_Union.2 ⟨i, mem_Union.2 ⟨⟨hi₃, hi₂⟩, hi₁⟩⟩) lemma map_nhds {a : α} {f : α → β} : map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) := calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) : map_binfi_eq (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, le_principal_iff.2 (inter_subset_left _ _), le_principal_iff.2 (inter_subset_right _ _)⟩) ⟨univ, mem_univ _, is_open_univ⟩ ... = _ : by simp only [map_principal] lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t := by simp only [nhds_sets, mem_set_of_eq, exists_prop] lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ (nhds a).sets := mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma pure_le_nhds : pure ≤ (nhds : α → filter α) := assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $ singleton_subset_iff.2 h₁ lemma tendsto_pure_nhds [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (nhds (f a)) := begin rw [tendsto, filter.map_pure], exact pure_le_nhds (f a) end @[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ := assume : nhds a = ⊥, have pure a = (⊥ : filter α), from lattice.bot_unique $ this ▸ pure_le_nhds a, pure_neq_bot this lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} := set.ext $ λ x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ (nhds a).sets := by simp only [interior_eq_nhds, le_principal_iff]; refl lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ (nhds a).sets := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} := calc closure s = - interior (- s) : closure_eq_compl_interior_compl ... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl ... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr (inf_eq_bot_iff_le_compl (show principal s ⊔ principal (-s) = ⊤, by simp only [sup_principal, union_compl_self, principal_univ]) (by simp only [inf_principal, inter_compl_self, principal_empty])).symm theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ (nhds a).sets, t ∩ s ≠ ∅ := mem_closure_iff.trans ⟨λ H t ht, subset_ne_empty (inter_subset_inter_left _ interior_subset) (H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)), λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩ lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s := calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed] ... ↔ closure s ⊆ s : ⟨assume h, by rw h, assume h, subset.antisymm h subset_closure⟩ ... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ (nhds a).sets, from mem_nhds_sets h hs, have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by rwa le_principal_iff, have nhds a ⊓ principal (s ∩ t) ≠ ⊥, from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by rw inf_principal ... = nhds a ⊓ principal t : by rw [←inf_assoc, this] ... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption, by rw [closure_eq_nhds]; assumption lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) := calc closure s \ closure t = (- closure t) ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b.sets) : a ∈ s := have b.map f ≤ nhds a ⊓ principal s, from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)), is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this lemma mem_closure_of_tendsto {f : β → α} {x : filter β} {a : α} {s : set α} (hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s := is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $ le_inf (le_trans (map_mono $ inf_le_left) hf) $ le_trans (map_mono $ inf_le_right_of_le $ by simp only [comap_principal, le_principal_iff]; exact subset.refl _) (@map_comap_le _ _ _ f) /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t∈(nhds x).sets, finite {i | f i ∩ t ≠ ∅ } lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite_subset h $ subset_univ _⟩ lemma locally_finite_subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, finite_subset ht₂ $ assume i hi, neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ -f i, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have ∀i, - f i ∈ (nhds a).sets, by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets, apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin, exact assume i h, this i end ... ≤ principal (- ⋃i, f i) : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, not_eq_empty_iff_exists, exists_imp_distrib, (≠)], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥ lemma compact_inter {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) := assume f hnf hstf, let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t, by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a, have a ∈ t, from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))) (le_refl _), ⟨a, ⟨hsa, this⟩, ha⟩ lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) := compact_inter hs (is_closed_compl_iff.mpr ht) lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := by convert ← compact_inter hs ht; exact inter_eq_self_of_subset_right h lemma compact_adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f.sets := classical.by_cases mem_sets_of_neq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have nhds a ⊓ principal (-t) ≠ ⊥, from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.mpr this, have false, from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (inter_compl_self _), by contradiction lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ nhds a ≠ ⊥, by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩ lemma compact_elim_finite_subcover {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' := classical.by_contradiction $ assume h, have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c', from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩, let f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩, principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩) (assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h hc'₁ hc'₂), have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $ show principal (s \ ⋃₀∅) ≤ principal s, from le_principal_iff.2 (diff_subset _ _), let ⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha in have f ≤ principal (-t), from infi_le_of_le ⟨{t}, by rwa singleton_subset_iff, finite_insert _ finite_empty⟩ $ principal_mono.mpr $ show s - ⋃₀{t} ⊆ - t, begin rw sUnion_singleton; exact assume x ⟨_, hnt⟩, hnt end, have is_closed (- t), from is_open_compl_iff.mp $ by rw lattice.neg_neg; exact hc₁ t ht₁, have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›), this ‹a ∈ t› lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := if h : b = ∅ then ⟨∅, empty_subset _, finite_empty, h ▸ hc₂⟩ else let ⟨i, hi⟩ := exists_mem_of_ne_empty h in have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj, have hc'₂ : s ⊆ ⋃₀ (c '' b), by rwa set.sUnion_image, let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx, let ⟨f', hf⟩ := axiom_of_choice this, f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i), from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid, by simpa only [f, dif_pos hid, (hf ⟨_, hid⟩).2] using hxi⟩, ⟨f '' d, assume i ⟨j, hj, h⟩, h ▸ by simpa only [f, dif_pos hj] using (hf ⟨_, hj⟩).1, finite_image f hd₂, subset.trans hd₃ $ by simpa only [subset_def, mem_sUnion, exists_imp_distrib, mem_Union, exists_prop, and_imp]⟩ lemma compact_of_finite_subcover {s : set α} (h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥), have hf : ∀x∈s, nhds x ⊓ f = ⊥, by simpa only [not_exists, not_not, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ (nhds x ⊓ f).sets, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ (nhds x ⊓ principal t₂).sets, from (nhds x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have nhds x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa only [not_exists, not_forall], let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c (assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa only [subset_def, sUnion_image, mem_Union]) in let ⟨b, hb⟩ := axiom_of_choice $ show ∀s:c', ∃t, t ∈ f.sets ∧ - closure t = s, from assume ⟨x, hx⟩, hcc' hx in have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets, from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left, have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f.sets, from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩, let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, from hsc' hxs) in have -closure (b ⟨t, htc'⟩) = t, from (hb _).right, have x ∈ - t, from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by rw mem_bInter_iff at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h ... ⊆ closure (b ⟨t, htc'⟩) : subset_closure ... ⊆ - - closure (b ⟨t, htc'⟩) : by rw lattice.neg_neg; exact subset.refl _), show false, from this hxt, hfn $ by rwa [empty_in_sets_eq_bot] at this lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') := ⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩ lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume c hc₁ hc₂, let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, from mem_sUnion.1 $ singleton_subset_iff.1 hc₂) in ⟨{i}, singleton_subset_iff.2 hic, finite_singleton _, by rwa [sUnion_singleton, singleton_subset_iff]⟩ lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) : (∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) := assume hf, compact_of_finite_subcover $ assume c c_open c_cover, have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃₀ c : c_cover), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in let c' := ⋃i, finite_subcovers i in have c' ⊆ c, from Union_subset (λi, (h i).fst), have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1), have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2 ... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _), ⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩ lemma compact_of_finite {s : set α} (hs : finite s) : compact s := let s' : set α := ⋃i ∈ s, {i} in have e : s' = s, from ext $ λi, by simp only [mem_bUnion_iff, mem_singleton_iff, exists_eq_right'], have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton), e ▸ this end compact /- separation axioms -/ section separation /-- A T₁ space, also known as a Fréchet space, is a topological space where for every pair `x ≠ y`, there is an open set containing `x` and not `y`. Equivalently, every singleton set is closed. -/ class t1_space (α : Type u) [topological_space α] := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [topological_space α] [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h instance t2_space.t1_space [topological_space α] [t2_space α] : t1_space α := ⟨assume x, have ∀y, y ≠ x ↔ ∃ (i : set α), (x ∉ i ∧ is_open i) ∧ y ∈ i, from assume y, ⟨assume h', let ⟨u, v, hu, hv, hy, hx, h⟩ := t2_separation h' in have x ∉ u, from assume : x ∈ u, have x ∈ u ∩ v, from ⟨this, hx⟩, by rwa [h] at this, ⟨u, ⟨this, hu⟩, hy⟩, assume ⟨s, ⟨hx, hs⟩, hy⟩ h, hx $ h ▸ hy⟩, have (-{x} : set α) = (⋃s∈{s : set α | x ∉ s ∧ is_open s}, s), by apply set.ext; simpa only [mem_compl_eq, mem_singleton_iff, mem_bUnion_iff], show is_open (- {x}), by rw [this]; exact (is_open_Union $ assume s, is_open_Union $ assume ⟨_, hs⟩, hs)⟩ lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ (nhds x ⊓ nhds y).sets, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by rw [h, inf_idem]; exact nhds_neq_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by rw [inf_of_le_left h]; exact nhds_neq_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t2_space α := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ (nhds a).sets) : ∃t∈(nhds a).sets, t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_neq_bot $ by rwa [lattice.neg_neg], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ end regularity /- generating sets -/ end topological_space namespace topological_space variables {α : Type u} /-- The least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ g, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) := le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s, begin intros s hs, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end, this s hs as) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f.sets) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ (n a).sets, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ (n a).sets → ∃t∈(n a).sets, t ⊆ s ∧ ∀a'∈t, s ∈ (n a').sets) : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ (n b).sets} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ (n b).sets} ∈ (nhds a).sets, { refine mem_nhds_sets (assume b (hb : s ∈ (n b).sets), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} instance : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ _, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h instance {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice class discrete_topology (α : Type*) [t : topological_space α] := (eq_top : t = ⊤) @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_top α).symm ▸ trivial lemma nhds_top (α : Type*) : (@nhds α ⊤) = pure := begin ext a s, rw [mem_nhds_sets_iff, mem_pure_iff], split, { exact assume ⟨t, ht, _, hta⟩, ht hta }, { exact assume h, ⟨{a}, set.singleton_subset_iff.2 h, trivial, set.mem_singleton a⟩ } end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_top α).symm ▸ nhds_top α instance t2_space_discrete [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) : t₁ ≤ t₂ := assume s, show @is_open α t₁ s → @is_open α t₂ s, begin simp only [is_open_iff_nhds, le_principal_iff]; exact assume hs a ha, h _ $ hs _ ha end lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ s = f ⁻¹' s', is_open_univ := ⟨univ, t.is_open_univ, preimage_univ.symm⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right.symm)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ s = f ⁻¹' t) := iff.refl _ lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨-t, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq.symm, lattice.neg_neg]⟩, assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.refl _ variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma induced_le_iff_le_coinduced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tβ.induced f ≤ tα ↔ tβ ≤ tα.coinduced f := iff.intro (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) (assume h s ⟨t, ht, hst⟩, hst.symm ▸ h _ ht) lemma gc_induced_coinduced (f : α → β) : galois_connection (topological_space.induced f) (topological_space.coinduced f) := assume f g, induced_le_iff_le_coinduced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_induced_coinduced g).monotone_l h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_induced_coinduced f).monotone_u h @[simp] lemma induced_bot : (⊥ : topological_space α).induced g = ⊥ := (gc_induced_coinduced g).l_bot @[simp] lemma induced_sup : (t₁ ⊔ t₂).induced g = t₁.induced g ⊔ t₂.induced g := (gc_induced_coinduced g).l_sup @[simp] lemma induced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).induced g = (⨆i, (t i).induced g) := (gc_induced_coinduced g).l_supr @[simp] lemma coinduced_top : (⊤ : topological_space α).coinduced f = ⊤ := (gc_induced_coinduced f).u_top @[simp] lemma coinduced_inf : (t₁ ⊓ t₂).coinduced f = t₁.coinduced f ⊓ t₂.coinduced f := (gc_induced_coinduced f).u_inf @[simp] lemma coinduced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).coinduced f = (⨅i, (t i).coinduced f) := (gc_induced_coinduced f).u_infi lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h.symm ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tβ : topological_space β] [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁.symm ▸ h₂.symm ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ instance : topological_space empty := ⊤ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space unit := ⊤ instance : discrete_topology unit := ⟨rfl⟩ instance : topological_space bool := ⊤ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊤ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊤ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced subtype.val t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊔ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊓ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨅a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨆a, induced (λf, f a) (t₂ a) instance [topological_space α] : topological_space (list α) := topological_space.mk_of_nhds (traverse nhds) lemma nhds_list [topological_space α] (as : list α) : nhds as = traverse nhds as := begin refine nhds_mk_of_nhds _ _ _ _, { assume l, induction l, case list.nil { exact le_refl _ }, case list.cons : a l ih { suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> nhds a <*> traverse nhds l, { simpa only [-filter.pure_def] with functor_norm using this }, exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } }, { assume l s hs, rcases (mem_traverse_sets_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs, have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s, { induction hu generalizing s, case list.forall₂.nil : hs this { existsi [], simpa only [list.forall₂_nil_left_iff, exists_eq_left] }, case list.forall₂.cons : a s as ss ht h ih t hts { rcases mem_nhds_sets_iff.1 ht with ⟨u, hut, hu⟩, rcases ih (subset.refl _) with ⟨v, hv, hvss⟩, exact ⟨u::v, list.forall₂.cons hu hv, subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } }, rcases this with ⟨v, hv, hvs⟩, refine ⟨sequence v, mem_traverse_sets _ _ _, hvs, _⟩, { exact hv.imp (assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) }, { assume u hu, have hu := (list.mem_traverse _ _).1 hu, have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v, { refine list.forall₂.flip _, replace hv := hv.flip, simp only [list.forall₂_and_left, flip] at ⊢ hv, exact ⟨hv.1, hu.flip⟩ }, refine mem_sets_of_superset _ hvs, exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } } end lemma nhds_nil [topological_space α] : nhds ([] : list α) = pure [] := by rw [nhds_list, list.traverse_nil _]; apply_instance lemma nhds_cons [topological_space α] (a : α) (l : list α) : nhds (a :: l) = list.cons <$> nhds a <*> nhds l := by rw [nhds_list, list.traverse_cons _, ← nhds_list]; apply_instance lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage_eq, y_x, x_in_U], have V_op : is_open V := U_op, have : V ∩ s ≠ ∅ := mem_closure_iff.1 (H y) V V_op y_in_V, rcases exists_mem_of_ne_empty this with ⟨w, w_in_V, w_in_range⟩, exact ne_empty_of_mem ⟨w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : generate_from g ≤ t := generate_from_le_iff_subset_is_open.2 h protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f.sets, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : @galois_connection _ (order_dual (filter α)) _ _ (λt, @nhds α t a) (topological_space.nhds_adjoint a) := assume t (f : filter α), show f ≤ @nhds α t a ↔ _, from iff.intro (assume h s hs has, h $ @mem_nhds_sets α t a s hs has) (assume h, le_infi $ assume u, le_infi $ assume ⟨hau, hu⟩, le_principal_iff.2 $ h _ hu hau) lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₂ a ≤ @nhds α t₁ a := (gc_nhds a).monotone_l h lemma nhds_supr {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (supr t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).l_supr lemma nhds_Sup {s : set (topological_space α)} {a : α} : @nhds α (Sup s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).l_Sup lemma nhds_sup {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊔ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).l_sup lemma nhds_bot {a : α} : @nhds α ⊥ a = ⊤ := (gc_nhds a).l_bot private lemma separated_by_f [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : induced f tβ ≤ tα) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst le_sup_left h₁) (λ h₂, separated_by_f prod.snd le_sup_right h₂)⟩ instance Pi.t2_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (le_supr _ i) hi⟩ instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨top_unique $ assume s hs, ⟨subtype.val '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.val_injective).symm⟩⟩ end constructions namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, by simpa only [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact nonempty_iff_univ_ne_empty.1 ⟨a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (generate_from_le $ assume s hs, by_cases (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s ≠ ∅, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa [sInter_singleton]⟩, sInter_singleton s⟩)) (generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu)) (generate_from_le h_open)⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin rw [hb.2.2, nhds_generate_from, infi_sets_eq'], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm]; refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t)) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in ⟨b', countable_image _ $ countable_subset (by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp, is_topological_basis_of_subbasis hb₂⟩ instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl, have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs, have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true], infi_neq_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets, (≥)], simp only [subset_inter_iff] at hs, split; apply inter_subset_inter_left; simp only [hs] end⟩) (assume ⟨s, has, hs⟩, have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅, from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩, mt principal_eq_bot_iff.1 this) ⟩⟩ variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, countable_image _ cT, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space section limit variables {α : Type u} [inhabited α] [topological_space α] open classical /-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/ noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h variables [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a := lim_eq nhds_neq_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (nhds a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end limit
52a99eb0a0336282147a3d55d1b7e61fa6f6f1dc
54f4ad05b219d444b709f56c2f619dd87d14ec29
/my_project/src/love01_definitions_and_statements_exercise_sheet.lean
e8d9d216f0102ea1da981bb12d316047594e93f1
[]
no_license
yizhou7/learning-lean
8efcf838c7276e235a81bd291f467fa43ce56e0a
91fb366c624df6e56e19555b2e482ce767cd8224
refs/heads/master
1,675,649,087,737
1,609,022,281,000
1,609,022,281,000
272,072,779
0
0
null
null
null
null
UTF-8
Lean
false
false
4,353
lean
import .love01_definitions_and_statements_demo /-! # LoVe Exercise 1: Definitions and Statements Replace the placeholders (e.g., `:= sorry`) with your solutions. -/ set_option pp.beta true namespace LoVe /-! ## Question 1: Truncating Subtraction 1.1. Define the function `sub` that implements truncating subtraction on natural numbers by recursion. "Truncating" means that results that mathematically would be negative are represented by 0. For example: `sub 7 2 = 5` `sub 2 7 = 0` -/ def sub : ℕ → ℕ → ℕ | nat.zero n := nat.zero | m nat.zero := m | (nat.succ m) (nat.succ n) := sub m n /-! 1.2. Check that your function works as expected. -/ #eval sub 0 0 -- expected: 0 #eval sub 0 1 -- expected: 0 #eval sub 0 7 -- expected: 0 #eval sub 1 0 -- expected: 1 #eval sub 1 1 -- expected: 0 #eval sub 3 0 -- expected: 3 #eval sub 2 7 -- expected: 0 #eval sub 3 1 -- expected: 2 #eval sub 3 3 -- expected: 0 #eval sub 3 7 -- expected: 0 #eval sub 7 2 -- expected: 5 /-! ## Question 2: Arithmetic Expressions Consider the type `aexp` from the lecture and the function `eval` that computes the value of an expression. You will find the definitions in the file `love01_definitions_and_statements_demo.lean`. One way to find them quickly is to 1. hold the Control (on Linux and Windows) or Command (on macOS) key pressed; 2. move the cursor to the identifier `aexp` or `eval`; 3. click the identifier. -/ #check aexp #check eval /-! 2.1. Test that `eval` behaves as expected. Make sure to exercise each constructor at least once. You can use the following environment in your tests. What happens if you divide by zero? Make sure to use `#eval`. For technical reasons, `#reduce` does not work well here. Note that `#eval` (Lean's evaluation command) and `eval` (our evaluation function on `aexp`) are unrelated. -/ def some_env : string → ℤ | "x" := 3 | "y" := 17 | _ := 0 #eval eval some_env (aexp.var "x") -- expected: 3 #eval eval some_env ((aexp.div (aexp.var "x") (aexp.num 0)) /-! 2.2. The following function simplifies arithmetic expressions involving addition. It simplifies `0 + e` and `e + 0` to `e`. Complete the definition so that it also simplifies expressions involving the other three binary operators. -/ def simplify : aexp → aexp | (aexp.add (aexp.num 0) e₂) := simplify e₂ | (aexp.add e₁ (aexp.num 0)) := simplify e₁ -- insert the missing cases here | (aexp.mul (aexp.num 1) e₂) := simplify e₂ | (aexp.mul e₁ (aexp.num 1)) := simplify e₁ -- catch-all cases below | (aexp.num i) := aexp.num i | (aexp.var x) := aexp.var x | (aexp.add e₁ e₂) := aexp.add (simplify e₁) (simplify e₂) | (aexp.sub e₁ e₂) := aexp.sub (simplify e₁) (simplify e₂) | (aexp.mul e₁ e₂) := aexp.mul (simplify e₁) (simplify e₂) | (aexp.div e₁ e₂) := aexp.div (simplify e₁) (simplify e₂) /-! 2.3. State (without proving it) the correctness lemma for `simplify`, namely that the simplified expression should have the same semantics, with respect to `eval`, as the original expression. -/ lemma simplify_correct (env : string → ℤ) (e : aexp) : -- enter your lemma statement here (eval env (simplify(e))) == (eval env e) := sorry /-! ## Question 3: λ-Terms 3.1. Complete the following definitions, by replacing the `sorry` markers by terms of the expected type. Hint: A procedure for doing so systematically is described in Section 1.1.4 of the Hitchhiker's Guide. As explained there, you can use `_` as a placeholder while constructing a term. By hovering over `_`, you will see the current logical context. -/ def I : α → α := λa, a def K : α → β → α := λa b, a def C : (α → β → γ) → β → α → γ := λf b a, f a b def proj_1st : α → α → α := λ a b, a /-! Please give a different answer than for `proj_1st`. -/ def proj_2nd : α → α → α := λ a b, b def some_nonsense : (α → β → γ) → α → (α → γ) → β → γ := λ f a g b, f a b /-! 3.2. Show the typing derivation for your definition of `C` above, on paper or using ASCII or Unicode art. You might find the characters `–` (to draw horizontal bars) and `⊢` useful. -/ -- write your solution in a comment here or on paper end LoVe
9674a54ae9fb416a0894521f5e768c02d0cf48c6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/special_functions/complex/arg.lean
c08f7fb3cc240fc96ea92d8e8fa79f3d9366be5f
[ "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
25,066
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import algebra.order.to_interval_mod import analysis.special_functions.trigonometric.angle import analysis.special_functions.trigonometric.inverse /-! # The argument of a complex number. We define `arg : ℂ → ℝ`, returing a real number in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, while `arg 0` defaults to `0` -/ noncomputable theory namespace complex open_locale complex_conjugate real topological_space open filter set /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := begin have habs : 0 < abs x := abs_pos.2 hx, have him : |im x / abs x| ≤ 1, { rw [_root_.abs_div, abs_abs], exact div_le_one_of_le x.abs_im_le_abs x.abs_nonneg }, rw abs_le at him, rw arg, split_ifs with h₁ h₂ h₂, { rw [real.cos_arcsin]; field_simp [real.sqrt_sq, habs.le, *] }, { rw [real.cos_add_pi, real.cos_arcsin], { field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { simpa [neg_div] using him.2 }, { simpa [neg_div, neg_le] using him.1 } }, { rw [real.cos_sub_pi, real.cos_arcsin], { field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { simpa [neg_div] using him.2 }, { simpa [neg_div, neg_le] using him.1 } } end @[simp] lemma abs_mul_exp_arg_mul_I (x : ℂ) : ↑(abs x) * exp (arg x * I) = x := begin rcases eq_or_ne x 0 with (rfl|hx), { simp }, { have : abs x ≠ 0 := abs_ne_zero.2 hx, ext; field_simp [sin_arg, cos_arg hx, this, mul_comm (abs x)] } end @[simp] lemma abs_mul_cos_add_sin_mul_I (x : ℂ) : (abs x * (cos (arg x) + sin (arg x) * I) : ℂ) = x := by rw [← exp_mul_I, abs_mul_exp_arg_mul_I] lemma abs_eq_one_iff (z : ℂ) : abs z = 1 ↔ ∃ θ : ℝ, exp (θ * I) = z := begin refine ⟨λ hz, ⟨arg z, _⟩, _⟩, { calc exp (arg z * I) = abs z * exp (arg z * I) : by rw [hz, of_real_one, one_mul] ... = z : abs_mul_exp_arg_mul_I z }, { rintro ⟨θ, rfl⟩, exact complex.abs_exp_of_real_mul_I θ }, end @[simp] lemma range_exp_mul_I : range (λ x : ℝ, exp (x * I)) = metric.sphere 0 1 := by { ext x, simp only [mem_sphere_zero_iff_norm, norm_eq_abs, abs_eq_one_iff, mem_range] } lemma arg_mul_cos_add_sin_mul_I {r : ℝ} (hr : 0 < r) {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (r * (cos θ + sin θ * I)) = θ := begin have hπ := real.pi_pos, simp only [arg, abs_mul, abs_cos_add_sin_mul_I, abs_of_nonneg hr.le, mul_one], simp only [of_real_mul_re, of_real_mul_im, neg_im, ← of_real_cos, ← of_real_sin, ← mk_eq_add_mul_I, neg_div, mul_div_cancel_left _ hr.ne', mul_nonneg_iff_right_nonneg_of_pos hr], by_cases h₁ : θ ∈ Icc (-(π / 2)) (π / 2), { rw if_pos, exacts [real.arcsin_sin' h₁, real.cos_nonneg_of_mem_Icc h₁] }, { rw [mem_Icc, not_and_distrib, not_le, not_le] at h₁, cases h₁, { replace hθ := hθ.1, have hcos : real.cos θ < 0, { rw [← neg_pos, ← real.cos_add_pi], refine real.cos_pos_of_mem_Ioo ⟨_, _⟩; linarith }, have hsin : real.sin θ < 0 := real.sin_neg_of_neg_of_neg_pi_lt (by linarith) hθ, rw [if_neg, if_neg, ← real.sin_add_pi, real.arcsin_sin, add_sub_cancel]; [linarith, linarith, exact hsin.not_le, exact hcos.not_le] }, { replace hθ := hθ.2, have hcos : real.cos θ < 0 := real.cos_neg_of_pi_div_two_lt_of_lt h₁ (by linarith), have hsin : 0 ≤ real.sin θ := real.sin_nonneg_of_mem_Icc ⟨by linarith, hθ⟩, rw [if_neg, if_pos, ← real.sin_sub_pi, real.arcsin_sin, sub_add_cancel]; [linarith, linarith, exact hsin, exact hcos.not_le] } } end lemma arg_cos_add_sin_mul_I {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (cos θ + sin θ * I) = θ := by rw [← one_mul (_ + _), ← of_real_one, arg_mul_cos_add_sin_mul_I zero_lt_one hθ] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := by rw [← abs_mul_exp_arg_mul_I x, ← abs_mul_exp_arg_mul_I y, h₁, h₂] lemma ext_abs_arg_iff {x y : ℂ} : x = y ↔ abs x = abs y ∧ arg x = arg y := ⟨λ h, h ▸ ⟨rfl, rfl⟩, and_imp.2 ext_abs_arg⟩ lemma arg_mem_Ioc (z : ℂ) : arg z ∈ Ioc (-π) π := begin have hπ : 0 < π := real.pi_pos, rcases eq_or_ne z 0 with (rfl|hz), simp [hπ, hπ.le], rcases exists_unique_add_zsmul_mem_Ioc real.two_pi_pos (arg z) (-π) with ⟨N, hN, -⟩, rw [two_mul, neg_add_cancel_left, ← two_mul, zsmul_eq_mul] at hN, rw [← abs_mul_cos_add_sin_mul_I z, ← cos_add_int_mul_two_pi _ N, ← sin_add_int_mul_two_pi _ N], simp only [← of_real_one, ← of_real_bit0, ← of_real_mul, ← of_real_add, ← of_real_int_cast], rwa [arg_mul_cos_add_sin_mul_I (abs_pos.2 hz) hN] end @[simp] lemma range_arg : range arg = Ioc (-π) π := (range_subset_iff.2 arg_mem_Ioc).antisymm (λ x hx, ⟨_, arg_cos_add_sin_mul_I hx⟩) lemma arg_le_pi (x : ℂ) : arg x ≤ π := (arg_mem_Ioc x).2 lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := (arg_mem_Ioc x).1 @[simp] lemma arg_nonneg_iff {z : ℂ} : 0 ≤ arg z ↔ 0 ≤ z.im := begin rcases eq_or_ne z 0 with (rfl|h₀), { simp }, calc 0 ≤ arg z ↔ 0 ≤ real.sin (arg z) : ⟨λ h, real.sin_nonneg_of_mem_Icc ⟨h, arg_le_pi z⟩, by { contrapose!, intro h, exact real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_arg _) }⟩ ... ↔ _ : by rw [sin_arg, le_div_iff (abs_pos.2 h₀), zero_mul] end @[simp] lemma arg_neg_iff {z : ℂ} : arg z < 0 ↔ z.im < 0 := lt_iff_lt_of_le_iff_le arg_nonneg_iff lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := begin rcases eq_or_ne x 0 with (rfl|hx), { rw mul_zero }, conv_lhs { rw [← abs_mul_cos_add_sin_mul_I x, ← mul_assoc, ← of_real_mul, arg_mul_cos_add_sin_mul_I (mul_pos hr (abs_pos.2 hx)) x.arg_mem_Ioc] } end lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := begin simp only [ext_abs_arg_iff, abs_mul, abs_div, abs_of_real, abs_abs, div_mul_cancel _ (abs_ne_zero.2 hx), eq_self_iff_true, true_and], rw [← of_real_div, arg_real_mul], exact div_pos (abs_pos.2 hy) (abs_pos.2 hx) end @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] @[simp] lemma tan_arg (x : ℂ) : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right _ (abs_ne_zero.2 h)] end lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_eq_zero_iff {z : ℂ} : arg z = 0 ↔ 0 ≤ z.re ∧ z.im = 0 := begin refine ⟨λ h, _, _⟩, { rw [←abs_mul_cos_add_sin_mul_I z, h], simp [abs_nonneg] }, { cases z with x y, rintro ⟨h, rfl : y = 0⟩, exact arg_of_real_of_nonneg h } end lemma arg_eq_pi_iff {z : ℂ} : arg z = π ↔ z.re < 0 ∧ z.im = 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero.symm] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨h : x < 0, rfl : y = 0⟩, rw [← arg_neg_one, ← arg_real_mul (-1) (neg_pos.2 h)], simp [← of_real_def] } end lemma arg_lt_pi_iff {z : ℂ} : arg z < π ↔ 0 ≤ z.re ∨ z.im ≠ 0 := by rw [(arg_le_pi z).lt_iff_ne, not_iff_comm, not_or_distrib, not_le, not_not, arg_eq_pi_iff] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := arg_eq_pi_iff.2 ⟨hx, rfl⟩ lemma arg_eq_pi_div_two_iff {z : ℂ} : arg z = π / 2 ↔ z.re = 0 ∧ 0 < z.im := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_div_two_pos.ne] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : 0 < y⟩, rw [← arg_I, ← arg_real_mul I hy, of_real_mul', I_re, I_im, mul_zero, mul_one] } end lemma arg_eq_neg_pi_div_two_iff {z : ℂ} : arg z = - (π / 2) ↔ z.re = 0 ∧ z.im < 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : y < 0⟩, rw [← arg_neg_I, ← arg_real_mul (-I) (neg_pos.2 hy), mk_eq_add_mul_I], simp } end lemma arg_of_re_nonneg {x : ℂ} (hx : 0 ≤ x.re) : arg x = real.arcsin (x.im / x.abs) := if_pos hx lemma arg_of_re_neg_of_im_nonneg {x : ℂ} (hx_re : x.re < 0) (hx_im : 0 ≤ x.im) : arg x = real.arcsin ((-x).im / x.abs) + π := by simp only [arg, hx_re.not_le, hx_im, if_true, if_false] lemma arg_of_re_neg_of_im_neg {x : ℂ} (hx_re : x.re < 0) (hx_im : x.im < 0) : arg x = real.arcsin ((-x).im / x.abs) - π := by simp only [arg, hx_re.not_le, hx_im.not_le, if_false] lemma arg_of_im_nonneg_of_ne_zero {z : ℂ} (h₁ : 0 ≤ z.im) (h₂ : z ≠ 0) : arg z = real.arccos (z.re / abs z) := by rw [← cos_arg h₂, real.arccos_cos (arg_nonneg_iff.2 h₁) (arg_le_pi _)] lemma arg_of_im_pos {z : ℂ} (hz : 0 < z.im) : arg z = real.arccos (z.re / abs z) := arg_of_im_nonneg_of_ne_zero hz.le (λ h, hz.ne' $ h.symm ▸ rfl) lemma arg_of_im_neg {z : ℂ} (hz : z.im < 0) : arg z = -real.arccos (z.re / abs z) := begin have h₀ : z ≠ 0, from mt (congr_arg im) hz.ne, rw [← cos_arg h₀, ← real.cos_neg, real.arccos_cos, neg_neg], exacts [neg_nonneg.2 (arg_neg_iff.2 hz).le, neg_le.2 (neg_pi_lt_arg z).le] end lemma arg_conj (x : ℂ) : arg (conj x) = if arg x = π then π else -arg x := begin simp_rw [arg_eq_pi_iff, arg, neg_im, conj_im, conj_re, abs_conj, neg_div, neg_neg, real.arcsin_neg, apply_ite has_neg.neg, neg_add, neg_sub, neg_neg, ←sub_eq_add_neg, sub_neg_eq_add, add_comm π], rcases lt_trichotomy x.re 0 with (hr|hr|hr); rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hr, hr.not_le, hi.le, hi.ne, not_le.2 hi] }, { simp [hr, hr.not_le, hi] }, { simp [hr, hr.not_le, hi.ne.symm, hi.le, not_le.2 hi] }, { simp [hr] }, { simp [hr] }, { simp [hr] }, { simp [hr, hr.le, hi.ne] }, { simp [hr, hr.le, hr.le.not_lt] }, { simp [hr, hr.le, hr.le.not_lt] }, end lemma arg_inv (x : ℂ) : arg x⁻¹ = if arg x = π then π else -arg x := begin rw [←arg_conj, inv_def, mul_comm], by_cases hx : x = 0, { simp [hx] }, { exact arg_real_mul (conj x) (by simp [hx]) } end lemma arg_le_pi_div_two_iff {z : ℂ} : arg z ≤ π / 2 ↔ 0 ≤ re z ∨ im z < 0 := begin cases le_or_lt 0 (re z) with hre hre, { simp only [hre, arg_of_re_nonneg hre, real.arcsin_le_pi_div_two, true_or] }, simp only [hre.not_le, false_or], cases le_or_lt 0 (im z) with him him, { simp only [him.not_lt], rw [iff_false, not_le, arg_of_re_neg_of_im_nonneg hre him, ← sub_lt_iff_lt_add, half_sub, real.neg_pi_div_two_lt_arcsin, neg_im, neg_div, neg_lt_neg_iff, div_lt_one, ← _root_.abs_of_nonneg him, abs_im_lt_abs], exacts [hre.ne, abs_pos.2 $ ne_of_apply_ne re hre.ne] }, { simp only [him], rw [iff_true, arg_of_re_neg_of_im_neg hre him], exact (sub_le_self _ real.pi_pos.le).trans (real.arcsin_le_pi_div_two _) } end lemma neg_pi_div_two_le_arg_iff {z : ℂ} : -(π / 2) ≤ arg z ↔ 0 ≤ re z ∨ 0 ≤ im z := begin cases le_or_lt 0 (re z) with hre hre, { simp only [hre, arg_of_re_nonneg hre, real.neg_pi_div_two_le_arcsin, true_or] }, simp only [hre.not_le, false_or], cases le_or_lt 0 (im z) with him him, { simp only [him], rw [iff_true, arg_of_re_neg_of_im_nonneg hre him], exact (real.neg_pi_div_two_le_arcsin _).trans (le_add_of_nonneg_right real.pi_pos.le) }, { simp only [him.not_le], rw [iff_false, not_le, arg_of_re_neg_of_im_neg hre him, sub_lt_iff_lt_add', ← sub_eq_add_neg, sub_half, real.arcsin_lt_pi_div_two, div_lt_one, neg_im, ← abs_of_neg him, abs_im_lt_abs], exacts [hre.ne, abs_pos.2 $ ne_of_apply_ne re hre.ne] } end @[simp] lemma abs_arg_le_pi_div_two_iff {z : ℂ} : |arg z| ≤ π / 2 ↔ 0 ≤ re z := by rw [abs_le, arg_le_pi_div_two_iff, neg_pi_div_two_le_arg_iff, ← or_and_distrib_left, ← not_le, and_not_self, or_false] @[simp] lemma arg_conj_coe_angle (x : ℂ) : (arg (conj x) : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_conj, h] end @[simp] lemma arg_inv_coe_angle (x : ℂ) : (arg x⁻¹ : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_inv, h] end lemma arg_neg_eq_arg_sub_pi_of_im_pos {x : ℂ} (hi : 0 < x.im) : arg (-x) = arg x - π := begin rw [arg_of_im_pos hi, arg_of_im_neg (show (-x).im < 0, from left.neg_neg_iff.2 hi)], simp [neg_div, real.arccos_neg] end lemma arg_neg_eq_arg_add_pi_of_im_neg {x : ℂ} (hi : x.im < 0) : arg (-x) = arg x + π := begin rw [arg_of_im_neg hi, arg_of_im_pos (show 0 < (-x).im, from left.neg_pos_iff.2 hi)], simp [neg_div, real.arccos_neg, add_comm, ←sub_eq_add_neg] end lemma arg_neg_eq_arg_sub_pi_iff {x : ℂ} : arg (-x) = arg x - π ↔ (0 < x.im ∨ x.im = 0 ∧ x.re < 0) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, hi.ne, hi.not_lt, arg_neg_eq_arg_add_pi_of_im_neg, sub_eq_add_neg, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr] }, { simp [hr, hi, real.pi_ne_zero] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr.not_lt, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] } }, { simp [hi, arg_neg_eq_arg_sub_pi_of_im_pos] } end lemma arg_neg_eq_arg_add_pi_iff {x : ℂ} : arg (-x) = arg x + π ↔ (x.im < 0 ∨ x.im = 0 ∧ 0 < x.re) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, arg_neg_eq_arg_add_pi_of_im_neg] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr.not_lt, ←two_mul, real.pi_ne_zero] }, { simp [hr, hi, real.pi_ne_zero.symm] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr] } }, { simp [hi, hi.ne.symm, hi.not_lt, arg_neg_eq_arg_sub_pi_of_im_pos, sub_eq_add_neg, ←add_eq_zero_iff_neg_eq, real.pi_ne_zero] } end lemma arg_neg_coe_angle {x : ℂ} (hx : x ≠ 0) : (arg (-x) : real.angle) = arg x + π := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { rw [arg_neg_eq_arg_add_pi_of_im_neg hi, real.angle.coe_add] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le, ←real.angle.coe_add, ←two_mul, real.angle.coe_two_pi, real.angle.coe_zero] }, { exact false.elim (hx (ext hr hi)) }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr), real.angle.coe_zero, zero_add] } }, { rw [arg_neg_eq_arg_sub_pi_of_im_pos hi, real.angle.coe_sub, real.angle.sub_coe_pi_eq_add_coe_pi] } end lemma arg_mul_cos_add_sin_mul_I_eq_to_Ioc_mod {r : ℝ} (hr : 0 < r) (θ : ℝ) : arg (r * (cos θ + sin θ * I)) = to_Ioc_mod (-π) real.two_pi_pos θ := begin have hi : to_Ioc_mod (-π) real.two_pi_pos θ ∈ Ioc (-π) π, { convert to_Ioc_mod_mem_Ioc _ real.two_pi_pos _, ring }, convert arg_mul_cos_add_sin_mul_I hr hi using 3, simp [to_Ioc_mod, cos_add_int_mul_two_pi, sin_add_int_mul_two_pi] end lemma arg_cos_add_sin_mul_I_eq_to_Ioc_mod (θ : ℝ) : arg (cos θ + sin θ * I) = to_Ioc_mod (-π) real.two_pi_pos θ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_eq_to_Ioc_mod zero_lt_one] lemma arg_mul_cos_add_sin_mul_I_sub {r : ℝ} (hr : 0 < r) (θ : ℝ) : arg (r * (cos θ + sin θ * I)) - θ = 2 * π * ⌊(π - θ) / (2 * π)⌋ := begin rw [arg_mul_cos_add_sin_mul_I_eq_to_Ioc_mod hr, to_Ioc_mod_sub_self, to_Ioc_div_eq_floor, zsmul_eq_mul], ring_nf end lemma arg_cos_add_sin_mul_I_sub (θ : ℝ) : arg (cos θ + sin θ * I) - θ = 2 * π * ⌊(π - θ) / (2 * π)⌋ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_sub zero_lt_one] lemma arg_mul_cos_add_sin_mul_I_coe_angle {r : ℝ} (hr : 0 < r) (θ : real.angle) : (arg (r * (real.angle.cos θ + real.angle.sin θ * I)) : real.angle) = θ := begin induction θ using real.angle.induction_on, rw [real.angle.cos_coe, real.angle.sin_coe, real.angle.angle_eq_iff_two_pi_dvd_sub], use ⌊(π - θ) / (2 * π)⌋, exact_mod_cast arg_mul_cos_add_sin_mul_I_sub hr θ end lemma arg_cos_add_sin_mul_I_coe_angle (θ : real.angle) : (arg (real.angle.cos θ + real.angle.sin θ * I) : real.angle) = θ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_coe_angle zero_lt_one] lemma arg_mul_coe_angle {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : (arg (x * y) : real.angle) = arg x + arg y := begin convert arg_mul_cos_add_sin_mul_I_coe_angle (mul_pos (abs_pos.2 hx) (abs_pos.2 hy)) (arg x + arg y : real.angle) using 3, simp_rw [←real.angle.coe_add, real.angle.sin_coe, real.angle.cos_coe, of_real_cos, of_real_sin, cos_add_sin_I, of_real_add, add_mul, exp_add, of_real_mul], rw [mul_assoc, mul_comm (exp _), ←mul_assoc (abs y : ℂ), abs_mul_exp_arg_mul_I, mul_comm y, ←mul_assoc, abs_mul_exp_arg_mul_I] end lemma arg_div_coe_angle {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : (arg (x / y) : real.angle) = arg x - arg y := by rw [div_eq_mul_inv, arg_mul_coe_angle hx (inv_ne_zero hy), arg_inv_coe_angle, sub_eq_add_neg] @[simp] lemma arg_coe_angle_to_real_eq_arg (z : ℂ) : (arg z : real.angle).to_real = arg z := begin rw real.angle.to_real_coe_eq_self_iff_mem_Ioc, exact arg_mem_Ioc _ end lemma arg_coe_angle_eq_iff_eq_to_real {z : ℂ} {θ : real.angle} : (arg z : real.angle) = θ ↔ arg z = θ.to_real := by rw [←real.angle.to_real_inj, arg_coe_angle_to_real_eq_arg] @[simp] lemma arg_coe_angle_eq_iff {x y : ℂ} : (arg x : real.angle) = arg y ↔ arg x = arg y := by simp_rw [←real.angle.to_real_inj, arg_coe_angle_to_real_eq_arg] section continuity variables {x z : ℂ} lemma arg_eq_nhds_of_re_pos (hx : 0 < x.re) : arg =ᶠ[𝓝 x] λ x, real.arcsin (x.im / x.abs) := ((continuous_re.tendsto _).eventually (lt_mem_nhds hx)).mono $ λ y hy, arg_of_re_nonneg hy.le lemma arg_eq_nhds_of_re_neg_of_im_pos (hx_re : x.re < 0) (hx_im : 0 < x.im) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) + π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ 0 < y.im, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_nonneg hy.1 hy.2.le), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ 0 < x.im), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_zero continuous_im), end lemma arg_eq_nhds_of_re_neg_of_im_neg (hx_re : x.re < 0) (hx_im : x.im < 0) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) - π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ y.im < 0, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_neg hy.1 hy.2), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ x.im < 0), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_im continuous_zero), end lemma arg_eq_nhds_of_im_pos (hz : 0 < im z) : arg =ᶠ[𝓝 z] λ x, real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (lt_mem_nhds hz)).mono $ λ x, arg_of_im_pos lemma arg_eq_nhds_of_im_neg (hz : im z < 0) : arg =ᶠ[𝓝 z] λ x, -real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (gt_mem_nhds hz)).mono $ λ x, arg_of_im_neg lemma continuous_at_arg (h : 0 < x.re ∨ x.im ≠ 0) : continuous_at arg x := begin have h₀ : abs x ≠ 0, { rw abs_ne_zero, rintro rfl, simpa using h }, rw [← lt_or_lt_iff_ne] at h, rcases h with (hx_re|hx_im|hx_im), exacts [(real.continuous_at_arcsin.comp (continuous_im.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_re_pos hx_re).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).neg.congr (arg_eq_nhds_of_im_neg hx_im).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_im_pos hx_im).symm] end lemma tendsto_arg_nhds_within_im_neg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)) := begin suffices H : tendsto (λ x : ℂ, real.arcsin ((-x).im / x.abs) - π) (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)), { refine H.congr' _, have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_neg him.not_le], }, convert (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).sub tendsto_const_nhds, { simp [him] }, { lift z to ℝ using him, simpa using hre.ne } end lemma continuous_within_at_arg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : continuous_within_at arg {z : ℂ | 0 ≤ z.im} z := begin have : arg =ᶠ[𝓝[{z : ℂ | 0 ≤ z.im}] z] λ x, real.arcsin ((-x).im / x.abs) + π, { have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_pos him] }, refine continuous_within_at.congr_of_eventually_eq _ this _, { refine (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).add tendsto_const_nhds, lift z to ℝ using him, simpa using hre.ne }, { rw [arg, if_neg hre.not_le, if_pos him.ge] } end lemma tendsto_arg_nhds_within_im_nonneg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | 0 ≤ z.im}] z) (𝓝 π) := by simpa only [arg_eq_pi_iff.2 ⟨hre, him⟩] using (continuous_within_at_arg_of_re_neg_of_im_zero hre him).tendsto lemma continuous_at_arg_coe_angle (h : x ≠ 0) : continuous_at (coe ∘ arg : ℂ → real.angle) x := begin by_cases hs : 0 < x.re ∨ x.im ≠ 0, { exact real.angle.continuous_coe.continuous_at.comp (continuous_at_arg hs) }, { rw [←function.comp.right_id (coe ∘ arg), (function.funext_iff.2 (λ _, (neg_neg _).symm) : (id : ℂ → ℂ) = has_neg.neg ∘ has_neg.neg), ←function.comp.assoc], refine continuous_at.comp _ continuous_neg.continuous_at, suffices : continuous_at (function.update ((coe ∘ arg) ∘ has_neg.neg : ℂ → real.angle) 0 π) (-x), by rwa continuous_at_update_of_ne (neg_ne_zero.2 h) at this, have ha : function.update ((coe ∘ arg) ∘ has_neg.neg : ℂ → real.angle) 0 π = λ z, (arg z : real.angle) + π, { rw function.update_eq_iff, exact ⟨by simp, λ z hz, arg_neg_coe_angle hz⟩ }, rw ha, push_neg at hs, refine (real.angle.continuous_coe.continuous_at.comp (continuous_at_arg (or.inl _))).add continuous_at_const, rw [neg_re, neg_pos], exact hs.1.lt_of_ne (λ h0, h (ext_iff.2 ⟨h0, hs.2⟩)) } end end continuity end complex
beb7d92143fdb882f56a21a0a6fdc81c8b92d297
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/algebra/group_power.lean
389f17f72f36afa6f1e8739cf88ad6126a512daf
[ "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
27,178
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis The power operation on monoids and groups. We separate this from group, because it depends on nat, which in turn depends on other parts of algebra. We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation a^n is used for the first, but users can locally redefine it to gpow when needed. Note: power adopts the convention that 0^0=1. -/ import algebra.group import data.int.basic data.list.basic universes u v variable {α : Type u} @[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] @[simp] theorem inv_inv' [discrete_field α] {a:α} : a⁻¹⁻¹ = a := by rw [inv_eq_one_div, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_one] /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [monoid α] (a : α) : ℕ → α | 0 := 1 | (n+1) := a * monoid.pow n def add_monoid.smul [add_monoid α] (n : ℕ) (a : α) : α := @monoid.pow (multiplicative α) _ a n precedence `•`:70 local infix ` • ` := add_monoid.smul @[priority 5] instance monoid.has_pow [monoid α] : has_pow α ℕ := ⟨monoid.pow⟩ /- monoid -/ section monoid variables [monoid α] {β : Type u} [add_monoid β] @[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl @[simp] theorem add_monoid.zero_smul (a : β) : 0 • a = 0 := rfl attribute [to_additive add_monoid.zero_smul] pow_zero theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_smul (a : β) (n : ℕ) : (n+1)•a = a + n•a := rfl attribute [to_additive succ_smul] pow_succ @[simp] theorem pow_one (a : α) : a^1 = a := mul_one _ @[simp] theorem add_monoid.one_smul (a : β) : 1•a = a := add_zero _ attribute [to_additive add_monoid.one_smul] pow_one theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; [rw [pow_zero, one_mul, mul_one], rw [pow_succ, mul_assoc, ih]] theorem smul_add_comm' : ∀ (a : β) (n : ℕ), n•a + a = a + n•a := @pow_mul_comm' (multiplicative β) _ theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_smul' (a : β) (n : ℕ) : (n+1)•a = n•a + a := by rw [succ_smul, smul_add_comm'] attribute [to_additive succ_smul'] pow_succ' theorem pow_two (a : α) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_smul (a : β) : 2•a = a + a := show a+(a+0)=a+a, by rw add_zero attribute [to_additive two_smul] pow_two theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl theorem add_monoid.add_smul : ∀ (a : β) (m n : ℕ), (m + n)•a = m•a + n•a := @pow_add (multiplicative β) _ attribute [to_additive add_monoid.add_smul] pow_add @[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : β) = (0:β) := by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]] attribute [to_additive add_monoid.smul_zero] one_pow theorem pow_mul (a : α) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem add_monoid.mul_smul' : ∀ (a : β) (m n : ℕ), m * n • a = n•(m•a) := @pow_mul (multiplicative β) _ attribute [to_additive add_monoid.mul_smul'] pow_mul theorem pow_mul' (a : α) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem add_monoid.mul_smul (a : β) (m n : ℕ) : m * n • a = m•(n•a) := by rw [mul_comm, add_monoid.mul_smul'] attribute [to_additive add_monoid.mul_smul] pow_mul' @[simp] theorem add_monoid.smul_one [has_one β] : ∀ n : ℕ, n • (1 : β) = n := nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _) theorem pow_bit0 (a : α) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_smul (a : β) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _ attribute [to_additive bit0_smul] pow_bit0 theorem pow_bit1 (a : α) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_smul : ∀ (a : β) (n : ℕ), bit1 n • a = n•a + n•a + a := @pow_bit1 (multiplicative β) _ attribute [to_additive bit1_smul] pow_bit1 theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] theorem smul_add_comm : ∀ (a : β) (m n : ℕ), m•a + n•a = n•a + m•a := @pow_mul_comm (multiplicative β) _ attribute [to_additive smul_add_comm] pow_mul_comm @[simp] theorem list.prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n := by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl @[simp] theorem list.sum_repeat : ∀ (a : β) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative β) _ attribute [to_additive list.sum_repeat] list.prod_repeat @[simp] lemma units.coe_pow (u : units α) (n : ℕ) : ((u ^ n : units α) : α) = u ^ n := by induction n; simp [*, pow_succ] end monoid namespace is_monoid_hom variables {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] theorem map_pow (a : α) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := is_monoid_hom.map_one f | (nat.succ n) := by rw [pow_succ, is_monoid_hom.map_mul f, map_pow n]; refl end is_monoid_hom namespace is_add_monoid_hom variables {β : Type*} [add_monoid α] [add_monoid β] (f : α → β) [is_add_monoid_hom f] theorem map_smul (a : α) : ∀(n : ℕ), f (n • a) = n • (f a) | 0 := is_add_monoid_hom.map_zero f | (nat.succ n) := by rw [succ_smul, is_add_monoid_hom.map_add f, map_smul n]; refl end is_add_monoid_hom attribute [to_additive is_add_monoid_hom.map_smul] is_monoid_hom.map_pow @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]] @[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul], rw [succ_smul', ih, nat.succ_mul]] /- commutative monoid -/ section comm_monoid variables [comm_monoid α] {β : Type*} [add_comm_monoid β] theorem mul_pow (a b : α) (n : ℕ) : (a * b)^n = a^n * b^n := by induction n with n ih; [exact (mul_one _).symm, simp only [pow_succ, ih, mul_assoc, mul_left_comm]] theorem add_monoid.smul_add : ∀ (a b : β) (n : ℕ), n•(a + b) = n•a + n•b := @mul_pow (multiplicative β) _ attribute [to_additive add_monoid.add_smul] mul_pow instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : α → α) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance add_monoid.smul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (add_monoid.smul n : β → β) := { map_add := λ _ _, add_monoid.smul_add _ _ _, map_zero := add_monoid.smul_zero _ } attribute [to_additive add_monoid.smul.is_add_monoid_hom] pow.is_monoid_hom end comm_monoid section group variables [group α] {β : Type*} [add_group β] section nat @[simp] theorem inv_pow (a : α) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem add_monoid.neg_smul : ∀ (a : β) (n : ℕ), n•(-a) = -(n•a) := @inv_pow (multiplicative β) _ attribute [to_additive add_monoid.neg_smul] inv_pow theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem add_monoid.smul_sub : ∀ (a : β) {m n : ℕ}, m ≥ n → (m - n)•a = m•a - n•a := @pow_sub (multiplicative β) _ attribute [to_additive add_monoid.smul_sub] inv_pow theorem pow_inv_comm (a : α) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _) theorem add_monoid.smul_neg_comm : ∀ (a : β) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) := @pow_inv_comm (multiplicative β) _ attribute [to_additive add_monoid.smul_neg_comm] pow_inv_comm end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : α) : ℤ → α | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ def gsmul (n : ℤ) (a : β) : β := @gpow (multiplicative β) _ a n @[priority 10] instance group.has_pow : has_pow α ℤ := ⟨gpow⟩ local infix ` • `:70 := gsmul local infix ` •ℕ `:70 := add_monoid.smul @[simp] theorem gpow_coe_nat (a : α) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : β) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl attribute [to_additive gsmul_coe_nat] gpow_coe_nat @[simp] theorem gpow_of_nat (a : α) (n : ℕ) : a ^ of_nat n = a ^ n := rfl @[simp] theorem gsmul_of_nat (a : β) (n : ℕ) : of_nat n • a = n •ℕ a := rfl attribute [to_additive gsmul_of_nat] gpow_of_nat @[simp] theorem gpow_neg_succ (a : α) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ (a : β) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl attribute [to_additive gsmul_neg_succ] gpow_neg_succ local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : α) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : β) : (0:ℤ) • a = 0 := rfl attribute [to_additive zero_gsmul] gpow_zero @[simp] theorem gpow_one (a : α) : a ^ (1:ℤ) = a := mul_one _ @[simp] theorem one_gsmul (a : β) : (1:ℤ) • a = a := add_zero _ attribute [to_additive one_gsmul] gpow_one @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : α) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:α), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : β) = 0 := @one_gpow (multiplicative β) _ attribute [to_additive gsmul_zero] one_gpow @[simp] theorem gpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm @[simp] theorem neg_gsmul : ∀ (a : β) (n : ℤ), -n • a = -(n • a) := @gpow_neg (multiplicative β) _ attribute [to_additive neg_gsmul] gpow_neg theorem gpow_neg_one (x : α) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : β) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x attribute [to_additive neg_one_gsmul] gpow_neg_one theorem inv_gpow (a : α) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) private lemma gpow_add_aux (a : α) (m n : nat) : a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] := or.elim (nat.lt_or_ge m (nat.succ n)) (assume h1 : m < succ n, have h2 : m ≤ n, from le_of_lt_succ h1, suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by rwa [of_nat_add_neg_succ_of_nat_of_lt h1], show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl) (assume : m ≥ succ n, suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : α) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux, gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm] | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this, by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem add_gsmul : ∀ (a : β) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative β) _ theorem gpow_add_one (a : α) (i : ℤ) : a ^ (i + 1) = a ^ i * a := by rw [gpow_add, gpow_one] theorem add_one_gsmul : ∀ (a : β) (i : ℤ), (i + 1) • a = i • a + a := @gpow_add_one (multiplicative β) _ attribute [to_additive add_one_gsmul] gpow_add_one theorem gpow_one_add (a : α) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : β) (i : ℤ), (1 + i) • a = a + i • a := @gpow_one_add (multiplicative β) _ attribute [to_additive one_add_gsmul] gpow_one_add theorem gpow_mul_comm (a : α) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : β) (i j), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative β) _ attribute [to_additive gsmul_add_comm] gpow_mul_comm theorem gpow_mul (a : α) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n | (m : ℕ) (n : ℕ) := pow_mul _ _ _ | (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $ show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl | -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $ show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl | -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv] theorem gsmul_mul' : ∀ (a : β) (m n : ℤ), m * n • a = n • (m • a) := @gpow_mul (multiplicative β) _ attribute [to_additive gsmul_mul'] gpow_mul theorem gpow_mul' (a : α) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : β) (m n : ℤ) : m * n • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] attribute [to_additive gsmul_mul] gpow_mul' theorem gpow_bit0 (a : α) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : β) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _ attribute [to_additive bit0_gsmul] gpow_bit0 theorem gpow_bit1 (a : α) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : β) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative β) _ attribute [to_additive bit1_gsmul] gpow_bit1 theorem gsmul_neg (a : β) (n : ℤ) : gsmul n (- a) = - gsmul n a := begin induction n using int.induction_on with z ih z ih, { simp }, { rw [add_comm] {occs := occurrences.pos [1]}, simp [add_gsmul, ih, -add_comm] }, { rw [sub_eq_add_neg, add_comm] {occs := occurrences.pos [1]}, simp [ih, add_gsmul, neg_gsmul, -add_comm] } end attribute [to_additive gsmul_neg] gpow_neg end group namespace is_group_hom variables {β : Type v} [group α] [group β] (f : α → β) [is_group_hom f] theorem map_pow (a : α) (n : ℕ) : f (a ^ n) = f a ^ n := is_monoid_hom.map_pow f a n theorem map_gpow (a : α) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact is_group_hom.map_pow f _ _, exact (is_group_hom.map_inv f _).trans (congr_arg _ $ is_group_hom.map_pow f _ _)] end is_group_hom namespace is_add_group_hom variables {β : Type v} [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] theorem map_smul (a : α) (n : ℕ) : f (n • a) = n • f a := is_add_monoid_hom.map_smul f a n theorem map_gsmul (a : α) (n : ℤ) : f (gsmul n a) = gsmul n (f a) := @is_group_hom.map_gpow (multiplicative α) (multiplicative β) _ _ f _ a n end is_add_group_hom local infix ` •ℤ `:70 := gsmul section comm_monoid variables [comm_group α] {β : Type*} [add_comm_group β] theorem mul_gpow (a b : α) : ∀ n:ℤ, (a * b)^n = a^n * b^n | (n : ℕ) := mul_pow a b n | -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm] theorem gsmul_add : ∀ (a b : β) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative β) _ attribute [to_additive gsmul_add] mul_gpow theorem gsmul_sub : ∀ (a b : β) (n : ℤ), gsmul n (a - b) = gsmul n a - gsmul n b := by simp [gsmul_add, gsmul_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : α → α) := ⟨λ _ _, mul_gpow _ _ n⟩ instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : β → β) := ⟨λ _ _, gsmul_add _ _ n⟩ attribute [to_additive gsmul.is_add_group_hom] gpow.is_group_hom end comm_monoid section group @[instance] theorem is_add_group_hom.gsmul {α β} [add_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] (z : ℤ) : is_add_group_hom (λa, gsmul z (f a)) := ⟨assume a b, by rw [is_add_group_hom.map_add f, gsmul_add]⟩ end group @[simp] lemma with_bot.coe_smul [add_monoid α] (a : α) (n : ℕ) : ((add_monoid.smul n a : α) : with_bot α) = add_monoid.smul n a := by induction n; simp [*, succ_smul]; refl theorem add_monoid.smul_eq_mul' [semiring α] (a : α) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero], rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]] theorem add_monoid.smul_eq_mul [semiring α] (n : ℕ) (a : α) : n • a = n * a := by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm] theorem add_monoid.mul_smul_left [semiring α] (a b : α) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc] theorem add_monoid.mul_smul_assoc [semiring α] (a b : α) (n : ℕ) : n • (a * b) = n • a * b := by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc] lemma zero_pow [semiring α] : ∀ {n : ℕ}, 0 < n → (0 : α) ^ n = 0 | (n+1) _ := zero_mul _ @[simp] theorem nat.cast_pow [semiring α] (n m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] theorem is_semiring_hom.map_pow {β} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] (x : α) (n : ℕ) : f (x ^ n) = f x ^ n := by induction n with n ih; [exact is_semiring_hom.map_one f, rw [pow_succ, pow_succ, is_semiring_hom.map_mul f, ih]] theorem neg_one_pow_eq_or {R} [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [comm_semiring α] (a : α) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem gsmul_eq_mul [ring α] (a : α) : ∀ n, n •ℤ a = n * a | (n : ℕ) := add_monoid.smul_eq_mul _ _ | -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring α] (a : α) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, int.mul_cast_comm] theorem mul_gsmul_left [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] theorem int.cast_pow [ring α] (n : ℤ) (m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring α] {n : ℕ} : (-1 : α) ^ n = -1 ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem pow_eq_zero [domain α] {x : α} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end theorem pow_ne_zero [domain α] {a : α} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h @[simp] theorem one_div_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : (1 / a) ^ n = 1 / a ^ n := by induction n with n ih; [exact (div_one _).symm, rw [pow_succ', ih, division_ring.one_div_mul_one_div (pow_ne_zero _ ha) ha]]; refl @[simp] theorem division_ring.inv_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ := by simpa only [inv_eq_one_div] using one_div_pow ha n @[simp] theorem div_pow [field α] (a : α) {b : α} (hb : b ≠ 0) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_one_div, mul_pow, one_div_pow hb, ← div_eq_mul_one_div] theorem add_monoid.smul_nonneg [ordered_comm_monoid α] {a : α} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a | 0 := le_refl _ | (n+1) := add_nonneg' H (add_monoid.smul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring α] (a : α) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma inv_pow' [discrete_field α] (a : α) (n : ℕ) : (a ^ n)⁻¹ = a⁻¹ ^ n := by induction n; simp [*, pow_succ, mul_inv', mul_comm] lemma pow_inv [division_ring α] (a : α) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n | 0 ha := inv_one | (n+1) ha := by rw [pow_succ, pow_succ', mul_inv_eq (pow_ne_zero _ ha) ha, pow_inv _ ha] namespace add_monoid variable [ordered_comm_monoid α] theorem smul_le_smul {a : α} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := let ⟨k, hk⟩ := nat.le.dest h in calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + k • a : add_le_add_left' (smul_nonneg ha _) ... = m • a : by rw [← hk, add_smul] lemma smul_le_smul_of_le_right {a b : α} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b | 0 := by simp | (k+1) := add_le_add' hab (smul_le_smul_of_le_right _) end add_monoid section linear_ordered_semiring variable [linear_ordered_semiring α] theorem pow_pos {a : α} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : α} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : α} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_right_inj {x y : α} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) theorem pow_ge_one_add_mul {a : α} (H : a ≥ 0) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := begin rw [pow_succ', succ_smul'], refine le_trans _ (mul_le_mul_of_nonneg_right (pow_ge_one_add_mul n) (add_nonneg zero_le_one H)), rw [mul_add, mul_one, ← add_assoc, add_le_add_iff_left], simpa only [one_mul] using mul_le_mul_of_nonneg_right ((le_add_iff_nonneg_right 1).2 (add_monoid.smul_nonneg H n)) H end theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : α} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : α} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : α} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : α} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp, rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : α} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : α} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : α} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : α} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : α) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring α] (a : α) : 0 ≤ a ^ 2 := by rw pow_two; exact mul_self_nonneg _ theorem pow_ge_one_add_sub_mul [linear_ordered_ring α] {a : α} (H : a ≥ 1) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n := by simpa only [add_sub_cancel'_right] using pow_ge_one_add_mul (sub_nonneg.2 H) n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma div_sq_cancel {α} [field α] {a : α} (ha : a ≠ 0) (b : α) : a^2 * b / a = a * b := by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
1fd03e6b44768685cdb367eec4278cdd144f77c6
96e44fc78cabfc9d646dc37d0e756189b6b79181
/library/init/algebra/order.lean
beae81f0ce5c1240a192b318599029aa8d18b687
[ "Apache-2.0" ]
permissive
TwoFX/lean
23c73c10a340f5a381f6abf27a27f53f1fb7e2e3
7e3f336714055869690b7309b6bb651fbc67e76e
refs/heads/master
1,612,504,908,183
1,594,641,622,000
1,594,641,622,000
243,750,847
0
0
Apache-2.0
1,582,890,661,000
1,582,890,661,000
null
UTF-8
Lean
false
false
9,242
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.classical init.meta.name init.algebra.classes /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u variables {α : Type u} set_option auto_param.check_exists false /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class preorder (α : Type u) extends has_le α, has_lt α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (lt := λ a b, a ≤ b ∧ ¬ b ≤ a) (lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) . order_laws_tac) /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class partial_order (α : Type u) extends preorder α := (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`.-/ class linear_order (α : Type u) extends partial_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) @[refl] lemma le_refl [preorder α] : ∀ a : α, a ≤ a := preorder.le_refl @[trans] lemma le_trans [preorder α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := preorder.le_trans lemma lt_iff_le_not_le [preorder α] : ∀ {a b : α}, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := preorder.lt_iff_le_not_le lemma lt_of_le_not_le [preorder α] : ∀ {a b : α}, a ≤ b → ¬ b ≤ a → a < b | a b hab hba := lt_iff_le_not_le.mpr ⟨hab, hba⟩ lemma le_not_le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b ∧ ¬ b ≤ a | a b hab := lt_iff_le_not_le.mp hab lemma le_antisymm [partial_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := partial_order.le_antisymm lemma le_of_eq [preorder α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a lemma le_antisymm_iff [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨λe, ⟨le_of_eq e, le_of_eq e.symm⟩, λ⟨h1, h2⟩, le_antisymm h1 h2⟩ @[trans] lemma ge_trans [preorder α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_order.le_total lemma le_of_not_ge [linear_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le [linear_order α] {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma lt_irrefl [preorder α] : ∀ a : α, ¬ a < a | a haa := match le_not_le_of_lt haa with | ⟨h1, h2⟩ := false.rec _ (h2 h1) end lemma gt_irrefl [preorder α] : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans [preorder α] : ∀ {a b c : α}, a < b → b < c → a < c | a b c hab hbc := match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ := lt_of_le_not_le (le_trans hab hbc) (λ hca, hcb (le_trans hca hab)) end def lt.trans := @lt_trans @[trans] lemma gt_trans [preorder α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ def gt.trans := @gt_trans lemma ne_of_lt [preorder α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [preorder α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [preorder α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [linear_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b | a b hab := (le_not_le_of_lt hab).left @[trans] lemma lt_of_lt_of_le [preorder α] : ∀ {a b c : α}, a < b → b ≤ c → a < c | a b c hab hbc := let ⟨hab, hba⟩ := le_not_le_of_lt hab in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hba (le_trans hbc hca) @[trans] lemma lt_of_le_of_lt [preorder α] : ∀ {a b c : α}, a ≤ b → b < c → a < c | a b c hab hbc := let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hcb (le_trans hca hab) @[trans] lemma gt_of_gt_of_ge [preorder α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt [preorder α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ lemma not_le_of_gt [preorder α] {a b : α} (h : a > b) : ¬ a ≤ b := (le_not_le_of_lt h).right lemma not_lt_of_ge [preorder α] {a b : α} (h : a ≥ b) : ¬ a < b := λ hab, not_le_of_gt hab h lemma lt_or_eq_of_le [partial_order α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b | a b hab := classical.by_cases (λ hba : b ≤ a, or.inr (le_antisymm hab hba)) (λ hba, or.inl (lt_of_le_not_le hab hba)) lemma le_of_lt_or_eq [preorder α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b | a b (or.inl hab) := le_of_lt hab | a b (or.inr hab) := hab ▸ le_refl _ lemma le_iff_lt_or_eq [partial_order α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b | a b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma lt_of_le_of_ne [partial_order α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, or.resolve_right (lt_or_eq_of_le h₁) h₂ lemma lt_trichotomy [linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h.symm))) lemma le_of_not_gt [linear_order α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_order α] {a b : α} (h : ¬ a ≥ b) : a < b := match lt_trichotomy a b with | or.inl hlt := hlt | or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h | or.inr (or.inr hgt) := absurd (le_of_lt hgt) h end lemma lt_or_ge [linear_order α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_order α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end lemma le_of_eq_or_lt [preorder α] {a b : α} (h : a = b ∨ a < b) : a ≤ b := or.elim h le_of_eq le_of_lt lemma ne_iff_lt_or_gt [linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λo, or.elim o ne_of_lt ne_of_gt⟩ lemma lt_iff_not_ge [linear_order α] (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ instance decidable_lt_of_decidable_le [preorder α] [decidable_rel ((≤) : α → α → Prop)] : decidable_rel ((<) : α → α → Prop) | a b := if hab : a ≤ b then if hba : b ≤ a then is_false $ λ hab', not_le_of_gt hab' hba else is_true $ lt_of_le_not_le hab hba else is_false $ λ hab', hab (le_of_lt hab') instance decidable_eq_of_decidable_le [partial_order α] [decidable_rel ((≤) : α → α → Prop)] : decidable_eq α | a b := if hab : a ≤ b then if hba : b ≤ a then is_true (le_antisymm hab hba) else is_false (λ heq, hba (heq ▸ le_refl _)) else is_false (λ heq, hab (heq ▸ le_refl _)) class decidable_linear_order (α : Type u) extends linear_order α := (decidable_le : decidable_rel (≤)) (decidable_eq : decidable_eq α := @decidable_eq_of_decidable_le _ _ decidable_le) (decidable_lt : decidable_rel ((<) : α → α → Prop) := @decidable_lt_of_decidable_le _ _ decidable_le) instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := decidable_linear_order.decidable_le a b instance [decidable_linear_order α] (a b : α) : decidable (a = b) := decidable_linear_order.decidable_eq a b lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁))) instance [decidable_linear_order α] : is_total_preorder α (≤) := {trans := @le_trans _ _, total := le_total} /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_weak_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_weak_order α (<) := is_strict_weak_order_of_is_total_preorder lt_iff_not_ge /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_total_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_total_order α (<) := { trichotomous := lt_trichotomy }
968ca3b0d3be0c109ec687bb52c46a6b45c2299c
37336e9dcf558f325cf43bdf45bab5d8e455a3b4
/xenalib/real_experiments.lean
08465f0bcec78a1d6c20a178b37030c57197f7a1
[]
no_license
rafaelbailo/xena
bfeab41b3b401c812689a4879d58f2ad046240b5
fad865c3d1bac6279f9a77e8aa6ba7e0cd572e06
refs/heads/master
1,626,002,809,060
1,507,793,086,000
1,507,793,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,611
lean
/- Fake real numbers. There are technical difficulties in accessing real numbers in the online version of Lean. Anyone who is using Lean online but wants real numbers can just cut and paste the below code. This gives us a class "real", which is a fake version of the real numbers. See if you can spot any differences! -/ constant real : Type -- note to self -- so I now have a new constant, which -- is like a new axiom saying "there exists a type in our -- system called `real' ". Currently this type has nothing to do -- with the real numbers, other than the name. @[instance] constant real_field : linear_ordered_field real -- Informally, real_field is the assertion that our -- new real type is actually a linearly ordered field. -- This means, amongst other things, that now, given -- two real numbers a and b (i.e. two things of type real) -- we should be able to add, subtract and multiply them, -- and also see if a is less than b. -- We might have to mention real_field, which is somehow -- the dictionary of all these facts. -- note to self -- how to make this a Q-algebra? -- Oh! Can't do this because no Q or R! #check ((↑(2:nat)):real) example : ∀ a b : real, a * b = b * a := begin exact mul_comm end example (a b : real) : a * b = b * a := begin simp [mul_comm] end #check mul_comm variables a b : real #check a*b #check linear_ordered_field real attribute [instance] real_field #check (45 : real) example (a b c : real) : a * (b + c) = a * c + a * b := by simp [mul_add] #check @mul_add variable x : real #eval (nat.add 3 4) #check real_field.add #check (x^2)
87842a36a4a87faa3b6b456b95e3632b1ba3c06a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/hole_issue2.lean
299e22bc6f3705cdde418f4aba375cf3b2c21094
[ "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
1,838
lean
constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid definition bag (A : Type) : Type := quotient (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quotient.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix (name := subbag) ` ⊆ ` := subbag noncomputable definition decidable_subbag_1 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, _)) end) noncomputable definition decidable_subbag_2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) _) end) noncomputable definition decidable_subbag_3 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, _) end)
fe0a26096dd0a9bd5b5e29856cc2f01e517cbb70
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/instances/real_auto.lean
130b24b8487d63cba0dc76feb32f8c197d497ce3
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
9,138
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.metric_space.basic import Mathlib.topology.algebra.uniform_group import Mathlib.topology.algebra.ring import Mathlib.topology.algebra.continuous_functions import Mathlib.ring_theory.subring import Mathlib.group_theory.archimedean import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Topological properties of ℝ -/ protected instance rat.metric_space : metric_space ℚ := metric_space.induced coe sorry real.metric_space theorem rat.dist_eq (x : ℚ) (y : ℚ) : dist x y = abs (↑x - ↑y) := rfl @[simp] theorem rat.dist_cast (x : ℚ) (y : ℚ) : dist ↑x ↑y = dist x y := rfl -- we want to ignore this instance for the next declaration protected instance int.metric_space : metric_space ℤ := let M : metric_space ℤ := metric_space.induced coe sorry real.metric_space; metric_space.replace_uniformity M sorry theorem int.dist_eq (x : ℤ) (y : ℤ) : dist x y = abs (↑x - ↑y) := rfl @[simp] theorem int.dist_cast_real (x : ℤ) (y : ℤ) : dist ↑x ↑y = dist x y := rfl @[simp] theorem int.dist_cast_rat (x : ℤ) (y : ℤ) : dist ↑x ↑y = dist x y := sorry theorem uniform_continuous_of_rat : uniform_continuous coe := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding coe := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding coe := sorry theorem embedding_of_rat : embedding coe := dense_embedding.to_embedding dense_embedding_of_rat theorem continuous_of_rat : continuous coe := uniform_continuous.continuous uniform_continuous_of_rat theorem real.uniform_continuous_add : uniform_continuous fun (p : ℝ × ℝ) => prod.fst p + prod.snd p := sorry -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous fun (p : ℚ × ℚ) => prod.fst p + prod.snd p := sorry theorem real.uniform_continuous_neg : uniform_continuous Neg.neg := sorry theorem rat.uniform_continuous_neg : uniform_continuous Neg.neg := sorry protected instance real.uniform_add_group : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg protected instance rat.uniform_add_group : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg protected instance real.topological_add_group : topological_add_group ℝ := linear_ordered_add_comm_group.topological_add_group protected instance rat.topological_add_group : topological_add_group ℚ := uniform_add_group.to_topological_add_group protected instance rat.order_topology : order_topology ℚ := induced_order_topology coe (fun (x y : ℚ) => rat.cast_lt) exists_rat_btwn theorem real.is_topological_basis_Ioo_rat : topological_space.is_topological_basis (set.Union fun (a : ℚ) => set.Union fun (b : ℚ) => set.Union fun (h : a < b) => singleton (set.Ioo ↑a ↑b)) := sorry protected instance real.topological_space.second_countable_topology : topological_space.second_countable_topology ℝ := sorry /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ theorem real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ (ε : ℝ) (H : ε > 0), ∃ (y : ℝ), ∃ (H : y ∈ s), abs (y - x) < ε := sorry theorem real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ (x : ℝ), x ∈ s → r ≤ abs x) : uniform_continuous fun (p : ↥s) => subtype.val p⁻¹ := sorry theorem real.uniform_continuous_abs : uniform_continuous abs := iff.mpr metric.uniform_continuous_iff fun (ε : ℝ) (ε0 : ε > 0) => Exists.intro ε (Exists.intro ε0 fun (a b : ℝ) => lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub a b)) theorem rat.uniform_continuous_abs : uniform_continuous abs := sorry theorem real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : filter.tendsto (fun (q : ℝ) => q⁻¹) (nhds r) (nhds (r⁻¹)) := sorry theorem real.continuous_inv : continuous fun (a : Subtype fun (r : ℝ) => r ≠ 0) => subtype.val a⁻¹ := sorry theorem real.continuous.inv {α : Type u} [topological_space α] {f : α → ℝ} (h : ∀ (a : α), f a ≠ 0) (hf : continuous f) : continuous fun (a : α) => f a⁻¹ := (fun (this : continuous ((has_inv.inv ∘ subtype.val) ∘ fun (a : α) => { val := f a, property := h a })) => this) (continuous.comp real.continuous_inv (continuous_subtype_mk (fun (a : α) => h a) hf)) theorem real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous (Mul.mul x) := sorry theorem real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ : ℝ} {r₂ : ℝ} (H : ∀ (x : ℝ × ℝ), x ∈ s → abs (prod.fst x) < r₁ ∧ abs (prod.snd x) < r₂) : uniform_continuous fun (p : ↥s) => prod.fst (subtype.val p) * prod.snd (subtype.val p) := sorry protected theorem real.continuous_mul : continuous fun (p : ℝ × ℝ) => prod.fst p * prod.snd p := sorry protected instance real.topological_ring : topological_ring ℝ := topological_ring.mk continuous_neg protected instance real.topological_semiring : topological_semiring ℝ := topological_ring.to_topological_semiring ℝ theorem rat.continuous_mul : continuous fun (p : ℚ × ℚ) => prod.fst p * prod.snd p := sorry protected instance rat.topological_ring : topological_ring ℚ := topological_ring.mk continuous_neg theorem real.ball_eq_Ioo (x : ℝ) (ε : ℝ) : metric.ball x ε = set.Ioo (x - ε) (x + ε) := sorry theorem real.Ioo_eq_ball (x : ℝ) (y : ℝ) : set.Ioo x y = metric.ball ((x + y) / bit0 1) ((y - x) / bit0 1) := sorry theorem real.totally_bounded_Ioo (a : ℝ) (b : ℝ) : totally_bounded (set.Ioo a b) := sorry theorem real.totally_bounded_ball (x : ℝ) (ε : ℝ) : totally_bounded (metric.ball x ε) := eq.mpr (id (Eq._oldrec (Eq.refl (totally_bounded (metric.ball x ε))) (real.ball_eq_Ioo x ε))) (real.totally_bounded_Ioo (x - ε) (x + ε)) theorem real.totally_bounded_Ico (a : ℝ) (b : ℝ) : totally_bounded (set.Ico a b) := sorry theorem real.totally_bounded_Icc (a : ℝ) (b : ℝ) : totally_bounded (set.Icc a b) := sorry theorem rat.totally_bounded_Icc (a : ℚ) (b : ℚ) : totally_bounded (set.Icc a b) := sorry protected instance real.complete_space : complete_space ℝ := sorry theorem closure_of_rat_image_lt {q : ℚ} : closure (coe '' set_of fun (x : ℚ) => q < x) = set_of fun (r : ℝ) => ↑q ≤ r := sorry /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ theorem compact_Icc {a : ℝ} {b : ℝ} : is_compact (set.Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) theorem compact_pi_Icc {ι : Type u_1} {a : ι → ℝ} {b : ι → ℝ} : is_compact (set.Icc a b) := Eq.subst (set.pi_univ_Icc a b) compact_univ_pi fun (i : ι) => compact_Icc protected instance real.proper_space : proper_space ℝ := proper_space.mk fun (x r : ℝ) => eq.mpr (id (Eq._oldrec (Eq.refl (is_compact (metric.closed_ball x r))) closed_ball_Icc)) compact_Icc theorem real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : metric.bounded s ↔ bdd_below s ∧ bdd_above s := sorry theorem real.image_Icc {f : ℝ → ℝ} {a : ℝ} {b : ℝ} (hab : a ≤ b) (h : continuous_on f (set.Icc a b)) : f '' set.Icc a b = set.Icc (Inf (f '' set.Icc a b)) (Sup (f '' set.Icc a b)) := sorry protected instance reals_semimodule : topological_semimodule ℝ ℝ := topological_semimodule.mk continuous_mul protected instance real_maps_algebra {α : Type u_1} [topological_space α] : algebra ℝ (continuous_map α ℝ) := Mathlib.continuous_map_algebra /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ theorem real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬∃ (a : ℝ), is_least (set_of fun (g : ℝ) => g ∈ G ∧ 0 < g) a) : dense ↑G := sorry /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ theorem real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense ↑G ∨ ∃ (a : ℝ), G = add_subgroup.closure (singleton a) := sorry end Mathlib
9983ea9f2044e36b19597cc98365b94baaef6eb3
618003631150032a5676f229d13a079ac875ff77
/test/lint_simp_comm.lean
34bc4e88b8b516b299b5cb86178ae541899900a1
[ "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
1,075
lean
import tactic.lint import algebra.group.basic /-! ## Commutativity lemmas should be rejected -/ attribute [simp] add_comm add_left_comm open tactic #eval do decl ← get_decl ``add_comm, res ← linter.simp_comm.test decl, -- linter complains guard res.is_some open tactic #eval do decl ← get_decl ``add_left_comm, res ← linter.simp_comm.test decl, -- linter complains guard res.is_some /-! ## Floris' trick should be accepted -/ @[simp] lemma list.filter_congr_decidable {α} (s : list α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @list.filter α p h s = s.filter p := by congr -- lemma is unproblematic example : @list.filter _ (λ x, x > 0) (λ _, classical.prop_decidable _) [1,2,3] = [1,2,3] := begin -- can rewrite once simp only [list.filter_congr_decidable], -- but not twice success_if_fail { simp only [list.filter_congr_decidable] }, refl end open tactic set_option pp.all true #eval do decl ← get_decl ``list.filter_congr_decidable, res ← linter.simp_comm.test decl, -- linter does not complain guard res.is_none
930bcbf02b2aca36e2c9de44bcc9709672c0017a
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/Syntax.lean
86c50d586b368b629e8d8f6f9b3c4409ae3d062c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
18,307
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.Elab.Command import Lean.Parser.Syntax import Lean.Elab.Util namespace Lean.Elab.Term /-- Expand `optional «precedence»` where «precedence» := leading_parser " : " >> precedenceParser -/ def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) := if stx.isNone then return none else return some (← evalPrec stx[0][1]) private def mkParserSeq (ds : Array (Term × Nat)) : TermElabM (Term × Nat) := do if ds.size == 0 then throwUnsupportedSyntax else if ds.size == 1 then pure ds[0]! else let mut (r, stackSum) := ds[0]! for (d, stackSz) in ds[1:ds.size] do r ← `(ParserDescr.binary `andthen $r $d) stackSum := stackSum + stackSz return (r, stackSum) structure ToParserDescrContext where catName : Name first : Bool leftRec : Bool -- true iff left recursion is allowed /-- See comment at `Parser.ParserCategory`. -/ behavior : Parser.LeadingIdentBehavior abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM) abbrev ToParserDescr := ToParserDescrM (Term × Nat) private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec) @[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with first := false }) x def ensureUnaryOutput (x : Term × Nat) : Term := let (stx, stackSz) := x if stackSz != 1 then Unhygienic.run ``(ParserDescr.unary $(quote `group) $stx) else stx @[inline] private def withNestedParser (x : ToParserDescr) : ToParserDescr := do withReader (fun ctx => { ctx with leftRec := false, first := false }) x /-- (Try to) add a term info for the category `catName` at `ref`. -/ def addCategoryInfo (ref : Syntax) (catName : Name) : TermElabM Unit := do let declName := ``Lean.Parser.Category ++ catName if (← getEnv).contains declName then addTermInfo' ref (Lean.mkConst declName) /-- (Try to) add a term info for the alias with info `info` at `ref`. -/ def addAliasInfo (ref : Syntax) (info : Parser.ParserAliasInfo) : TermElabM Unit := do if (← getInfoState).enabled then if (← getEnv).contains info.declName then addTermInfo' ref (Lean.mkConst info.declName) def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do let ctx ← read unless ctx.first && stx.getKind == ``Lean.Parser.Syntax.cat do return false let cat := stx[0].getId.eraseMacroScopes unless cat == ctx.catName do return false addCategoryInfo stx cat let prec? ← liftMacroM <| expandOptPrecedence stx[1] unless ctx.leftRec do throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion" markAsTrailingParser (prec?.getD 0) return true /-- Resolve the given parser name and return a list of candidates. Each candidate is a pair `(resolvedParserName, isDescr)`. `isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/ def resolveParserName [Monad m] [MonadInfoTree m] [MonadResolveName m] [MonadEnv m] [MonadError m] (parserName : Syntax) : m (List (Name × Bool)) := do try let candidates ← resolveGlobalConstWithInfos parserName /- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name, and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/ let env ← getEnv return candidates.filterMap fun c => match env.find? c with | none => none | some info => match info.type with | Expr.const ``Lean.Parser.TrailingParser _ => (c, false) | Expr.const ``Lean.Parser.Parser _ => (c, false) | Expr.const ``Lean.ParserDescr _ => (c, true) | Expr.const ``Lean.TrailingParserDescr _ => (c, true) | _ => none catch _ => return [] open TSyntax.Compat in /-- Given a `stx` of category `syntax`, return a `(newStx, lhsPrec?)`, where `newStx` is of category `term`. After elaboration, `newStx` should have type `TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/ partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Term × Option Nat) := do let env ← getEnv let behavior := Parser.leadingIdentBehavior env catName let ((newStx, _), lhsPrec?) ← (process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none return (newStx, lhsPrec?) where process (stx : Syntax) : ToParserDescr := withRef stx do let kind := stx.getKind if kind == nullKind then processSeq stx else if kind == choiceKind then process stx[0] else if kind == ``Lean.Parser.Syntax.paren then process stx[1] else if kind == ``Lean.Parser.Syntax.cat then processNullaryOrCat stx else if kind == ``Lean.Parser.Syntax.unary then processAlias stx[0] #[stx[2]] else if kind == ``Lean.Parser.Syntax.binary then processAlias stx[0] #[stx[2], stx[4]] else if kind == ``Lean.Parser.Syntax.sepBy then processSepBy stx else if kind == ``Lean.Parser.Syntax.sepBy1 then processSepBy1 stx else if kind == ``Lean.Parser.Syntax.atom then processAtom stx else if kind == ``Lean.Parser.Syntax.nonReserved then processNonReserved stx else let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _) match stxNew? with | some stxNew => process stxNew | none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}" /-- Sequence (aka NullNode) -/ processSeq (stx : Syntax) := do let args := stx.getArgs if (← checkLeftRec stx[0]) then if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax" let args := args.eraseIdx 0 let args ← args.mapM fun arg => withNestedParser do process arg mkParserSeq args else let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg mkParserSeq args ensureNoPrec (stx : Syntax) := unless stx[1].isNone do throwErrorAt stx[1] "unexpected precedence" processParserCategory (stx : Syntax) := do let catName := stx[0].getId.eraseMacroScopes if (← read).first && catName == (← read).catName then throwErrorAt stx "invalid atomic left recursive syntax" let prec? ← liftMacroM <| expandOptPrecedence stx[1] let prec := prec?.getD 0 addCategoryInfo stx catName return (← `(ParserDescr.cat $(quote catName) $(quote prec)), 1) processAlias (id : Syntax) (args : Array Syntax) := do let aliasName := id.getId.eraseMacroScopes let info ← Parser.getParserAliasInfo aliasName addAliasInfo id info let args ← args.mapM (withNestedParser ∘ process) let (args, stackSz) := if let some stackSz := info.stackSz? then if !info.autoGroupArgs then (args.map (·.1), stackSz) else (args.map ensureUnaryOutput, stackSz) else let (args, stackSzs) := args.unzip (args, stackSzs.foldl (· + ·) 0) let stx ← match args with | #[] => Parser.ensureConstantParserAlias aliasName; ``(ParserDescr.const $(quote aliasName)) | #[p1] => Parser.ensureUnaryParserAlias aliasName; ``(ParserDescr.unary $(quote aliasName) $p1) | #[p1, p2] => Parser.ensureBinaryParserAlias aliasName; ``(ParserDescr.binary $(quote aliasName) $p1 $p2) | _ => unreachable! return (stx, stackSz) processNullaryOrCat (stx : Syntax) := do match (← resolveParserName stx[0]) with | [(c, true)] => ensureNoPrec stx -- `syntax _ :=` at least enforces this let stackSz := 1 return (mkIdentFrom stx c, stackSz) | [(c, false)] => ensureNoPrec stx -- as usual, we assume that people using `Parser` know what they are doing let stackSz := 1 return (← `(ParserDescr.parser $(quote c)), stackSz) | cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}" | [] => let id := stx[0].getId.eraseMacroScopes if Parser.isParserCategory (← getEnv) id then processParserCategory stx else if (← Parser.isParserAlias id) then ensureNoPrec stx processAlias stx[0] #[] else throwError "unknown parser declaration/category/alias '{id}'" processSepBy (stx : Syntax) := do let p ← ensureUnaryOutput <$> withNestedParser do process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else ensureUnaryOutput <$> withNestedParser do process stx[4][1] let allowTrailingSep := !stx[5].isNone return (← `((with_annotate_term $(stx[0]) @ParserDescr.sepBy) $p $sep $psep $(quote allowTrailingSep)), 1) processSepBy1 (stx : Syntax) := do let p ← ensureUnaryOutput <$> withNestedParser do process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else ensureUnaryOutput <$> withNestedParser do process stx[4][1] let allowTrailingSep := !stx[5].isNone return (← `((with_annotate_term $(stx[0]) @ParserDescr.sepBy1) $p $sep $psep $(quote allowTrailingSep)), 1) isValidAtom (s : String) : Bool := !s.isEmpty && s.front != '\'' && s.front != '\"' && !(s.front == '`' && (s.endPos == ⟨1⟩ || isIdFirst (s.get ⟨1⟩) || isIdBeginEscape (s.get ⟨1⟩))) && !s.front.isDigit processAtom (stx : Syntax) := do match stx[0].isStrLit? with | some atom => unless isValidAtom atom do throwErrorAt stx "invalid atom" /- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark the first symbol as nonReserved. -/ if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then return (← `(ParserDescr.nonReservedSymbol $(quote atom) false), 1) else return (← `(ParserDescr.symbol $(quote atom)), 1) | none => throwUnsupportedSyntax processNonReserved (stx : Syntax) := do let some atom := stx[1].isStrLit? | throwUnsupportedSyntax return (← `((with_annotate_term $(stx[0]) @ParserDescr.nonReservedSymbol) $(quote atom) false), 1) end Term namespace Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do if let .str _ suffix := catName then let quotSymbol := "`(" ++ suffix ++ "|" let name := catName ++ `quot let cmd ← `( @[termParser] def $(mkIdent name) : Lean.ParserDescr := Lean.ParserDescr.node `Lean.Parser.Term.quot $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.node $(quote name) $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol)) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.cat $(quote catName) 0) (Lean.ParserDescr.symbol ")"))))) elabCommand cmd @[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do let docString? := stx[0].getOptional?.map fun stx => ⟨stx⟩ let catName := stx[2].getId let catBehavior := if stx[3].isNone then Parser.LeadingIdentBehavior.default else if stx[3][3].getKind == ``Parser.Command.catBehaviorBoth then Parser.LeadingIdentBehavior.both else Parser.LeadingIdentBehavior.symbol let attrName := catName.appendAfter "Parser" let catDeclName := ``Lean.Parser.Category ++ catName setEnv (← Parser.registerParserCategory (← getEnv) attrName catName catBehavior catDeclName) let cmd ← `($[$docString?]? def $(mkIdentFrom stx[2] (`_root_ ++ catDeclName) (canonical := true)) : Lean.Parser.Category := {}) declareSyntaxCatQuotParser catName elabCommand cmd /-- Auxiliary function for creating declaration names from parser descriptions. Example: Given ``` syntax term "+" term : term syntax "[" sepBy(term, ", ") "]" : term ``` It generates the names `term_+_` and `term[_,]` -/ partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : MacroM Name := do mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx "" where visit (stx : Syntax) (acc : String) : String := match stx.isStrLit? with | some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize | none => match stx with | Syntax.node _ k args => if k == ``Lean.Parser.Syntax.cat then acc ++ "_" else args.foldl (init := acc) fun acc arg => visit arg acc | Syntax.ident .. => acc | Syntax.atom .. => acc | Syntax.missing => acc appendCatName (str : String) := match catName with | .str _ s => s ++ str | _ => str /-- We assume a new syntax can be treated as an atom when it starts and ends with a token. Here are examples of atom-like syntax. ``` syntax "(" term ")" : term syntax "[" (sepBy term ",") "]" : term syntax "foo" : term ``` -/ private partial def isAtomLikeSyntax (stx : Syntax) : Bool := let kind := stx.getKind if kind == nullKind then isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1] else if kind == choiceKind then isAtomLikeSyntax stx[0] -- see toParserDescr else if kind == ``Lean.Parser.Syntax.paren then isAtomLikeSyntax stx[1] else kind == ``Lean.Parser.Syntax.atom def resolveSyntaxKind (k : Name) : CommandElabM Name := do checkSyntaxNodeKindAtNamespaces k (← getCurrNamespace) <|> throwError "invalid syntax node kind '{k}'" @[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do let `($[$doc?:docComment]? $[ @[ $attrInstances:attrInstance,* ] ]? $attrKind:attrKind syntax%$tk $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) := stx | throwUnsupportedSyntax let cat := catStx.getId.eraseMacroScopes unless (Parser.isParserCategory (← getEnv) cat) do throwErrorAt catStx "unknown category '{cat}'" liftTermElabM <| Term.addCategoryInfo catStx cat let syntaxParser := mkNullNode ps -- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise. let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec let prec ← match prec? with | some prec => liftMacroM <| evalPrec prec | none => pure precDefault let name ← match name? with | some name => pure name.getId | none => liftMacroM <| mkNameFromParserSyntax cat syntaxParser let prio ← liftMacroM <| evalOptPrio prio? let idRef := (name?.map (·.raw)).getD tk let stxNodeKind := (← getCurrNamespace) ++ name let catParserId := mkIdentFrom idRef (cat.appendAfter "Parser") let (val, lhsPrec?) ← runTermElabM fun _ => Term.toParserDescr syntaxParser cat let declName := name?.getD (mkIdentFrom idRef name (canonical := true)) let attrInstance ← `(attrInstance| $attrKind:attrKind $catParserId:ident $(quote prio):num) let attrInstances := attrInstances.getD { elemsAndSeps := #[] } let attrInstances := attrInstances.push attrInstance let d ← if let some lhsPrec := lhsPrec? then `($[$doc?:docComment]? @[$attrInstances,*] def $declName:ident : Lean.TrailingParserDescr := ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val) else `($[$doc?:docComment]? @[$attrInstances,*] def $declName:ident : Lean.ParserDescr := ParserDescr.node $(quote stxNodeKind) $(quote prec) $val) trace `Elab fun _ => d withMacroExpansion stx d <| elabCommand d @[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do let `($[$doc?:docComment]? syntax $declName:ident := $[$ps:stx]*) ← pure stx | throwUnsupportedSyntax -- TODO: nonatomic names let (val, _) ← runTermElabM fun _ => Term.toParserDescr (mkNullNode ps) Name.anonymous let stxNodeKind := (← getCurrNamespace) ++ declName.getId let stx' ← `($[$doc?:docComment]? def $declName:ident : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val) withMacroExpansion stx stx' <| elabCommand stx' def checkRuleKind (given expected : SyntaxNodeKind) : Bool := given == expected || given == expected ++ `antiquot def inferMacroRulesAltKind : TSyntax ``matchAlt → CommandElabM SyntaxNodeKind | `(matchAltExpr| | $pat:term => $_) => do if !pat.raw.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat pure quoted.getKind | _ => throwUnsupportedSyntax /-- Infer syntax kind `k` from first pattern, put alternatives of same kind into new `macro/elab_rules (kind := k)` via `mkCmd (some k)`, leave remaining alternatives (via `mkCmd none`) to be recursively expanded. -/ def expandNoKindMacroRulesAux (alts : Array (TSyntax ``matchAlt)) (cmdName : String) (mkCmd : Option Name → Array (TSyntax ``matchAlt) → CommandElabM Command) : CommandElabM Command := do let mut k ← inferMacroRulesAltKind alts[0]! if k.isStr && k.getString! == "antiquot" then k := k.getPrefix if k == choiceKind then throwErrorAt alts[0]! "invalid {cmdName} alternative, multiple interpretations for pattern (solution: specify node kind using `{cmdName} (kind := ...) ...`)" else let altsK ← alts.filterM fun alt => return checkRuleKind (← inferMacroRulesAltKind alt) k let altsNotK ← alts.filterM fun alt => return !checkRuleKind (← inferMacroRulesAltKind alt) k if altsNotK.isEmpty then mkCmd k altsK else `($(← mkCmd k altsK):command $(← mkCmd none altsNotK)) def strLitToPattern (stx: Syntax) : MacroM Syntax := match stx.isStrLit? with | some str => return mkAtomFrom stx str | none => Macro.throwUnsupported builtin_initialize registerTraceClass `Elab.syntax end Lean.Elab.Command
95ed37fc041abe5480e5028f805b30e71e627a1c
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/tactic/rewrite.lean
1059f2ca59794a1eac6c90b3b4310e854a8c255c
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
7,414
lean
import data.dlist import meta.expr namespace tactic open expr list meta def match_fn (fn : expr) : expr → tactic (expr × expr) | (app (app fn' e₀) e₁) := (e₀,e₁) <$ unify fn fn' | _ := failed meta def fill_args : expr → tactic (expr × list expr) | (pi n bi d b) := do v ← mk_meta_var d, (r,vs) ← fill_args (b.instantiate_var v), return (r,v::vs) | e := return (e,[]) meta def mk_assoc_pattern' (fn : expr) : expr → tactic (dlist expr) | e := (do (e₀,e₁) ← match_fn fn e, (++) <$> mk_assoc_pattern' e₀ <*> mk_assoc_pattern' e₁) <|> pure (dlist.singleton e) meta def mk_assoc_pattern (fn e : expr) : tactic (list expr) := dlist.to_list <$> mk_assoc_pattern' fn e meta def mk_assoc (fn : expr) : list expr → tactic expr | [] := failed | [x] := pure x | (x₀ :: x₁ :: xs) := mk_assoc (fn x₀ x₁ :: xs) meta def chain_eq_trans : list expr → tactic expr | [] := to_expr ``(rfl) | [e] := pure e | (e :: es) := chain_eq_trans es >>= mk_eq_trans e meta def unify_prefix : list expr → list expr → tactic unit | [] _ := pure () | _ [] := failed | (x :: xs) (y :: ys) := unify x y >> unify_prefix xs ys meta def match_assoc_pattern' (p : list expr) : list expr → tactic (list expr × list expr) | es := ([],es.drop p.length) <$ unify_prefix p es <|> match es with | [] := failed | (x :: xs) := prod.map (cons x) id <$> match_assoc_pattern' xs end meta def match_assoc_pattern (fn p e : expr) : tactic (list expr × list expr) := do p' ← mk_assoc_pattern fn p, e' ← mk_assoc_pattern fn e, match_assoc_pattern' p' e' meta def mk_eq_proof (fn : expr) (e₀ e₁ : list expr) (p : expr) : tactic (expr × expr × expr) := do (l,r) ← infer_type p >>= match_eq, if e₀.empty ∧ e₁.empty then pure (l,r,p) else do l' ← mk_assoc fn (e₀ ++ [l] ++ e₁), r' ← mk_assoc fn (e₀ ++ [r] ++ e₁), t ← infer_type l', v ← mk_local_def `x t, e ← mk_assoc fn (e₀ ++ [v] ++ e₁), p ← mk_congr_arg (e.lambdas [v]) p, p' ← mk_id_eq l' r' p, return (l',r',p') meta def assoc_root (fn assoc : expr) : expr → tactic (expr × expr) | e := (do (e₀,e₁) ← match_fn fn e, (ea,eb) ← match_fn fn e₁, let e' := fn (fn e₀ ea) eb, p' ← mk_eq_symm (assoc e₀ ea eb), (e'',p'') ← assoc_root e', prod.mk e'' <$> mk_eq_trans p' p'' ) <|> prod.mk e <$> mk_eq_refl e meta def assoc_refl' (fn assoc : expr) : expr → expr → tactic expr | l r := (is_def_eq l r >> mk_eq_refl l) <|> (do (l',l_p) ← assoc_root fn assoc l <|> fail "A", (el₀,el₁) ← match_fn fn l' <|> fail "B", (r',r_p) ← assoc_root fn assoc r <|> fail "C", (er₀,er₁) ← match_fn fn r' <|> fail "D", p₀ ← assoc_refl' el₀ er₀, p₁ ← is_def_eq el₁ er₁ >> mk_eq_refl el₁, f_eq ← mk_congr_arg fn p₀ <|> fail "G", p' ← mk_congr f_eq p₁ <|> fail "H", r_p' ← mk_eq_symm r_p, chain_eq_trans [l_p,p',r_p'] ) meta def assoc_refl (fn : expr) : tactic unit := do (l,r) ← target >>= match_eq, assoc ← mk_mapp ``is_associative.assoc [none,fn,none] <|> fail format!"{fn} is not associative", assoc_refl' fn assoc l r >>= tactic.exact meta def flatten (fn assoc e : expr) : tactic (expr × expr) := do ls ← mk_assoc_pattern fn e, e' ← mk_assoc fn ls, p ← assoc_refl' fn assoc e e', return (e',p) meta def assoc_rewrite_intl (assoc h e : expr) : tactic (expr × expr) := do t ← infer_type h, (lhs,rhs) ← match_eq t, let fn := lhs.app_fn.app_fn, (l,r) ← match_assoc_pattern fn lhs e, (lhs',rhs',h') ← mk_eq_proof fn l r h, e_p ← assoc_refl' fn assoc e lhs', (rhs'',rhs_p) ← flatten fn assoc rhs', final_p ← chain_eq_trans [e_p,h',rhs_p], return (rhs'', final_p) meta def expr.mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (expr.traverse (λ e', get >>= (monad_lift ∘ flip f e') >>= put >> pure e') e) x : m _) -- TODO(Simon): visit expressions built of `fn` nested inside other such expressions: -- e.g.: x + f (a + b + c) + y should generate two rewrite candidates meta def enum_assoc_subexpr' (fn : expr) : expr → tactic (dlist expr) | e := dlist.singleton e <$ (match_fn fn e >> guard (¬ e.has_var)) <|> expr.mfoldl (λ es e', (++ es) <$> enum_assoc_subexpr' e') dlist.empty e meta def enum_assoc_subexpr (fn e : expr) : tactic (list expr) := dlist.to_list <$> enum_assoc_subexpr' fn e meta def mk_assoc_instance (fn : expr) : tactic expr := do t ← mk_mapp ``is_associative [none,fn], inst ← prod.snd <$> solve_aux t assumption <|> (mk_instance t >>= assertv `_inst t) <|> fail format!"{fn} is not associative", mk_mapp ``is_associative.assoc [none,fn,inst] meta def assoc_rewrite (h e : expr) (opt_assoc : option expr := none) : tactic (expr × expr × list expr) := do (t,vs) ← infer_type h >>= fill_args, (lhs,rhs) ← match_eq t, let fn := lhs.app_fn.app_fn, es ← enum_assoc_subexpr fn e, assoc ← match opt_assoc with | none := mk_assoc_instance fn | (some assoc) := pure assoc end, (_,p) ← mfirst (assoc_rewrite_intl assoc $ h.mk_app vs) es, (e',p',_) ← tactic.rewrite p e, pure (e',p',vs) meta def assoc_rewrite_target (h : expr) (opt_assoc : option expr := none) : tactic unit := do tgt ← target, (tgt',p,_) ← assoc_rewrite h tgt opt_assoc, replace_target tgt' p meta def assoc_rewrite_hyp (h hyp : expr) (opt_assoc : option expr := none) : tactic expr := do tgt ← infer_type hyp, (tgt',p,_) ← assoc_rewrite h tgt opt_assoc, replace_hyp hyp tgt' p namespace interactive open lean.parser interactive interactive.types tactic private meta def assoc_rw_goal (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, assoc_rewrite_target e) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_target e) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def assoc_rw_hyp : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs) (eq_lemmas.empty) private meta def assoc_rw_core (rs : parse rw_rules) (loca : parse location) : tactic unit := match loca with | loc.wildcard := loca.try_apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules) | _ := loca.apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules) end >> try (reflexivity) >> (returnopt rs.end_pos >>= save_info <|> skip) /-- `assoc_rewrite [h₀,← h₁] at ⊢ h₂` behaves like `rewrite [h₀,← h₁] at ⊢ h₂` with the exception that associativity is used implicitly to make rewriting possible. -/ meta def assoc_rewrite (q : parse rw_rules) (l : parse location) : tactic unit := propagate_tags (assoc_rw_core q l) /-- synonym for `assoc_rewrite` -/ meta def assoc_rw (q : parse rw_rules) (l : parse location) : tactic unit := assoc_rewrite q l end interactive end tactic
e91d70656d38ab4e6a5723914c7119edd4caac0c
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/InferType.lean
83c401fafe999fdbed3510e31c7bb49cf0251433
[ "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
16,816
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LBool import Lean.Meta.Basic namespace Lean /-- Auxiliary function for instantiating the loose bound variables in `e` with `args[start:stop]`. This function is similar to `instantiateRevRange`, but it applies beta-reduction when we instantiate a bound variable with a lambda expression. Example: Given the term `#0 a`, and `start := 0, stop := 1, args := #[fun x => x]` the result is `a` instead of `(fun x => x) a`. This reduction is useful when we are inferring the type of eliminator-like applications. For example, given `(n m : Nat) (f : Nat → Nat) (h : m = n)`, the type of `Eq.subst (motive := fun x => f m = f x) h rfl` is `motive n` which is `(fun (x : Nat) => f m = f x) n` This function reduces the new application to `f m = f n` We use it to implement `inferAppType` -/ partial def Expr.instantiateBetaRevRange (e : Expr) (start : Nat) (stop : Nat) (args : Array Expr) : Expr := if e.hasLooseBVars && stop > start then assert! stop ≤ args.size visit e 0 |>.run else e where visit (e : Expr) (offset : Nat) : MonadStateCacheT (ExprStructEq × Nat) Expr Id Expr := if offset >= e.looseBVarRange then -- `e` doesn't have free variables return e else checkCache ({ val := e : ExprStructEq }, offset) fun _ => do match e with | .forallE _ d b _ => return e.updateForallE! (← visit d offset) (← visit b (offset+1)) | .lam _ d b _ => return e.updateLambdaE! (← visit d offset) (← visit b (offset+1)) | .letE _ t v b _ => return e.updateLet! (← visit t offset) (← visit v offset) (← visit b (offset+1)) | .mdata _ b => return e.updateMData! (← visit b offset) | .proj _ _ b => return e.updateProj! (← visit b offset) | .app .. => e.withAppRev fun f revArgs => do let fNew ← visit f offset let revArgs ← revArgs.mapM (visit · offset) if f.isBVar then -- try to beta reduce if `f` was a bound variable return fNew.betaRev revArgs else return mkAppRev fNew revArgs | Expr.bvar vidx => -- Recall that looseBVarRange for `Expr.bvar` is `vidx+1`. -- So, we must have offset ≤ vidx, since we are in the "else" branch of `if offset >= e.looseBVarRange` let n := stop - start if vidx < offset + n then return args[stop - (vidx - offset) - 1]!.liftLooseBVars 0 offset else return mkBVar (vidx - n) -- The following cases are unreachable because they never contain loose bound variables | .const .. => unreachable! | .fvar .. => unreachable! | .mvar .. => unreachable! | .sort .. => unreachable! | .lit .. => unreachable! namespace Meta def throwFunctionExpected {α} (f : Expr) : MetaM α := throwError "function expected{indentExpr f}" private def inferAppType (f : Expr) (args : Array Expr) : MetaM Expr := do let mut fType ← inferType f let mut j := 0 /- TODO: check whether `instantiateBetaRevRange` is too expensive, and use it only when `args` contains a lambda expression. -/ for i in [:args.size] do match fType with | Expr.forallE _ _ b _ => fType := b | _ => match (← whnf <| fType.instantiateBetaRevRange j i args) with | Expr.forallE _ _ b _ => j := i; fType := b | _ => throwFunctionExpected <| mkAppRange f 0 (i+1) args return fType.instantiateBetaRevRange j args.size args def throwIncorrectNumberOfLevels {α} (constName : Name) (us : List Level) : MetaM α := throwError "incorrect number of universe levels {mkConst constName us}" private def inferConstType (c : Name) (us : List Level) : MetaM Expr := do let cinfo ← getConstInfo c if cinfo.levelParams.length == us.length then instantiateTypeLevelParams cinfo us else throwIncorrectNumberOfLevels c us private def inferProjType (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do let failed {α} : Unit → MetaM α := fun _ => throwError "invalid projection{indentExpr (mkProj structName idx e)}" let structType ← inferType e let structType ← whnf structType matchConstStruct structType.getAppFn failed fun structVal structLvls ctorVal => let n := structVal.numParams let structParams := structType.getAppArgs if n != structParams.size then failed () else do let mut ctorType ← inferAppType (mkConst ctorVal.name structLvls) structParams for i in [:idx] do ctorType ← whnf ctorType match ctorType with | Expr.forallE _ _ body _ => if body.hasLooseBVars then ctorType := body.instantiate1 <| mkProj structName i e else ctorType := body | _ => failed () ctorType ← whnf ctorType match ctorType with | Expr.forallE _ d _ _ => return d.consumeTypeAnnotations | _ => failed () def throwTypeExcepted {α} (type : Expr) : MetaM α := throwError "type expected{indentExpr type}" def getLevel (type : Expr) : MetaM Level := do let typeType ← inferType type let typeType ← whnfD typeType match typeType with | Expr.sort lvl => return lvl | Expr.mvar mvarId => if (← mvarId.isReadOnlyOrSyntheticOpaque) then throwTypeExcepted type else let lvl ← mkFreshLevelMVar mvarId.assign (mkSort lvl) return lvl | _ => throwTypeExcepted type private def inferForallType (e : Expr) : MetaM Expr := forallTelescope e fun xs e => do let lvl ← getLevel e let lvl ← xs.foldrM (init := lvl) fun x lvl => do let xType ← inferType x let xTypeLvl ← getLevel xType return mkLevelIMax' xTypeLvl lvl return mkSort lvl.normalize /-- Infer type of lambda and let expressions -/ private def inferLambdaType (e : Expr) : MetaM Expr := lambdaLetTelescope e fun xs e => do let type ← inferType e mkForallFVars xs type @[inline] private def withLocalDecl' {α} (name : Name) (bi : BinderInfo) (type : Expr) (x : Expr → MetaM α) : MetaM α := savingCache do let fvarId ← mkFreshFVarId withReader (fun ctx => { ctx with lctx := ctx.lctx.mkLocalDecl fvarId name type bi }) do x (mkFVar fvarId) def throwUnknownMVar {α} (mvarId : MVarId) : MetaM α := throwError "unknown metavariable '?{mvarId.name}'" private def inferMVarType (mvarId : MVarId) : MetaM Expr := do match (← getMCtx).findDecl? mvarId with | some d => return d.type | none => throwUnknownMVar mvarId private def inferFVarType (fvarId : FVarId) : MetaM Expr := do match (← getLCtx).find? fvarId with | some d => return d.type | none => fvarId.throwUnknown @[inline] private def checkInferTypeCache (e : Expr) (inferType : MetaM Expr) : MetaM Expr := do match (← get).cache.inferType.find? e with | some type => return type | none => let type ← inferType unless e.hasMVar || type.hasMVar do modifyInferTypeCache fun c => c.insert e type return type @[export lean_infer_type] def inferTypeImp (e : Expr) : MetaM Expr := let rec infer (e : Expr) : MetaM Expr := do match e with | .const c [] => inferConstType c [] | .const c us => checkInferTypeCache e (inferConstType c us) | .proj n i s => checkInferTypeCache e (inferProjType n i s) | .app f .. => checkInferTypeCache e (inferAppType f.getAppFn e.getAppArgs) | .mvar mvarId => inferMVarType mvarId | .fvar fvarId => inferFVarType fvarId | .bvar bidx => throwError "unexpected bound variable {mkBVar bidx}" | .mdata _ e => infer e | .lit v => return v.type | .sort lvl => return mkSort (mkLevelSucc lvl) | .forallE .. => checkInferTypeCache e (inferForallType e) | .lam .. => checkInferTypeCache e (inferLambdaType e) | .letE .. => checkInferTypeCache e (inferLambdaType e) withIncRecDepth <| withTransparency TransparencyMode.default (infer e) /-- Return `LBool.true` if given level is always equivalent to universe level zero. It is used to implement `isProp`. -/ private def isAlwaysZero : Level → Bool | .zero .. => true | .mvar .. => false | .param .. => false | .succ .. => false | .max u v => isAlwaysZero u && isAlwaysZero v | .imax _ u => isAlwaysZero u /-- `isArrowProp type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Prop`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProp : Expr → Nat → MetaM LBool | .sort u, 0 => return isAlwaysZero (← instantiateLevelMVars u) |>.toLBool | .forallE .., 0 => return LBool.false | .forallE _ _ b _, n+1 => isArrowProp b n | .letE _ _ _ b _, n => isArrowProp b n | .mdata _ e, n => isArrowProp e n | _, _ => return LBool.undef /-- `isPropQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proposition. -/ private partial def isPropQuickApp : Expr → Nat → MetaM LBool | .const c lvls, arity => do let constType ← inferConstType c lvls; isArrowProp constType arity | .fvar fvarId, arity => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType arity | .mvar mvarId, arity => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType arity | .app f .., arity => isPropQuickApp f (arity+1) | .mdata _ e, arity => isPropQuickApp e arity | .letE _ _ _ b _, arity => isPropQuickApp b arity | .lam .., 0 => return LBool.false | .lam _ _ b _, arity+1 => isPropQuickApp b arity | _, _ => return LBool.undef /-- `isPropQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proposition. -/ partial def isPropQuick : Expr → MetaM LBool | .bvar .. => return LBool.undef | .lit .. => return LBool.false | .sort .. => return LBool.false | .lam .. => return LBool.false | .letE _ _ _ b _ => isPropQuick b | .proj .. => return LBool.undef | .forallE _ _ b _ => isPropQuick b | .mdata _ e => isPropQuick e | .const c lvls => do let constType ← inferConstType c lvls; isArrowProp constType 0 | .fvar fvarId => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType 0 | .mvar mvarId => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType 0 | .app f .. => isPropQuickApp f 1 /-- `isProp whnf e` return `true` if `e` is a proposition. If `e` contains metavariables, it may not be possible to decide whether is a proposition or not. We return `false` in this case. We considered using `LBool` and retuning `LBool.undef`, but we have no applications for it. -/ def isProp (e : Expr) : MetaM Bool := do match (← isPropQuick e) with | .true => return true | .false => return false | .undef => let type ← inferType e let type ← whnfD type match type with | Expr.sort u => return isAlwaysZero (← instantiateLevelMVars u) | _ => return false /-- `isArrowProposition type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> B`, where `B` is a proposition. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProposition : Expr → Nat → MetaM LBool | .forallE _ _ b _, n+1 => isArrowProposition b n | .letE _ _ _ b _, n => isArrowProposition b n | .mdata _ e, n => isArrowProposition e n | type, 0 => isPropQuick type | _, _ => return LBool.undef mutual /-- `isProofQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proof. -/ private partial def isProofQuickApp : Expr → Nat → MetaM LBool | .const c lvls, arity => do let constType ← inferConstType c lvls; isArrowProposition constType arity | .fvar fvarId, arity => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType arity | .mvar mvarId, arity => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType arity | .app f _, arity => isProofQuickApp f (arity+1) | .mdata _ e, arity => isProofQuickApp e arity | .letE _ _ _ b _, arity => isProofQuickApp b arity | .lam _ _ b _, 0 => isProofQuick b | .lam _ _ b _, arity+1 => isProofQuickApp b arity | _, _ => return LBool.undef /-- `isProofQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proof. -/ partial def isProofQuick : Expr → MetaM LBool | .bvar .. => return LBool.undef | .lit .. => return LBool.false | .sort .. => return LBool.false | .lam _ _ b _ => isProofQuick b | .letE _ _ _ b _ => isProofQuick b | .proj .. => return LBool.undef | .forallE .. => return LBool.false | .mdata _ e => isProofQuick e | .const c lvls => do let constType ← inferConstType c lvls; isArrowProposition constType 0 | .fvar fvarId => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType 0 | .mvar mvarId => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType 0 | .app f .. => isProofQuickApp f 1 end def isProof (e : Expr) : MetaM Bool := do match (← isProofQuick e) with | .true => return true | .false => return false | .undef => Meta.isProp (← inferType e) /-- `isArrowType type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Sort _`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowType : Expr → Nat → MetaM LBool | .sort .., 0 => return LBool.true | .forallE .., 0 => return LBool.false | .forallE _ _ b _, n+1 => isArrowType b n | .letE _ _ _ b _, n => isArrowType b n | .mdata _ e, n => isArrowType e n | _, _ => return LBool.undef /-- `isTypeQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a type. -/ private partial def isTypeQuickApp : Expr → Nat → MetaM LBool | .const c lvls, arity => do let constType ← inferConstType c lvls; isArrowType constType arity | .fvar fvarId, arity => do let fvarType ← inferFVarType fvarId; isArrowType fvarType arity | .mvar mvarId, arity => do let mvarType ← inferMVarType mvarId; isArrowType mvarType arity | .app f _, arity => isTypeQuickApp f (arity+1) | .mdata _ e, arity => isTypeQuickApp e arity | .letE _ _ _ b _, arity => isTypeQuickApp b arity | .lam .., 0 => return LBool.false | .lam _ _ b _, arity+1 => isTypeQuickApp b arity | _, _ => return LBool.undef /-- `isTypeQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a type. -/ partial def isTypeQuick : Expr → MetaM LBool | .bvar .. => return LBool.undef | .lit .. => return LBool.false | .sort .. => return LBool.true | .lam .. => return LBool.false | .letE _ _ _ b _ => isTypeQuick b | .proj .. => return LBool.undef | .forallE .. => return LBool.true | .mdata _ e => isTypeQuick e | .const c lvls => do let constType ← inferConstType c lvls; isArrowType constType 0 | .fvar fvarId => do let fvarType ← inferFVarType fvarId; isArrowType fvarType 0 | .mvar mvarId => do let mvarType ← inferMVarType mvarId; isArrowType mvarType 0 | .app f .. => isTypeQuickApp f 1 /-- Return `true` iff the type of `e` is a `Sort _`. -/ def isType (e : Expr) : MetaM Bool := do match (← isTypeQuick e) with | .true => return true | .false => return false | .undef => let type ← inferType e let type ← whnfD type match type with | .sort .. => return true | _ => return false /-- Return true iff `type` is `Sort _` or `As → Sort _`. -/ partial def isTypeFormerType (type : Expr) : MetaM Bool := do let type ← whnfD type match type with | .sort .. => return true | .forallE n d b c => withLocalDecl' n c d fun fvar => isTypeFormerType (b.instantiate1 fvar) | _ => return false /-- Return true iff `e : Sort _` or `e : (forall As, Sort _)`. Remark: it subsumes `isType` -/ def isTypeFormer (e : Expr) : MetaM Bool := do isTypeFormerType (← inferType e) end Lean.Meta
256ab2cdb8edc91ff408958cca6aba64a19fd36d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/Tactic/Induction.lean
622f95d72c0475b93a7ede1421dce2d80a36a9a5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
27,662
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectFVars import Lean.AuxRecursor import Lean.Parser.Term import Lean.Meta.RecursorInfo import Lean.Meta.CollectMVars import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeVars import Lean.Elab.App import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Generalize namespace Lean.Elab.Tactic open Meta /- Given an `inductionAlt` of the form ``` syntax inductionAltLHS := "| " (group("@"? ident) <|> hole) (ident <|> hole)* syntax inductionAlt := ppDedent(ppLine) inductionAltLHS+ " => " (hole <|> syntheticHole <|> tacticSeq) ``` -/ private def getFirstAltLhs (alt : Syntax) : Syntax := alt[0][0] /-- Return `inductionAlt` name. It assumes `alt` does not have multiple `inductionAltLHS` -/ private def getAltName (alt : Syntax) : Name := let lhs := getFirstAltLhs alt if !lhs[1].isOfKind ``Parser.Term.hole then lhs[1][1].getId.eraseMacroScopes else `_ /-- Returns the `inductionAlt` `ident <|> hole` -/ private def getAltNameStx (alt : Syntax) : Syntax := let lhs := getFirstAltLhs alt if lhs[1].isOfKind ``Parser.Term.hole then lhs[1] else lhs[1][1] /-- Return `true` if the first LHS of the given alternative contains `@`. -/ private def altHasExplicitModifier (alt : Syntax) : Bool := let lhs := getFirstAltLhs alt !lhs[1].isOfKind ``Parser.Term.hole && !lhs[1][0].isNone /-- Return the variables in the first LHS of the given alternative. -/ private def getAltVars (alt : Syntax) : Array Syntax := let lhs := getFirstAltLhs alt lhs[2].getArgs private def getAltRHS (alt : Syntax) : Syntax := alt[2] private def getAltDArrow (alt : Syntax) : Syntax := alt[1] -- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic def isHoleRHS (rhs : Syntax) : Bool := rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole def evalAlt (mvarId : MVarId) (alt : Syntax) (addInfo : TermElabM Unit) (remainingGoals : Array MVarId) : TacticM (Array MVarId) := let rhs := getAltRHS alt withCaseRef (getAltDArrow alt) rhs do if isHoleRHS rhs then addInfo let gs' ← mvarId.withContext <| withRef rhs do let mvarDecl ← mvarId.getDecl let val ← elabTermEnsuringType rhs mvarDecl.type mvarId.assign val let gs' ← getMVarsNoDelayed val tagUntaggedGoals mvarDecl.userName `induction gs'.toList pure gs' return remainingGoals ++ gs' else setGoals [mvarId] closeUsingOrAdmit (withTacticInfoContext alt (addInfo *> evalTactic rhs)) return remainingGoals /-! Helper method for creating an user-defined eliminator/recursor application. -/ namespace ElimApp structure Alt where /-- The short name of the alternative, used in `| foo =>` cases -/ name : Name /-- A declaration corresponding to the inductive constructor. (For custom recursors, the alternatives correspond to parameter names in the recursor, so we may not have a declaration to point to.) This is used for go-to-definition on the alternative name. -/ declName? : Option Name /-- The subgoal metavariable for the alternative. -/ mvarId : MVarId deriving Inhabited structure Context where elimInfo : ElimInfo targets : Array Expr -- targets provided by the user structure State where argPos : Nat := 0 -- current argument position targetPos : Nat := 0 -- current target at targetsStx f : Expr fType : Expr alts : Array Alt := #[] insts : Array MVarId := #[] abbrev M := ReaderT Context $ StateRefT State TermElabM private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /-- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /-- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! private def getFType : M Expr := do let fType ← whnfForall (← get).fType modify fun s => { s with fType := fType } pure fType structure Result where elimApp : Expr alts : Array Alt := #[] others : Array MVarId := #[] /-- Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for the eliminator. For example, the indices of builtin recursors are considered implicit targets. Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets from the explicit ones. -/ partial def mkElimApp (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do let rec loop : M Unit := do match (← getFType) with | .forallE binderName _ _ c => let ctx ← read let argPos := (← get).argPos if ctx.elimInfo.motivePos == argPos then let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque addNewArg motive else if ctx.elimInfo.targetsPos.contains argPos then let s ← get let ctx ← read unless s.targetPos < ctx.targets.size do throwError "insufficient number of targets for '{elimInfo.name}'" let target := ctx.targets[s.targetPos]! let expectedType ← getArgExpectedType let target ← withAssignableSyntheticOpaque <| Term.ensureHasType expectedType target modify fun s => { s with targetPos := s.targetPos + 1 } addNewArg target else match c with | .implicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | .strictImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | .instImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName) modify fun s => { s with insts := s.insts.push arg.mvarId! } addNewArg arg | _ => let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName) let x ← getBindingName modify fun s => let declName? := elimInfo.altsInfo[s.alts.size]!.declName? { s with alts := s.alts.push ⟨x, declName?, arg.mvarId!⟩ } addNewArg arg loop | _ => pure () let f ← Term.mkConst elimInfo.name let fType ← inferType f let (_, s) ← (loop).run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType } let mut others := #[] for mvarId in s.insts do try unless (← Term.synthesizeInstMVarCore mvarId) do mvarId.setKind .syntheticOpaque others := others.push mvarId catch _ => mvarId.setKind .syntheticOpaque others := others.push mvarId let alts ← s.alts.filterM fun alt => return !(← alt.mvarId.isAssigned) return { elimApp := (← instantiateMVars s.f), alts, others := others } /-- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign `motiveArg := fun targets => C[targets]` -/ def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do let type ← inferType (mkMVar mvarId) let motive ← mkLambdaFVars (targets.map mkFVar) type let motiverInferredType ← inferType motive let motiveType ← inferType (mkMVar motiveArg) unless (← isDefEqGuarded motiverInferredType motiveType) do throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}" motiveArg.assign motive private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do for altInfo in elimInfo.altsInfo do if altInfo.name == altName then return altInfo.numFields throwError "unknown alternative name '{altName}'" private def checkAltNames (alts : Array Alt) (altsSyntax : Array Syntax) : TacticM Unit := for i in [:altsSyntax.size] do let altStx := altsSyntax[i]! if getAltName altStx == `_ && i != altsSyntax.size - 1 then withRef altStx <| throwError "invalid occurrence of wildcard alternative, it must be the last alternative" let altName := getAltName altStx if altName != `_ then unless alts.any (·.name == altName) do throwErrorAt altStx "invalid alternative name '{altName}'" /-- Given the goal `altMVarId` for a given alternative that introduces `numFields` new variables, return the number of explicit variables. Recall that when the `@` is not used, only the explicit variables can be named by the user. -/ private def getNumExplicitFields (altMVarId : MVarId) (numFields : Nat) : MetaM Nat := altMVarId.withContext do let target ← altMVarId.getType withoutModifyingState do let (_, bis, _) ← forallMetaBoundedTelescope target numFields return bis.foldl (init := 0) fun r bi => if bi.isExplicit then r + 1 else r private def saveAltVarsInfo (altMVarId : MVarId) (altStx : Syntax) (fvarIds : Array FVarId) : TermElabM Unit := withSaveInfoContext <| altMVarId.withContext do let useNamesForExplicitOnly := !altHasExplicitModifier altStx let mut i := 0 let altVars := getAltVars altStx for fvarId in fvarIds do if !useNamesForExplicitOnly || (← fvarId.getDecl).binderInfo.isExplicit then if i < altVars.size then Term.addLocalVarInfo altVars[i]! (mkFVar fvarId) i := i + 1 /-- If `altsSyntax` is not empty we reorder `alts` using the order the alternatives have been provided in `altsSyntax`. Motivations: 1- It improves the effectiveness of the `checkpoint` and `save` tactics. Consider the following example: ```lean example (h₁ : p ∨ q) (h₂ : p → x = 0) (h₃ : q → y = 0) : x * y = 0 := by cases h₁ with | inr h => sleep 5000 -- sleeps for 5 seconds save have : y = 0 := h₃ h -- We can confortably work here | inl h => stop ... ``` If we do reorder, the `inl` alternative will be executed first. Moreover, as we type in the `inr` alternative, type errors will "swallow" the `inl` alternative and affect the tactic state at `save` making it ineffective. 2- The errors are produced in the same order the appear in the code above. This is not super important when using IDEs. -/ def reorderAlts (alts : Array Alt) (altsSyntax : Array Syntax) : Array Alt := Id.run do if altsSyntax.isEmpty then return alts else let mut alts := alts let mut result := #[] for altStx in altsSyntax do let altName := getAltName altStx let some i := alts.findIdx? (·.1 == altName) | return result ++ alts result := result.push alts[i]! alts := alts.eraseIdx i return result ++ alts def evalAlts (elimInfo : ElimInfo) (alts : Array Alt) (optPreTac : Syntax) (altsSyntax : Array Syntax) (initialInfo : Info) (numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do checkAltNames alts altsSyntax let hasAlts := altsSyntax.size > 0 if hasAlts then -- default to initial state outside of alts -- HACK: because this node has the same span as the original tactic, -- we need to take all the info trees we have produced so far and re-nest them -- inside this node as well let treesSaved ← getResetInfoTrees withInfoContext ((modifyInfoState fun s => { s with trees := treesSaved }) *> go) (pure initialInfo) else go where go := do let alts := reorderAlts alts altsSyntax let hasAlts := altsSyntax.size > 0 let mut usedWildcard := false let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here let mut altsSyntax := altsSyntax for { name := altName, declName?, mvarId := altMVarId } in alts do let numFields ← getAltNumFields elimInfo altName let mut isWildcard := false let altStx? ← match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with | some idx => let altStx := altsSyntax[idx]! altsSyntax := altsSyntax.eraseIdx idx pure (some altStx) | none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with | some idx => isWildcard := true pure (some altsSyntax[idx]!) | none => pure none match altStx? with | none => let mut (_, altMVarId) ← altMVarId.introN numFields match (← Cases.unifyEqs? numEqs altMVarId {}) with | none => pure () -- alternative is not reachable | some (altMVarId', _) => (_, altMVarId) ← altMVarId'.introNP numGeneralized for fvarId in toClear do altMVarId ← altMVarId.tryClear fvarId let altMVarIds ← applyPreTac altMVarId if !hasAlts then -- User did not provide alternatives using `|` subgoals := subgoals ++ altMVarIds.toArray else if altMVarIds.isEmpty then pure () else logError m!"alternative '{altName}' has not been provided" altMVarIds.forM fun mvarId => admitGoal mvarId | some altStx => (subgoals, usedWildcard) ← withRef altStx do let altVars := getAltVars altStx let numFieldsToName ← if altHasExplicitModifier altStx then pure numFields else getNumExplicitFields altMVarId numFields if altVars.size > numFieldsToName then logError m!"too many variable names provided at alternative '{altName}', #{altVars.size} provided, but #{numFieldsToName} expected" let mut (fvarIds, altMVarId) ← altMVarId.introN numFields (altVars.toList.map getNameOfIdent') (useNamesForExplicitOnly := !altHasExplicitModifier altStx) -- Delay adding the infos for the pattern LHS because we want them to nest -- inside tacticInfo for the current alternative (in `evalAlt`) let addInfo := do if (← getInfoState).enabled then if let some declName := declName? then addConstInfo (getAltNameStx altStx) declName saveAltVarsInfo altMVarId altStx fvarIds let unusedAlt := do addInfo if isWildcard then pure (#[], usedWildcard) else throwError "alternative '{altName}' is not needed" match (← Cases.unifyEqs? numEqs altMVarId {}) with | none => unusedAlt | some (altMVarId', _) => (_, altMVarId) ← altMVarId'.introNP numGeneralized for fvarId in toClear do altMVarId ← altMVarId.tryClear fvarId let altMVarIds ← applyPreTac altMVarId if altMVarIds.isEmpty then unusedAlt else let mut subgoals := subgoals for altMVarId' in altMVarIds do subgoals ← evalAlt altMVarId' altStx addInfo subgoals pure (subgoals, usedWildcard || isWildcard) if usedWildcard then altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_ unless altsSyntax.isEmpty do logErrorAt altsSyntax[0]! "unused alternative" setGoals subgoals.toList applyPreTac (mvarId : MVarId) : TacticM (List MVarId) := if optPreTac.isNone then return [mvarId] else evalTacticAt optPreTac[0] mvarId end ElimApp /- Recall that ``` generalizingVars := optional (" generalizing " >> many1 ident) «induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts ``` `stx` is syntax for `induction`. -/ private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) := withRef stx do let generalizingStx := stx[3] if generalizingStx.isNone then pure #[] else trace[Elab.induction] "{generalizingStx}" let vars := generalizingStx[1].getArgs getFVarIds vars -- process `generalizingVars` subterm of induction Syntax `stx`. private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) := mvarId.withContext do let userFVarIds ← getUserGeneralizingFVarIds stx let forbidden ← mkGeneralizationForbiddenSet targets let mut s ← getFVarSetToGeneralize targets forbidden for userFVarId in userFVarIds do if forbidden.contains userFVarId then throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}" if s.contains userFVarId then throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically" s := s.insert userFVarId let fvarIds ← sortFVarIds s.toArray let (fvarIds, mvarId') ← mvarId.revert fvarIds return (fvarIds.size, mvarId') /-- Given `inductionAlts` of the fom ``` syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) ``` Return an array containing its alternatives. -/ private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax := inductionAlts[2].getArgs private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax := if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0] private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax := if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1] private def isMultiAlt (alt : Syntax) : Bool := alt[0].getNumArgs > 1 /-- Return `some #[alt_1, ..., alt_n]` if `alt` has multiple LHSs. -/ private def expandMultiAlt? (alt : Syntax) : Option (Array Syntax) := Id.run do if isMultiAlt alt then some <| alt[0].getArgs.map fun lhs => alt.setArg 0 (mkNullNode #[lhs]) else none /-- Given `inductionAlts` of the form ``` syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) ``` Return `some inductionAlts'` if one of the alternatives have multiple LHSs, in the new `inductionAlts'` all alternatives have a single LHS. Remark: the `RHS` of alternatives with multi LHSs is copied. -/ private def expandInductionAlts? (inductionAlts : Syntax) : Option Syntax := Id.run do let alts := getAltsOfInductionAlts inductionAlts if alts.any isMultiAlt then let mut altsNew := #[] for alt in alts do if let some alt' := expandMultiAlt? alt then altsNew := altsNew ++ alt' else altsNew := altsNew.push alt some <| inductionAlts.setArg 2 (mkNullNode altsNew) else none /-- Expand ``` syntax "induction " term,+ (" using " ident)? ("generalizing " (colGt term:max)+)? (inductionAlts)? : tactic ``` if `inductionAlts` has an alternative with multiple LHSs. -/ private def expandInduction? (induction : Syntax) : Option Syntax := do let optInductionAlts := induction[4] guard <| !optInductionAlts.isNone let inductionAlts' ← expandInductionAlts? optInductionAlts[0] return induction.setArg 4 (mkNullNode #[inductionAlts']) /-- Expand ``` syntax "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic ``` if `inductionAlts` has an alternative with multiple LHSs. -/ private def expandCases? (induction : Syntax) : Option Syntax := do let optInductionAlts := induction[3] guard <| !optInductionAlts.isNone let inductionAlts' ← expandInductionAlts? optInductionAlts[0] return induction.setArg 3 (mkNullNode #[inductionAlts']) /-- We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names. The idea is to make sure users do not write unstructured tactics. -/ private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit := unless optInductionAlts.isNone do let mut found := false for alt in getAltsOfInductionAlts optInductionAlts[0] do let n := getAltName alt if n == `_ then unless (getAltVars alt).isEmpty do throwErrorAt alt "wildcard alternative must not specify variable names" if found then throwErrorAt alt "more than one wildcard alternative '| _ => ...' used" found := true def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal := liftMetaMAtMain fun mvarId => do let majorType ← inferType major let majorType ← whnf majorType matchConstInduct majorType.getAppFn (fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}") (fun val _ => pure val) -- `optElimId` is of the form `("using" ident)?` private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM ElimInfo := do if optElimId.isNone then if let some elimInfo ← getCustomEliminator? targets then return elimInfo unless targets.size == 1 do throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>'), and no default eliminator has been registered using attribute `[eliminator]`" let indVal ← getInductiveValFromMajor targets[0]! if induction && indVal.all.length != 1 then throwError "'induction' tactic does not support mutually inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives" if induction && indVal.isNested then throwError "'induction' tactic does not support nested inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives" let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name getElimInfo elimName indVal.name else let elimId := optElimId[1] let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId -- not a precise check, but covers the common cases of T.recOn / T.casesOn -- as well as user defined T.myInductionOn to locate the constructors of T let baseName? := if ← isInductive elimName.getPrefix then some elimName.getPrefix else none withRef elimId <| getElimInfo elimName baseName? private def shouldGeneralizeTarget (e : Expr) : MetaM Bool := do if let .fvar fvarId .. := e then return (← fvarId.getDecl).hasValue -- must generalize let-decls else return true private def generalizeTargets (exprs : Array Expr) : TacticM (Array Expr) := do if (← withMainContext <| exprs.anyM (shouldGeneralizeTarget ·)) then liftMetaTacticAux fun mvarId => do let (fvarIds, mvarId) ← mvarId.generalize (exprs.map fun expr => { expr }) return (fvarIds.map mkFVar, [mvarId]) else return exprs @[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => match expandInduction? stx with | some stxNew => withMacroExpansion stx stxNew <| evalTactic stxNew | _ => focus do let optInductionAlts := stx[4] let alts := getAltsOfOptInductionAlts optInductionAlts let targets ← withMainContext <| stx[1].getSepArgs.mapM (elabTerm · none) let targets ← generalizeTargets targets let elimInfo ← withMainContext <| getElimNameInfo stx[2] targets (induction := true) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← mvarId.getTag mvarId.withContext do let targets ← addImplicitTargets elimInfo targets checkTargets targets let targetFVarIds := targets.map (·.fvarId!) let (n, mvarId) ← generalizeVars mvarId stx targets mvarId.withContext do let result ← withRef stx[1] do -- use target position as reference ElimApp.mkElimApp elimInfo targets tag trace[Elab.induction] "elimApp: {result.elimApp}" let elimArgs := result.elimApp.getAppArgs ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos]!.mvarId! targetFVarIds let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts mvarId.assign result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds) appendGoals result.others.toList where checkTargets (targets : Array Expr) : MetaM Unit := do let mut foundFVars : FVarIdSet := {} for target in targets do unless target.isFVar do throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}" if foundFVars.contains target.fvarId! then throwError "target (or one of its indices) occurs more than once{indentExpr target}" def elabCasesTargets (targets : Array Syntax) : TacticM (Array Expr) := withMainContext do let args ← targets.mapM fun target => do let hName? := if target[0].isNone then none else some target[0][0].getId let expr ← elabTerm target[1] none return { expr, hName? : GeneralizeArg } if (← withMainContext <| args.anyM fun arg => shouldGeneralizeTarget arg.expr <||> pure arg.hName?.isSome) then liftMetaTacticAux fun mvarId => do let argsToGeneralize ← args.filterM fun arg => shouldGeneralizeTarget arg.expr <||> pure arg.hName?.isSome let (fvarIdsNew, mvarId) ← mvarId.generalize argsToGeneralize let mut result := #[] let mut j := 0 for arg in args do if (← shouldGeneralizeTarget arg.expr) || arg.hName?.isSome then result := result.push (mkFVar fvarIdsNew[j]!) j := j+1 else result := result.push arg.expr return (result, [mvarId]) else return args.map (·.expr) @[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => match expandCases? stx with | some stxNew => withMacroExpansion stx stxNew <| evalTactic stxNew | _ => focus do -- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts let targets ← elabCasesTargets stx[1].getSepArgs let optInductionAlts := stx[3] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts let targetRef := stx[1] let elimInfo ← withMainContext <| getElimNameInfo stx[2] targets (induction := false) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← mvarId.getTag mvarId.withContext do let targets ← addImplicitTargets elimInfo targets let result ← withRef targetRef <| ElimApp.mkElimApp elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i]! let motiveType ← inferType elimArgs[elimInfo.motivePos]! let mvarId ← generalizeTargetsEq mvarId motiveType targets let (targetsNew, mvarId) ← mvarId.introN targets.size mvarId.withContext do ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos]!.mvarId! targetsNew mvarId.assign result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew) builtin_initialize registerTraceClass `Elab.cases registerTraceClass `Elab.induction end Lean.Elab.Tactic
4c33f5edbde474d5e30a9ba45bb1c2a08b8832ed
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/struct_instance_in_eqn.lean
7d561bda55b918bea1d320aaa888cf4406c4d316
[ "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
155
lean
structure S := (x : Nat) (y : Bool) (z : Nat) (w : Nat) set_option trace.compiler.stage1 true def g : S → S | s@{ x := x, ..} => { s with x := x + 1 }
e1b410fb993bbe5e0f1a0f235d71f60c78a6167c
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/finset/basic.lean
b084904ab0bb84fe8e11969b3d673cb7605bbdb9
[ "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
122,013
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ import data.int.basic import data.multiset.finset_ops import tactic.apply import tactic.monotonicity import tactic.nth_rewrite /-! # Finite sets Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `finset α` is defined as a structure with 2 fields: 1. `val` is a `multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `list` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i in (s : finset α), f i`; 2. `∏ i in (s : finset α), f i`. Lean refers to these operations as `big_operator`s. More information can be found in `algebra.big_operators.basic`. Finsets are directly used to define fintypes in Lean. A `fintype α` instance for a type `α` consists of a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `data.fintype.basic`. `finset.card`, the size of a finset is defined in `data.finset.card`. This is then used to define `fintype.card`, the size of a type. ## Main declarations ### Main definitions * `finset`: Defines a type for the finite subsets of `α`. Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `finset.has_mem`: Defines membership `a ∈ (s : finset α)`. * `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`. * `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`. * `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`, then it holds for the finset obtained by inserting a new element. * `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. ### Finset constructions * `singleton`: Denoted by `{a}`; the finset consisting of one element. * `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`. * `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`. * `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `finset.has_subset`: Lots of API about lattices, otherwise behaves exactly as one would expect. * `finset.has_union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `finset.sup`/`finset.bUnion` for finite unions. * `finset.has_inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. See `finset.inf` for finite intersections. * `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. ### Operations on two or more finsets * `insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `finset.has_union`: see "The lattice structure on subsets of finsets" * `finset.has_inter`: see "The lattice structure on subsets of finsets" * `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `finset.has_sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`. * `finset.product`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `data.finset.pi`. * `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a `s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. * `finset.bInter`: TODO: Implemement finite intersections. ### Maps constructed using finsets * `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ### Predicates on finsets * `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `finset.nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form. ### Equivalences between finsets * The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ open multiset subtype nat function universes u 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 dedup_eq_self [decidable_eq α] (s : finset α) : dedup s.1 = s.1 := s.2.dedup instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ s₁.nodup.ext s₂.nodup @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### type coercion -/ /-- Coercion from a finset to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (finset α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)] (s : finset ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α (∈ s) } instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) : can_lift (s → α) (ι → α) := pi_finset_coe.can_lift ι (λ _, α) s instance finset_coe.can_lift (s : finset α) : can_lift α s := { coe := coe, cond := λ a, a ∈ s, prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } @[simp, norm_cast] lemma coe_sort_coe (s : finset α) : ((s : set α) : Sort*) = s := rfl /-! ### Subset and strict subset relations -/ section subset variables {s t : finset α} instance : has_subset (finset α) := ⟨λ s t, ∀ ⦃a⦄, a ∈ s → a ∈ t⟩ instance : has_ssubset (finset α) := ⟨λ s t, s ⊆ t ∧ ¬ t ⊆ s⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := λ s a, id, le_trans := λ s t u hst htu a ha, htu $ hst ha, le_antisymm := λ s t hst hts, ext $ λ a, ⟨@hst _, @hts _⟩ } instance : is_refl (finset α) (⊆) := has_le.le.is_refl instance : is_trans (finset α) (⊆) := has_le.le.is_trans instance : is_antisymm (finset α) (⊆) := has_le.le.is_antisymm instance : is_irrefl (finset α) (⊂) := has_lt.lt.is_irrefl instance : is_trans (finset α) (⊂) := has_lt.lt.is_trans instance : is_asymm (finset α) (⊂) := has_lt.lt.is_asymm instance : is_nonstrict_strict_order (finset α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩ lemma subset_def : s ⊆ t ↔ s.1 ⊆ t.1 := iff.rfl lemma ssubset_def : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ protected lemma subset.rfl {s :finset α} : s ⊆ s := subset.refl _ protected theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset lemma not_mem_mono {s t : finset α} (h : s ⊆ t) {a : α} : a ∉ t → a ∉ s := mt $ @h _ theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff theorem not_subset (s t : finset α) : ¬(s ⊆ t) ↔ ∃ x ∈ s, ¬(x ∈ t) := by simp only [←finset.coe_subset, set.not_subset, exists_prop, finset.mem_coe] @[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl @[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne _ _ s t theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := set.exists_of_ssubset h end subset -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans /-! ### Order embedding from `finset α` to `set α` -/ /-- Coercion to `set α` as an `order_embedding`. -/ def coe_emb : finset α ↪o set α := ⟨⟨coe, coe_injective⟩, λ s t, coe_subset⟩ @[simp] lemma coe_coe_emb : ⇑(coe_emb : finset α ↪o set α) = coe := rfl /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x : α, x ∈ s instance decidable_nonempty {s : finset α} : decidable s.nonempty := decidable_of_iff (∃ a ∈ s, true) $ by simp_rw [exists_prop, and_true, finset.nonempty] @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s : set α).nonempty ↔ s.nonempty := iff.rfl @[simp] lemma nonempty_coe_sort {s : finset α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype alias coe_nonempty ↔ _ nonempty.to_set lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x : α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩ /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance inhabited_finset : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ lemma 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 @[simp] lemma not_ssubset_empty (s : finset α) : ¬s ⊂ ∅ := λ h, let ⟨x, he, hs⟩ := exists_of_ssubset h in he theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := nonempty_iff_ne_empty.not.trans not_not theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] @[simp] lemma is_empty_coe_sort {s : finset α} : is_empty ↥s ↔ s = ∅ := by simpa using @set.is_empty_coe_sort α s /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem is_empty_elim /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = {a} := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton lemma eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : finset α)) : x = y := mem_singleton.1 h theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl lemma singleton_injective : injective (singleton : α → finset α) := λ a b h, mem_singleton.1 (h ▸ mem_singleton_self _) theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := singleton_injective.eq_iff @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } @[simp, norm_cast] lemma coe_eq_singleton {α : Type*} {s : finset α} {a : α} : (s : set α) = {a} ↔ s = {a} := by rw [←finset.coe_singleton, finset.coe_inj] lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { rintro rfl, simp }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, exact hne.some_spec } end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := by rw [←coe_subset, coe_singleton, set.subset_singleton_iff_eq, coe_eq_empty, coe_eq_singleton] protected lemma nonempty.subset_singleton_iff {s : finset α} {a : α} (h : s.nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff.trans $ or_iff_right h.ne_empty lemma subset_singleton_iff' {s : finset α} {a : α} : s ⊆ {a} ↔ ∀ b ∈ s, b = a := forall₂_congr $ λ _ _, mem_singleton @[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty] lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### cons -/ section cons variables {s t : finset α} {a b : α} /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] lemma mem_cons {h} : b ∈ s.cons a h ↔ b = a ∨ b ∈ s := mem_cons @[simp] lemma mem_cons_self (a : α) (s : finset α) {h} : a ∈ cons a s h := mem_cons_self _ _ @[simp] lemma cons_val (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl lemma forall_mem_cons (h : a ∉ s) (p : α → Prop) : (∀ x, x ∈ cons a s h → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by simp only [mem_cons, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] lemma mk_cons {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (nodup_cons.1 h).2⟩ (nodup_cons.1 h).1 := rfl @[simp] lemma nonempty_cons (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 $ or.inl rfl⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a :: l) hl := by simp [← multiset.cons_coe] @[simp] lemma coe_cons {a s h} : (@cons α a s h : set α) = insert a s := by { ext, simp } lemma subset_cons (h : a ∉ s) : s ⊆ s.cons a h := subset_cons _ _ lemma ssubset_cons (h : a ∉ s) : s ⊂ s.cons a h := ssubset_cons h lemma cons_subset {h : a ∉ s} : s.cons a h ⊆ t ↔ a ∈ t ∧ s ⊆ t := cons_subset @[simp] lemma cons_subset_cons {hs ht} : s.cons a hs ⊆ t.cons a ht ↔ s ⊆ t := by rwa [← coe_subset, coe_cons, coe_cons, set.insert_subset_insert_iff, coe_subset] lemma ssubset_iff_exists_cons_subset : s ⊂ t ↔ ∃ a (h : a ∉ s), s.cons a h ⊆ t := begin refine ⟨λ h, _, λ ⟨a, ha, h⟩, ssubset_of_ssubset_of_subset (ssubset_cons _) h⟩, obtain ⟨a, hs, ht⟩ := (not_subset _ _).1 h.2, exact ⟨a, ht, cons_subset.2 ⟨hs, h.subset⟩⟩, end end cons /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append lemma disj_union_comm (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : disj_union s t h = disj_union t s (λ a ht hs, h _ hs ht) := eq_of_veq $ add_comm _ _ @[simp] lemma empty_disj_union (t : finset α) (h : ∀ a' ∈ ∅, a' ∉ t := λ a h _, not_mem_empty _ h) : disj_union ∅ t h = t := eq_of_veq $ zero_add _ @[simp] lemma disj_union_empty (s : finset α) (h : ∀ a' ∈ s, a' ∉ ∅ := λ a h, not_mem_empty _) : disj_union s ∅ h = s := eq_of_veq $ add_zero _ lemma singleton_disj_union (a : α) (t : finset α) (h : ∀ a' ∈ {a}, a' ∉ t) : disj_union {a} t h = cons a t (h _ $ mem_singleton_self _) := eq_of_veq $ multiset.singleton_add _ _ lemma disj_union_singleton (s : finset α) (a : α) (h : ∀ a' ∈ s, a' ∉ {a}) : disj_union s {a} h = cons a s (λ ha, h _ ha $ mem_singleton_self _) := by rw [disj_union_comm, singleton_disj_union] /-! ### insert -/ section decidable_eq variables [decidable_eq α] {s t u v : finset α} {a b : α} /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, s.2.ndinsert a⟩⟩ lemma insert_def (a : α) (s : finset α) : insert a s = ⟨_, s.2.ndinsert a⟩ := 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 = dedup (a ::ₘ s.1) := by rw [dedup_cons, dedup_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] lemma mem_insert : 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 lemma mem_insert_of_mem (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h lemma mem_of_mem_insert_of_ne (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left lemma eq_of_not_mem_of_mem_insert (ha : b ∈ insert a s) (hb : b ∉ s) : b = a := (mem_insert.1 ha).resolve_right hb @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] lemma insert_eq_of_mem (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem pair_comm (a b : α) : ({a, b} : finset α) = {b, a} := insert.comm a b ∅ @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } lemma insert_subset : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] lemma subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert_self _ _) ha, congr_arg _⟩ lemma insert_inj_on (s : finset α) : set.inj_on (λ a, insert a s) sᶜ := λ a h b _, (insert_inj h).1 lemma ssubset_iff : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.rfl⟩ @[elab_as_eliminator] lemma cons_induction {α : Type*} {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ 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 _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [cons_val] } end) nd @[elab_as_eliminator] lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- To prove a proposition about a nonempty `s : finset α`, it suffices to show it holds for all singletons and that if it holds for nonempty `t : finset α`, then it also holds for the `finset` obtained by inserting an element in `t`. -/ @[elab_as_eliminator] lemma nonempty.cons_induction {α : Type*} {p : Π s : finset α, s.nonempty → Prop} (h₀ : ∀ a, p {a} (singleton_nonempty _)) (h₁ : ∀ ⦃a⦄ s (h : a ∉ s) hs, p s hs → p (finset.cons a s h) (nonempty_cons h)) {s : finset α} (hs : s.nonempty) : p s hs := begin induction s using finset.cons_induction with a t ha h, { exact (not_nonempty_empty hs).elim }, obtain rfl | ht := t.eq_empty_or_nonempty, { exact h₀ a }, { exact h₁ t ha ht (h ht) } end /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### Lattice structure -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s t, ⟨_, t.2.ndunion s.1⟩⟩ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s t, ⟨_, s.2.ndinter t.1⟩⟩ instance : lattice (finset α) := { sup := (∪), sup_le := λ s t u hs ht a ha, (mem_ndunion.1 ha).elim (λ h, hs h) (λ h, ht h), le_sup_left := λ s t a h, mem_ndunion.2 $ or.inl h, le_sup_right := λ s t a h, mem_ndunion.2 $ or.inr h, inf := (∩), le_inf := λ s t u ht hu a h, mem_ndinter.2 ⟨ht h, hu h⟩, inf_le_left := λ s t a h, (mem_ndinter.1 h).1, inf_le_right := λ s t a h, (mem_ndinter.1 h).2, ..finset.partial_order } /-! #### union -/ @[simp] lemma sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl lemma union_val_nd (s t : finset α) : (s ∪ t).1 = ndunion s.1 t.1 := rfl @[simp] lemma union_val (s t : finset α) : (s ∪ t).1 = s.1 ∪ t.1 := ndunion_eq_union s.2 @[simp] lemma mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := mem_ndunion @[simp] lemma disj_union_eq_union (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp lemma mem_union_left (t : finset α) (h : a ∈ s) : a ∈ s ∪ t := mem_union.2 $ or.inl h lemma mem_union_right (s : finset α) (h : a ∈ t) : a ∈ s ∪ t := mem_union.2 $ or.inr h lemma forall_mem_union {p : α → Prop} : (∀ a ∈ s ∪ t, p a) ↔ (∀ a ∈ s, p a) ∧ ∀ a ∈ t, p a := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ lemma not_mem_union : a ∉ s ∪ t ↔ a ∉ s ∧ a ∉ t := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union lemma union_subset (hs : s ⊆ u) : t ⊆ u → s ∪ t ⊆ u := sup_le $ le_iff_subset.2 hs theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union (hsu : s ⊆ u) (htv : t ⊆ v) : s ∪ t ⊆ u ∪ v := sup_le_sup (le_iff_subset.2 hsu) htv lemma union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := sup_comm instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] lemma union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := sup_assoc instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] lemma union_idempotent (s : finset α) : s ∪ s = s := sup_idem instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ lemma union_subset_left (h : s ∪ t ⊆ u) : s ⊆ u := (subset_union_left _ _).trans h lemma union_subset_right {s t u : finset α} (h : s ∪ t ⊆ u) : t ⊆ u := subset.trans (subset_union_right _ _) h lemma union_left_comm (s t u : finset α) : s ∪ (t ∪ u) = t ∪ (s ∪ u) := ext $ λ _, by simp only [mem_union, or.left_comm] lemma union_right_comm (s t u : finset α) : (s ∪ t) ∪ u = (s ∪ u) ∪ t := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ t)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] lemma insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end lemma _root_.directed.exists_mem_subset_of_finset_subset_bUnion {α ι : Type*} [hn : nonempty ι] {f : ι → set α} (h : directed (⊆) f) {s : finset α} (hs : (s : set α) ⊆ ⋃ i, f i) : ∃ i, (s : set α) ⊆ f i := begin classical, revert hs, apply s.induction_on, { refine λ _, ⟨hn.some, _⟩, simp only [coe_empty, set.empty_subset], }, { intros b t hbt htc hbtc, obtain ⟨i : ι , hti : (t : set α) ⊆ f i⟩ := htc (set.subset.trans (t.subset_insert b) hbtc), obtain ⟨j, hbj⟩ : ∃ j, b ∈ f j, by simpa [set.mem_Union₂] using hbtc (t.mem_insert_self b), rcases h j i with ⟨k, hk, hk'⟩, use k, rw [coe_insert, set.insert_subset], exact ⟨hk hbj, trans hti hk'⟩ } end lemma _root_.directed_on.exists_mem_subset_of_finset_subset_bUnion {α ι : Type*} {f : ι → set α} {c : set ι} (hn : c.nonempty) (hc : directed_on (λ i j, f i ⊆ f j) c) {s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i := begin rw set.bUnion_eq_Union at hs, haveI := set.nonempty_coe_sort.2 hn, obtain ⟨⟨i, hic⟩, hi⟩ := (directed_comp.2 hc.directed_coe).exists_mem_subset_of_finset_subset_bUnion hs, exact ⟨i, hic, hi⟩ end /-! #### inter -/ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] lemma 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 lemma subset_inter {s₁ s₂ u : finset α} : s₁ ⊆ s₂ → s₁ ⊆ u → s₁ ⊆ s₂ ∩ u := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] lemma inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] lemma inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] lemma empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_left (h : t ⊆ u) : s ∩ t ⊆ s ∩ u := inter_subset_inter subset.rfl h lemma inter_subset_inter_right (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter h subset.rfl instance {α : Type u} : order_bot (finset α) := { bot := ∅, bot_le := empty_subset } @[simp] lemma bot_eq_empty {α : Type u} : (⊥ : finset α) = ∅ := rfl 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 } @[simp] theorem union_left_idem (s t : finset α) : s ∪ (s ∪ t) = s ∪ t := sup_left_idem @[simp] theorem union_right_idem (s t : finset α) : s ∪ t ∪ t = s ∪ t := sup_right_idem @[simp] theorem inter_left_idem (s t : finset α) : s ∩ (s ∩ t) = s ∩ t := inf_left_idem @[simp] theorem inter_right_idem (s t : finset α) : s ∩ t ∩ t = s ∩ t := inf_right_idem theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_union_distrib_left (s t u : finset α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ lemma union_union_distrib_right (s t u : finset α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ lemma inter_inter_distrib_left (s t u : finset α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ lemma inter_inter_distrib_right (s t u : finset α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ lemma union_union_union_comm (s t u v : finset α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ lemma inter_inter_inter_comm (s t u v : finset α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff lemma union_subset_iff : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (sup_le_iff : s ⊔ t ≤ u ↔ s ≤ u ∧ t ≤ u) lemma subset_inter_iff : s ⊆ t ∩ u ↔ s ⊆ t ∧ s ⊆ u := (le_inf_iff : s ≤ t ⊓ u ↔ s ≤ t ∧ s ≤ u) lemma inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := inf_eq_left lemma inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := inf_eq_right lemma ite_subset_union (s s' : finset α) (P : Prop) [decidable P] : ite P s s' ⊆ s ∪ s' := ite_le_sup s s' P lemma inter_subset_ite (s s' : finset α) (P : Prop) [decidable P] : s ∩ s' ⊆ ite P s s' := inf_le_ite s s' P /-! ### 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 α := ⟨_, s.2.erase a⟩ @[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 := s.2.mem_erase_iff lemma not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := s.2.not_mem_erase -- While this can be solved by `simp`, this lemma is eligible for `dsimp` @[nolint simp_nf, simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl @[simp] lemma erase_singleton (a : α) : ({a} : finset α).erase a = ∅ := begin ext x, rw [mem_erase, mem_singleton, not_and_self], refl, end lemma ne_of_mem_erase : b ∈ erase s a → b ≠ a := λ h, (mem_erase.1 h).1 lemma mem_of_mem_erase : b ∈ erase s a → b ∈ s := mem_of_mem_erase lemma mem_erase_of_ne_of_mem : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ lemma subset_erase {a : α} {s t : finset α} : s ⊆ t.erase a ↔ s ⊆ t ∧ a ∉ s := ⟨λ h, ⟨h.trans (erase_subset _ _), λ ha, not_mem_erase _ _ (h ha)⟩, λ h b hb, mem_erase.2 ⟨ne_of_mem_of_not_mem hb h.2, h.1 hb⟩⟩ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h lemma ssubset_iff_exists_subset_erase {s t : finset α} : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t.erase a := begin refine ⟨λ h, _, λ ⟨a, ha, h⟩, ssubset_of_subset_of_ssubset h $ erase_ssubset ha⟩, obtain ⟨a, ht, hs⟩ := (not_subset _ _).1 h.2, exact ⟨a, ht, subset_erase.2 ⟨h.1, hs⟩⟩, end lemma erase_ssubset_insert (s : finset α) (a : α) : s.erase a ⊂ insert a s := ssubset_iff_exists_subset_erase.2 ⟨a, mem_insert_self _ _, erase_subset_erase _ $ subset_insert _ _⟩ @[simp] theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h @[simp] lemma erase_insert_eq_erase (s : finset α) (a : α) : (insert a s).erase a = s.erase a := by by_cases ha : a ∈ s; { simp [ha, erase_insert] } lemma erase_cons {s : finset α} {a : α} (h : a ∉ s) : (s.cons a h).erase a = s := by rw [cons_eq_insert, erase_insert_eq_erase, erase_eq_of_not_mem h] lemma erase_idem {a : α} {s : finset α} : erase (erase s a) a = erase s a := by simp lemma erase_right_comm {a b : α} {s : finset α} : erase (erase s a) b = erase (erase s b) a := by { ext x, simp only [mem_erase, ←and_assoc], rw and_comm (x ≠ a) } 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.rfl theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.rfl lemma subset_insert_iff_of_not_mem (h : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := by rw [subset_insert_iff, erase_eq_of_not_mem h] lemma erase_subset_iff_of_mem (h : a ∈ t) : s.erase a ⊆ t ↔ s ⊆ t := by rw [←subset_insert_iff, insert_eq_of_mem h] lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := begin refine ⟨λ h, _, congr_arg _⟩, rw eq_of_mem_of_not_mem_erase hx, rw ←h, simp, end lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp lemma erase_inj_on' (a : α) : {s : finset α | a ∈ s}.inj_on (λ s, erase s a) := λ s hs t ht (h : s.erase a = _), by rw [←insert_erase hs, ←insert_erase ht, h] /-! ### 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 tsub_le_self s₁.2⟩⟩ @[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl @[simp] theorem mem_sdiff : a ∈ s \ t ↔ a ∈ s ∧ a ∉ t := mem_sub_of_nodup s.2 @[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 instance : generalized_boolean_algebra (finset α) := { sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter], tauto }, inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff, inf_eq_inter, not_mem_empty], tauto }, ..finset.has_sdiff, ..finset.distrib_lattice, ..finset.order_bot } lemma not_mem_sdiff_of_mem_right (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] lemma not_mem_sdiff_of_not_mem_left (h : a ∉ s) : a ∉ s \ t := by simpa lemma union_sdiff_of_subset (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_cancel_right h theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) lemma inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] lemma sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left @[simp] lemma sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self lemma sdiff_inter_distrib_right (s t u : finset α) : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf @[simp] lemma sdiff_inter_self_left (s t : finset α) : s \ (s ∩ t) = s \ t := sdiff_inf_self_left @[simp] lemma sdiff_inter_self_right (s t : finset α) : s \ (t ∩ s) = s \ t := sdiff_inf_self_right @[simp] lemma sdiff_empty : s \ ∅ = s := sdiff_bot @[mono] lemma sdiff_subset_sdiff (hst : s ⊆ t) (hvu : v ⊆ u) : s \ u ⊆ t \ v := sdiff_le_sdiff ‹s ≤ t› ‹v ≤ u› @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem sdiff_union_self_eq_union : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left lemma union_sdiff_symm : s ∪ (t \ s) = t ∪ (s \ t) := sup_sdiff_symm lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := sup_sdiff_inf _ _ @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem lemma sdiff_eq_empty_iff_subset : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff lemma sdiff_nonempty : (s \ t).nonempty ↔ ¬ s ⊆ t := nonempty_iff_ne_empty.trans sdiff_eq_empty_iff_subset.not @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le lemma sdiff_ssubset (h : t ⊆ s) (ht : t.nonempty) : s \ t ⊂ s := sdiff_lt ‹t ≤ s› ht.ne_empty lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } @[simp] lemma sdiff_singleton_not_mem_eq_self (s : finset α) {a : α} (ha : a ∉ s) : s \ {a} = s := by simp only [sdiff_singleton_eq_erase, ha, erase_eq_of_not_mem, not_false_iff] lemma sdiff_erase {x : α} (hx : x ∈ s) : s \ s.erase x = {x} := begin rw [← sdiff_singleton_eq_erase, sdiff_sdiff_right_self], exact inf_eq_right.2 (singleton_subset_iff.2 hx), end lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma sdiff_sdiff_eq_self (h : t ⊆ s) : s \ (s \ t) = t := sdiff_sdiff_eq_self h lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf lemma erase_eq_empty_iff (s : finset α) (a : α) : s.erase a = ∅ ↔ s = ∅ ∨ s = {a} := by rw [←sdiff_singleton_eq_erase, sdiff_eq_empty_iff_subset, subset_singleton_iff] end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl @[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty := by simp [finset.nonempty] @[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ := by simpa [eq_empty_iff_forall_not_mem] /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Π i, δ i) [Π j, decidable (j ∈ s)] : Π i, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Π i, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀ i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [Π i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [Π j, decidable (j ∈ s)] -- TODO: fix this in norm_cast @[norm_cast move] lemma piecewise_coe [∀ j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀ i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀ i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := by { classical, simp only [← piecewise_coe, coe_insert, ← set.piecewise_insert] } lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Π a ∈ s, Prop} [hp : ∀ a (h : a ∈ s), decidable (p a h)] : decidable (∀ a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀ a, decidable_eq (β a)] : decidable_eq (Π a ∈ s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Π a ∈ s, Prop} [hp : ∀ a (h : a ∈ s), decidable (p a h)] : decidable (∃ a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, s.2.filter p⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter lemma mem_of_mem_filter {s : finset α} (x : α) (h : x ∈ s.filter p) : x ∈ s := mem_of_mem_filter h theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} lemma filter_eq_self (s : finset α) : s.filter p = s ↔ ∀ x ∈ s, p x := by simp [finset.ext_iff] /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := (filter_eq_self s).mpr h /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_eq_empty_iff (s : finset α) : (s.filter p = ∅) ↔ ∀ x ∈ s, ¬ p x := begin refine ⟨_, filter_false_of_mem⟩, intros hs, injection hs with hs', rwa filter_eq_nil at hs' end lemma filter_nonempty_iff {s : finset α} : (s.filter p).nonempty ↔ ∃ a ∈ s, p a := by simp only [nonempty_iff_ne_empty, ne.def, filter_eq_empty_iff, not_not, not_forall] lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) 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⟩ lemma monotone_filter_left : monotone (filter p) := λ _ _, filter_subset_filter p lemma monotone_filter_right (s : finset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := multiset.subset_of_le (multiset.monotone_filter_right s.val h) @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter lemma subset_coe_filter_of_subset_forall (s : finset α) {t : set α} (h₁ : t ⊆ s) (h₂ : ∀ x ∈ t, p x) : t ⊆ s.filter p := λ x hx, (s.coe_filter p).symm ▸ ⟨h₁ hx, h₂ x hx⟩ theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_cons_of_pos (a : α) (s : finset α) (ha : a ∉ s) (hp : p a): filter p (cons a s ha) = cons a (filter p s) (mem_filter.not.mpr $ mt and.left ha) := eq_of_veq $ multiset.filter_cons_of_pos s.val hp theorem filter_cons_of_neg (a : α) (s : finset α) (ha : a ∉ s) (hp : ¬p a): filter p (cons a s ha) = filter p s := eq_of_veq $ multiset.filter_cons_of_neg s.val hp theorem filter_disj_union (s : finset α) (t : finset α) (h : ∀ (a : α), a ∈ s → a ∉ t) : filter p (disj_union s t h) = (filter p s).disj_union (filter p t) (λ a hs ht, h a (mem_of_mem_filter _ hs) (mem_of_mem_filter _ ht)) := eq_of_veq $ multiset.filter_add _ _ _ theorem filter_cons {a : α} (s : finset α) (ha : a ∉ s) : filter p (cons a s ha) = (if p a then {a} else ∅ : finset α).disj_union (filter p s) (λ b hb, by { split_ifs at hb, { rw finset.mem_singleton.mp hb, exact (mem_filter.not.mpr $ mt and.left ha) }, { cases hb } }) := begin split_ifs with h, { rw [filter_cons_of_pos _ _ _ ha h, singleton_disj_union] }, { rw [filter_cons_of_neg _ _ _ ha h, empty_disj_union] }, end variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] lemma filter_inter_distrib (s t : finset α) : (s ∩ t).filter p = s.filter p ∩ t.filter p := by { ext, simp only [mem_filter, mem_inter], exact and_and_distrib_right _ _ _ } theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_erase (a : α) (s : finset α) : filter p (erase s a) = erase (filter p s) a := by { ext x, simp only [and_assoc, mem_filter, iff_self, mem_erase] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] lemma sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃ s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩ }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintro m ⟨e⟩, exact h m } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], tauto } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm lemma range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := ne_of_gt $ tsub_pos_of_lt $ mem_range.1 hx @[simp] lemma nonempty_range_iff : (range n).nonempty ↔ n ≠ 0 := ⟨λ ⟨k, hk⟩, ((zero_le k).trans_lt $ mem_range.1 hk).ne', λ h, ⟨0, mem_range.2 $ pos_iff_ne_zero.2 h⟩⟩ @[simp] lemma range_eq_empty_iff : range n = ∅ ↔ n = 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not] lemma nonempty_range_succ : (range $ n + 1).nonempty := nonempty_range_iff.2 n.succ_ne_zero 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] lemma exists_mem_insert [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 lemma forall_mem_insert [decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := λ j, begin rw subtype.ext_iff_val, apply tsub_add_cancel_of_le, simpa using j.2 end, right_inv := λ j, add_tsub_cancel_right _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl /-! ### dedup 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_dedup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.dedup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 n.dedup.symm lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l = l' := by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h @[simp] lemma mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_dedup @[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 dedup_cons @[simp] lemma to_finset_singleton (a : α) : to_finset ({a} : multiset α) = {a} := by rw [singleton_eq_cons, to_finset_cons, to_finset_zero, is_lawful_singleton.insert_emptyc_eq] @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀ (n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp @[simp] theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.dedup_eq_zero @[simp] lemma to_finset_subset (s t : multiset α) : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace finset @[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s := by { ext, rw [multiset.mem_to_finset, ←mem_def] } lemma val_le_iff_val_subset {a : finset α} {b : multiset α} : a.val ≤ b ↔ a.val ⊆ b := multiset.le_iff_subset a.nodup end finset namespace list variables [decidable_eq α] {l l' : list α} {a : α} /-- `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.dedup : multiset α) := rfl lemma to_finset_eq (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] lemma mem_to_finset : a ∈ l.to_finset ↔ a ∈ l := mem_dedup @[simp] lemma to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] lemma to_finset_cons : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.dedup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := by { rintro ⟨⟨l⟩, hl⟩ _, exact ⟨l, hl, (to_finset_eq hl).symm⟩ } theorem to_finset_surjective : surjective (to_finset : list α → finset α) := λ s, let ⟨l, _, hls⟩ := to_finset_surj_on (set.mem_univ s) in ⟨l, hls⟩ lemma to_finset_eq_iff_perm_dedup : l.to_finset = l'.to_finset ↔ l.dedup ~ l'.dedup := by simp [finset.ext_iff, perm_ext (nodup_dedup _) (nodup_dedup _)] lemma to_finset.ext_iff {a b : list α} : a.to_finset = b.to_finset ↔ ∀ x, x ∈ a ↔ x ∈ b := by simp only [finset.ext_iff, mem_to_finset] lemma to_finset.ext : (∀ x, x ∈ l ↔ x ∈ l') → l.to_finset = l'.to_finset := to_finset.ext_iff.mpr lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset := to_finset_eq_iff_perm_dedup.mpr h.dedup lemma perm_of_nodup_nodup_to_finset_eq (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l ~ l' := by { rw ←multiset.coe_eq_coe, exact multiset.nodup.to_finset_inj hl hl' h } @[simp] lemma to_finset_append : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset := begin induction l with hd tl hl, { simp }, { simp [hl] } end @[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset := to_finset_eq_of_perm _ _ (reverse_perm l) lemma to_finset_repeat_of_ne_zero {n : ℕ} (hn : n ≠ 0) : (list.repeat a n).to_finset = {a} := by { ext x, simp [hn, list.mem_repeat] } @[simp] lemma to_finset_union (l l' : list α) : (l ∪ l').to_finset = l.to_finset ∪ l'.to_finset := by { ext, simp } @[simp] lemma to_finset_inter (l l' : list α) : (l ∩ l').to_finset = l.to_finset ∩ l'.to_finset := by { ext, simp } @[simp] lemma to_finset_eq_empty_iff (l : list α) : l.to_finset = ∅ ↔ l = nil := by cases l; simp end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, s.2.map f.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl @[simp] lemma mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.to_embedding ↔ f.symm b ∈ s := by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ } lemma mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 lemma mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 lemma forall_mem_map {f : α ↪ β} {s : finset α} {p : Π a, a ∈ s.map f → Prop} : (∀ y ∈ s.map f, p y H) ↔ ∀ x ∈ s, p (f x) (mem_map_of_mem _ H) := ⟨λ h y hy, h (f y) (mem_map_of_mem _ hy), λ h x hx, by { obtain ⟨y, hy, rfl⟩ := mem_map.1 hx, exact h _ hy }⟩ lemma apply_coe_mem_map (f : α ↪ β) (s : finset α) (x : s) : f x ∈ s.map f := mem_map_of_mem f x.prop @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f := calc ↑(s.map f) = f '' s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s /-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect. -/ lemma map_perm {σ : equiv.perm α} (hs : {a | σ a ≠ a} ⊆ s) : s.map (σ : α ↪ α) = s := coe_injective $ (coe_map _ _).trans $ set.image_perm hs theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right @[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) : s.map (equiv.cast h).to_embedding == s := by { subst h, simp } 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 lemma map_comm {β'} {f : β ↪ γ} {g : α ↪ β} {f' : α ↪ β'} {g' : β' ↪ γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.map g).map f = (s.map f').map g' := by simp_rw [map_map, embedding.trans, function.comp, h_comm] lemma _root_.function.semiconj.finset_map {f : α ↪ β} {ga : α ↪ α} {gb : β ↪ β} (h : function.semiconj f ga gb) : function.semiconj (map f) (map ga) (map gb) := λ s, map_comm h lemma _root_.function.commute.finset_map {f g : α ↪ α} (h : function.commute f g) : function.commute (map f) (map g) := h.finset_map @[simp] 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]⟩ /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪o finset β := order_embedding.of_map_le_iff (map f) (λ _ _, map_subset_map) @[simp] theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := (map_embedding f).injective.eq_iff lemma map_injective (f : α ↪ β) : injective (map f) := (map_embedding f).injective @[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 := eq_of_veq (map_filter _ _ _) /-- A helper lemma to produce a default proof for `finset.map_disj_union`. -/ theorem map_disj_union_aux {f : α ↪ β} {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ → a ∉ s₂) ↔ ∀ a, a ∈ map f s₁ → a ∉ map f s₂ := by simp_rw [forall_mem_map, mem_map'] theorem map_disj_union {f : α ↪ β} (s₁ s₂ : finset α) (h) (h' := map_disj_union_aux.1 h) : (s₁.disj_union s₂ h).map f = (s₁.map f).disj_union (s₂.map f) h' := eq_of_veq $ multiset.map_add _ _ _ /-- A version of `finset.map_disj_union` for writing in the other direction. -/ theorem map_disj_union' {f : α ↪ β} (s₁ s₂ : finset α) (h') (h := map_disj_union_aux.2 h') : (s₁.disj_union s₂ h).map f = (s₁.map f).disj_union (s₂.map f) h' := map_disj_union _ _ _ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := coe_injective $ by simp only [coe_map, coe_union, set.image_union] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := coe_injective $ by simp only [coe_map, coe_inter, set.image_inter f.injective] @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := coe_injective $ by simp only [coe_map, coe_singleton, set.image_singleton] @[simp] lemma map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] lemma map_cons (f : α ↪ β) (a : α) (s : finset α) (ha : a ∉ s) : (cons a s ha).map f = cons (f a) (s.map f) (by simpa using ha) := eq_of_veq $ multiset.map_cons f a s.val @[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⟩ @[simp] lemma map_nonempty : (s.map f).nonempty ↔ s.nonempty := by rw [nonempty_iff_ne_empty, nonempty_iff_ne_empty, ne.def, map_eq_empty] alias map_nonempty ↔ _ nonempty.map 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 _ lemma disjoint_range_add_left_embedding (a b : ℕ) : disjoint (range a) (map (add_left_embedding a) (range b)) := begin intros k hk, simp only [exists_prop, mem_range, inf_eq_inter, mem_map, add_left_embedding_apply, mem_inter] at hk, obtain ⟨a, haQ, ha⟩ := hk.2, simpa [← ha] using hk.1, end lemma disjoint_range_add_right_embedding (a b : ℕ) : disjoint (range a) (map (add_right_embedding a) (range b)) := begin intros k hk, simp only [exists_prop, mem_range, inf_eq_inter, mem_map, add_left_embedding_apply, mem_inter] at hk, obtain ⟨a, haQ, ha⟩ := hk.2, simpa [← ha] using hk.1, end end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).dedup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f g : α → β} {s : finset α} {t : finset β} {a : α} {b c : β} @[simp] lemma mem_image : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_dedup, multiset.mem_map, exists_prop] lemma mem_image_of_mem (f : α → β) {a} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma mem_image_const : c ∈ s.image (const α b) ↔ s.nonempty ∧ b = c := by { rw mem_image, simp only [exists_prop, const_apply, exists_and_distrib_right], refl } lemma mem_image_const_self : b ∈ s.image (const α b) ↔ s.nonempty := mem_image_const.trans $ and_iff_left rfl instance [can_lift β α] : can_lift (finset β) (finset α) := { cond := λ s, ∀ x ∈ s, can_lift.cond α x, coe := image can_lift.coe, prf := begin rintro ⟨⟨l⟩, hd : l.nodup⟩ hl, lift l to list α using hl, exact ⟨⟨l, hd.of_map _⟩, ext $ λ a, by simp⟩, end } lemma image_congr (h : (s : set α).eq_on f g) : finset.image f s = finset.image g s := by { ext, simp_rw mem_image, exact bex_congr (λ x hx, by rw h hx) } lemma _root_.function.injective.mem_finset_image (hf : injective f) : f a ∈ s.image f ↔ a ∈ s := begin refine ⟨λ h, _, finset.mem_image_of_mem f⟩, obtain ⟨y, hy, heq⟩ := mem_image.1 h, exact hf heq ▸ hy, end lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm protected lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ @[simp] lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty := ⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] lemma image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f := (s.2.map_on H).dedup @[simp] lemma image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] @[simp] theorem image_id' [decidable_eq α] : s.image (λ x, x) = s := image_id theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, dedup_map_dedup_eq, multiset.map_map] lemma image_comm {β'} [decidable_eq β'] [decidable_eq γ] {f : β → γ} {g : α → β} {f' : α → β'} {g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.image g).image f = (s.image f').image g' := by simp_rw [image_image, comp, h_comm] lemma _root_.function.semiconj.finset_image [decidable_eq α] {f : α → β} {ga : α → α} {gb : β → β} (h : function.semiconj f ga gb) : function.semiconj (image f) (image ga) (image gb) := λ s, image_comm h lemma _root_.function.commute.finset_image [decidable_eq α] {f g : α → α} (h : function.commute f g) : function.commute (image f) (image g) := h.finset_image theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_dedup', dedup_subset', multiset.map_subset_map h] lemma image_subset_iff : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image lemma image_subset_image_iff {t : finset α} (hf : injective f) : s.image f ⊆ t.image f ↔ s ⊆ t := by { simp_rw ←coe_subset, push_cast, exact set.image_subset_image_iff hf } theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] lemma image_inter_subset [decidable_eq α] (f : α → β) (s t : finset α) : (s ∩ t).image f ⊆ s.image f ∩ t.image f := subset_inter (image_subset_image $ inter_subset_left _ _) $ image_subset_image $ inter_subset_right _ _ lemma image_inter_of_inj_on [decidable_eq α] {f : α → β} (s t : finset α) (hf : set.inj_on f (s ∪ t)) : (s ∩ t).image f = s.image f ∩ t.image f := (image_inter_subset _ _ _).antisymm $ λ x, begin simp only [mem_inter, mem_image], rintro ⟨⟨a, ha, rfl⟩, b, hb, h⟩, exact ⟨a, ⟨ha, by rwa ←hf (or.inr hb) (or.inl ha) h⟩, rfl⟩, end lemma image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : injective f) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := image_inter_of_inj_on _ _ $ hf.inj_on _ @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] lemma erase_image_subset_image_erase [decidable_eq α] (f : α → β) (s : finset α) (a : α) : (s.image f).erase (f a) ⊆ (s.erase a).image f := begin simp only [subset_iff, and_imp, exists_prop, mem_image, exists_imp_distrib, mem_erase], rintro b hb x hx rfl, exact ⟨_, ⟨ne_of_apply_ne f hb, hx⟩, rfl⟩, end @[simp] lemma image_erase [decidable_eq α] {f : α → β} (hf : injective f) (s : finset α) (a : α) : (s.erase a).image f = (s.image f).erase (f a) := begin refine (erase_image_subset_image_erase _ _ _).antisymm' (λ b, _), simp only [mem_image, exists_prop, mem_erase], rintro ⟨a', ⟨haa', ha'⟩, rfl⟩, exact ⟨hf.ne haa', a', ha', rfl⟩, end @[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 mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀ i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := begin split, { rintros ⟨i, hi⟩, simp only [mem_image, exists_prop, mem_range], exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ }, { rintro h, simp only [mem_image, exists_prop, set.mem_range, mem_range] at *, rcases h with ⟨i, hi, ha⟩, exact ⟨i, ha⟩ } end lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀ i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃ i, f (i % n) = a) ↔ ∃ i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) lemma range_add (a b : ℕ) : range (a + b) = range a ∪ (range b).map (add_left_embedding a) := by { rw [←val_inj, union_val], exact multiset.range_add_eq_union a b } @[simp] 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, dedup_eq_self] @[simp] lemma attach_image_coe [decidable_eq α] {s : finset α} : s.attach.image coe = s := finset.attach_image_val @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq (s.map f).2.dedup.symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] @[simp] lemma map_erase [decidable_eq α] (f : α ↪ β) (s : finset α) (a : α) : (s.erase a).map f = (s.map f).erase (f a) := by { simp_rw map_eq_image, exact s.image_erase f.2 a } /-! ### Subtype -/ /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀ {a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl @[mono] lemma subtype_mono {p : α → Prop} [decidable_pred p] : monotone (finset.subtype p) := λ s t h x hx, mem_subtype.2 $ h $ mem_subtype.1 hx /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, simp [and_comm _ (_ = _), @and.left_comm _ (_ = _), and_comm (p x) (x ∈ s)] end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {s : set α} : ↑t ⊆ f '' s ↔ ∃ s' : finset α, ↑s' ⊆ s ∧ s'.image f = t := begin split, swap, { rintro ⟨t, ht, rfl⟩, rw [coe_image], exact set.image_subset f ht }, intro h, letI : can_lift β s := ⟨f ∘ coe, λ y, y ∈ f '' s, λ y ⟨x, hxt, hy⟩, ⟨⟨x, hxt⟩, hy⟩⟩, lift t to finset s using h, refine ⟨t.map (embedding.subtype _), map_subtype_subset _, _⟩, ext y, simp end lemma range_sdiff_zero {n : ℕ} : range (n + 1) \ {0} = (range n).image nat.succ := begin induction n with k hk, { simp }, nth_rewrite 1 range_succ, rw [range_succ, image_insert, ←hk, insert_sdiff_of_not_mem], simp end end image lemma _root_.multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.dedup_map_dedup_eq _ _).symm section to_list /-- Produce a list of the elements in the finite set using choice. -/ @[reducible] noncomputable def to_list (s : finset α) : list α := s.1.to_list lemma nodup_to_list (s : finset α) : s.to_list.nodup := by { rw [to_list, ←multiset.coe_nodup, multiset.coe_to_list], exact s.nodup } @[simp] lemma mem_to_list {a : α} (s : finset α) : a ∈ s.to_list ↔ a ∈ s := by { rw [to_list, ←multiset.mem_coe, multiset.coe_to_list], exact iff.rfl } @[simp] lemma to_list_empty : (∅ : finset α).to_list = [] := by simp [to_list] @[simp, norm_cast] lemma coe_to_list (s : finset α) : (s.to_list : multiset α) = s.val := by { classical, ext, simp } @[simp] lemma to_list_to_finset [decidable_eq α] (s : finset α) : s.to_list.to_finset = s := by { ext, simp } lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) : ∃ (l : list α), l.nodup ∧ l.to_finset = s := ⟨s.to_list, s.nodup_to_list, s.to_list_to_finset⟩ lemma to_list_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).to_list ~ a :: s.to_list := (list.perm_ext (nodup_to_list _) (by simp [h, nodup_to_list s])).2 $ λ x, by simp only [list.mem_cons_iff, finset.mem_to_list, finset.mem_cons] lemma to_list_insert [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : (insert a s).to_list ~ a :: s.to_list := cons_eq_insert _ _ h ▸ to_list_cons _ end to_list section bUnion /-! ### bUnion This section is about the bounded union of an indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. -/ variables [decidable_eq β] {s s₁ s₂ : finset α} {t t₁ t₂ : α → finset β} /-- `bUnion s t` is the union of `t x` over `x ∈ s`. (This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/ protected def bUnion (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bUnion_val (s : finset α) (t : α → finset β) : (s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).dedup := rfl @[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl @[simp] lemma mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃ a ∈ s, b ∈ t a := by simp only [mem_def, bUnion_val, mem_dedup, mem_bind, exists_prop] @[simp, norm_cast] lemma coe_bUnion : (s.bUnion t : set β) = ⋃ x ∈ (s : set α), t x := by simp only [set.ext_iff, mem_bUnion, set.mem_Union, iff_self, mem_coe, implies_true_iff] @[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t := ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] lemma bUnion_congr (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) : s₁.bUnion t₁ = s₂.bUnion t₂ := ext $ λ x, by simp [hs, ht] { contextual := tt } theorem bUnion_subset {s' : finset β} : s.bUnion t ⊆ s' ↔ ∀ x ∈ s, t x ⊆ s' := by simp only [subset_iff, mem_bUnion]; exact ⟨λ H a ha b hb, H ⟨a, ha, hb⟩, λ H b ⟨a, ha, hb⟩, H a ha hb⟩ @[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a := by { classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] } theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) := begin ext x, simp only [mem_bUnion, mem_inter], tauto end theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) := by rw [inter_comm, bUnion_inter]; simp [inter_comm] theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bUnion t = s.bUnion (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bUnion_insert, ih]) theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bUnion t).image f = s.bUnion (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bUnion_insert, image_union, ih]) lemma bUnion_bUnion [decidable_eq γ] (s : finset α) (f : α → finset β) (g : β → finset γ) : (s.bUnion f).bUnion g = s.bUnion (λ a, (f a).bUnion g) := begin ext, simp only [finset.mem_bUnion, exists_prop], simp_rw [←exists_and_distrib_right, ←exists_and_distrib_left, and_assoc], rw exists_comm, end theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop] lemma bUnion_mono (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion 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_bUnion, exists_imp_distrib, and_imp, exists_prop] lemma bUnion_subset_bUnion_of_subset_left (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t := begin intro x, simp only [and_imp, mem_bUnion, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma subset_bUnion_of_mem (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u := singleton_bUnion.superset.trans $ bUnion_subset_bUnion_of_subset_left u $ singleton_subset_iff.2 xs @[simp] lemma bUnion_subset_iff_forall_subset {α β : Type*} [decidable_eq β] {s : finset α} {t : finset β} {f : α → finset β} : s.bUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := ⟨λ h x hx, (subset_bUnion_of_mem f hx).trans h, λ h x hx, let ⟨a, ha₁, ha₂⟩ := mem_bUnion.mp hx in h _ ha₁ ha₂⟩ lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm] @[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s := by { rw bUnion_singleton, exact image_id } lemma filter_bUnion (s : finset α) (f : α → finset β) (p : β → Prop) [decidable_pred p] : (s.bUnion f).filter p = s.bUnion (λ a, (f a).filter p) := begin ext b, simp only [mem_bUnion, exists_prop, mem_filter], split, { rintro ⟨⟨a, ha, hba⟩, hb⟩, exact ⟨a, ha, hba, hb⟩ }, { rintro ⟨a, ha, hba, hb⟩, exact ⟨⟨a, ha, hba⟩, hb⟩ } end lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bUnion (λa, s.filter $ (λc, f c = a)) = s := ext $ λ b, by simpa using h b lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s := bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g) lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) : (s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) := by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] } @[simp] lemma bUnion_nonempty : (s.bUnion t).nonempty ↔ ∃ x ∈ s, (t x).nonempty := by simp [finset.nonempty, ← exists_and_distrib_left, @exists_swap α] lemma nonempty.bUnion (hs : s.nonempty) (ht : ∀ x ∈ s, (t x).nonempty) : (s.bUnion t).nonempty := bUnion_nonempty.2 $ hs.imp $ λ x hx, ⟨hx, ht x hx⟩ end bUnion /-! ### disjoint -/ --TODO@Yaël: Kill lemmas duplicate with `boolean_algebra` section disjoint variables [decidable_eq α] [decidable_eq β] {f : α → β} {s t u : finset α} {a b : α} lemma disjoint_left : 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 lemma disjoint_val : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left lemma disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] lemma disjoint_iff_ne : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] lemma _root_.disjoint.forall_ne_finset (h : disjoint s t) (ha : a ∈ s) (hb : b ∈ t) : a ≠ b := disjoint_iff_ne.1 h _ ha _ hb lemma not_disjoint_iff : ¬ disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t := not_forall.trans $ exists_congr $ λ a, not_not.trans mem_inter lemma disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) lemma disjoint_of_subset_right (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] lemma disjoint_singleton_left : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] lemma disjoint_singleton_right : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans disjoint_singleton_left @[simp] lemma disjoint_singleton : disjoint ({a} : finset α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton] @[simp] lemma disjoint_insert_left : 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] lemma disjoint_insert_right : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] lemma disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] lemma disjoint_union_right : 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 : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint : s \ t = s ↔ disjoint s t := sdiff_eq_self_iff_disjoint' lemma sdiff_eq_self_of_disjoint (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bUnion_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bUnion f) t ↔ (∀ i ∈ s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] } end lemma disjoint_bUnion_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bUnion f) ↔ ∀ i ∈ t, disjoint s (f i) := by simpa only [disjoint.comm] using disjoint_bUnion_left t f s lemma disjoint_filter {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ ∀ x ∈ s, p x → ¬ q x := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_filter_filter_neg (s : finset α) (p : α → Prop) [decidable_pred p] : disjoint (s.filter p) (s.filter $ λ a, ¬ p a) := (disjoint_filter.2 $ λ a _, id).symm @[simp, norm_cast] lemma disjoint_coe : disjoint (s : set α) t ↔ disjoint s t := by { rw [finset.disjoint_left, set.disjoint_left], refl } @[simp, norm_cast] lemma pairwise_disjoint_coe {ι : Type*} {s : set ι} {f : ι → finset α} : s.pairwise_disjoint (λ i, f i : ι → set α) ↔ s.pairwise_disjoint f := forall₅_congr $ λ _ _ _ _ _, disjoint_coe @[simp] lemma _root_.disjoint.of_image_finset (h : disjoint (s.image f) (t.image f)) : disjoint s t := disjoint_iff_ne.2 $ λ a ha b hb, ne_of_apply_ne f $ h.forall_ne_finset (mem_image_of_mem _ ha) (mem_image_of_mem _ hb) @[simp] lemma disjoint_image {f : α → β} (hf : injective f) : disjoint (s.image f) (t.image f) ↔ disjoint s t := begin simp only [disjoint_iff_ne, mem_image, exists_prop, exists_imp_distrib, and_imp], refine ⟨λ h a ha b hb hab, h _ _ ha rfl _ _ hb rfl $ congr_arg _ hab, _⟩, rintro h _ a ha rfl _ b hb rfl, exact hf.ne (h _ ha _ hb), end @[simp] lemma disjoint_map {f : α ↪ β} : disjoint (s.map f) (t.map f) ↔ disjoint s t := by { simp_rw map_eq_image, exact disjoint_image f.injective } end disjoint /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose section pairwise variables {s : finset α} lemma pairwise_subtype_iff_pairwise_finset' (r : β → β → Prop) (f : α → β) : pairwise (r on λ x : s, f x) ↔ (s : set α).pairwise (r on f) := begin refine ⟨λ h x hx y hy hxy, h ⟨x, hx⟩ ⟨y, hy⟩ (by simpa only [subtype.mk_eq_mk, ne.def]), _⟩, rintros h ⟨x, hx⟩ ⟨y, hy⟩ hxy, exact h hx hy (subtype.mk_eq_mk.not.mp hxy) end lemma pairwise_subtype_iff_pairwise_finset (r : α → α → Prop) : pairwise (r on λ x : s, x) ↔ (s : set α).pairwise r := pairwise_subtype_iff_pairwise_finset' r id lemma pairwise_cons' {a : α} (ha : a ∉ s) (r : β → β → Prop) (f : α → β) : pairwise (r on λ a : s.cons a ha, f a) ↔ pairwise (r on λ a : s, f a) ∧ ∀ b ∈ s, r (f a) (f b) ∧ r (f b) (f a) := begin simp only [pairwise_subtype_iff_pairwise_finset', finset.coe_cons, set.pairwise_insert, finset.mem_coe, and.congr_right_iff], exact λ hsr, ⟨λ h b hb, h b hb $ by { rintro rfl, contradiction }, λ h b hb _, h b hb⟩, end lemma pairwise_cons {a : α} (ha : a ∉ s) (r : α → α → Prop) : pairwise (r on λ a : s.cons a ha, a) ↔ pairwise (r on λ a : s, a) ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_cons' ha r id end pairwise end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_refl : (equiv.refl α).finset_congr = equiv.refl _ := by { ext, simp } @[simp] lemma finset_congr_symm (e : α ≃ β) : e.finset_congr.symm = e.symm.finset_congr := rfl @[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) : e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr := by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] } lemma finset_congr_to_embedding (e : α ≃ β) : e.finset_congr.to_embedding = (finset.map_embedding e.to_embedding).to_embedding := rfl /-- Inhabited types are equivalent to `option β` for some `β` by identifying `default α` with `none`. -/ def sigma_equiv_option_of_inhabited (α : Type u) [inhabited α] [decidable_eq α] : Σ (β : Type u), α ≃ option β := ⟨{x : α // x ≠ default}, { to_fun := λ (x : α), if h : x = default then none else some ⟨x, h⟩, inv_fun := option.elim default coe, left_inv := λ x, by { dsimp only, split_ifs; simp [*] }, right_inv := begin rintro (_|⟨x,h⟩), { simp }, { dsimp only, split_ifs with hi, { simpa [h] using hi }, { simp } } end }⟩ end equiv namespace multiset variable [decidable_eq α] lemma disjoint_to_finset {m1 m2 : multiset α} : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, refine ⟨λ h a ha1 ha2, _, _⟩, { rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset namespace list variables [decidable_eq α] {l l' : list α} lemma disjoint_to_finset_iff_disjoint : _root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' := multiset.disjoint_to_finset end list
8d5bc7ad57d9ef40c9e9988ddc694dc625c8391c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/order/t5.lean
14ac6d4ad9c254459bb17755bcc2c59e7cc4f6a1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,449
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.order.basic import data.set.intervals.ord_connected_component /-! # Linear order is a completely normal Hausdorff topological space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that a linear order with order topology is a completely normal Hausdorff topological space. -/ open filter set function order_dual open_locale topology filter interval variables {X : Type*} [linear_order X] [topological_space X] [order_topology X] {a b c : X} {s t : set X} namespace set @[simp] lemma ord_connected_component_mem_nhds : ord_connected_component s a ∈ 𝓝 a ↔ s ∈ 𝓝 a := begin refine ⟨λ h, mem_of_superset h ord_connected_component_subset, λ h, _⟩, rcases exists_Icc_mem_subset_of_mem_nhds h with ⟨b, c, ha, ha', hs⟩, exact mem_of_superset ha' (subset_ord_connected_component ha hs) end lemma compl_section_ord_separating_set_mem_nhds_within_Ici (hd : disjoint s (closure t)) (ha : a ∈ s) : (ord_connected_section $ ord_separating_set s t)ᶜ ∈ 𝓝[≥] a := begin have hmem : tᶜ ∈ 𝓝[≥] a, { refine mem_nhds_within_of_mem_nhds _, rw [← mem_interior_iff_mem_nhds, interior_compl], exact disjoint_left.1 hd ha }, rcases exists_Icc_mem_subset_of_mem_nhds_within_Ici hmem with ⟨b, hab, hmem', hsub⟩, by_cases H : disjoint (Icc a b) (ord_connected_section $ ord_separating_set s t), { exact mem_of_superset hmem' (disjoint_left.1 H) }, { simp only [set.disjoint_left, not_forall, not_not] at H, rcases H with ⟨c, ⟨hac, hcb⟩, hc⟩, have hsub' : Icc a b ⊆ ord_connected_component tᶜ a, from subset_ord_connected_component (left_mem_Icc.2 hab) hsub, replace hac : a < c := hac.lt_of_ne (ne.symm $ ne_of_mem_of_not_mem hc $ disjoint_left.1 (disjoint_left_ord_separating_set.mono_right ord_connected_section_subset) ha), refine mem_of_superset (Ico_mem_nhds_within_Ici (left_mem_Ico.2 hac)) (λ x hx hx', _), refine hx.2.ne (eq_of_mem_ord_connected_section_of_uIcc_subset hx' hc _), refine subset_inter (subset_Union₂_of_subset a ha _) _, { exact ord_connected.uIcc_subset infer_instance (hsub' ⟨hx.1, hx.2.le.trans hcb⟩) (hsub' ⟨hac.le, hcb⟩) }, { rcases mem_Union₂.1 (ord_connected_section_subset hx').2 with ⟨y, hyt, hxy⟩, refine subset_Union₂_of_subset y hyt (ord_connected.uIcc_subset infer_instance hxy _), refine subset_ord_connected_component left_mem_uIcc hxy _, suffices : c < y, { rw [uIcc_of_ge (hx.2.trans this).le], exact ⟨hx.2.le, this.le⟩ }, refine lt_of_not_le (λ hyc, _), have hya : y < a, from not_le.1 (λ hay, hsub ⟨hay, hyc.trans hcb⟩ hyt), exact hxy (Icc_subset_uIcc ⟨hya.le, hx.1⟩) ha } } end lemma compl_section_ord_separating_set_mem_nhds_within_Iic (hd : disjoint s (closure t)) (ha : a ∈ s) : (ord_connected_section $ ord_separating_set s t)ᶜ ∈ 𝓝[≤] a := have hd' : disjoint (of_dual ⁻¹' s) (closure $ of_dual ⁻¹' t) := hd, have ha' : to_dual a ∈ of_dual ⁻¹' s := ha, by simpa only [dual_ord_separating_set, dual_ord_connected_section] using compl_section_ord_separating_set_mem_nhds_within_Ici hd' ha' lemma compl_section_ord_separating_set_mem_nhds (hd : disjoint s (closure t)) (ha : a ∈ s) : (ord_connected_section $ ord_separating_set s t)ᶜ ∈ 𝓝 a := begin rw [← nhds_left_sup_nhds_right, mem_sup], exact ⟨compl_section_ord_separating_set_mem_nhds_within_Iic hd ha, compl_section_ord_separating_set_mem_nhds_within_Ici hd ha⟩ end lemma ord_t5_nhd_mem_nhds_set (hd : disjoint s (closure t)) : ord_t5_nhd s t ∈ 𝓝ˢ s := bUnion_mem_nhds_set $ λ x hx, ord_connected_component_mem_nhds.2 $ inter_mem (by { rw [← mem_interior_iff_mem_nhds, interior_compl], exact disjoint_left.1 hd hx }) (compl_section_ord_separating_set_mem_nhds hd hx) end set open set /-- A linear order with order topology is a completely normal Hausdorff topological space. -/ @[priority 100] instance order_topology.t5_space : t5_space X := ⟨λ s t h₁ h₂, filter.disjoint_iff.2 ⟨ord_t5_nhd s t, ord_t5_nhd_mem_nhds_set h₂, ord_t5_nhd t s, ord_t5_nhd_mem_nhds_set h₁.symm, disjoint_ord_t5_nhd⟩⟩
d35ff0564094313588dcbe4aeabf37a4e26cbafe
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/rational_root.lean
eb7120cabc7ce29fb4dd93bd9a946cb5a73948c1
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,908
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.polynomial.scale_roots import Mathlib.ring_theory.localization import Mathlib.PostPort universes u_1 u_4 u_2 namespace Mathlib /-! # Rational root theorem and integral root theorem This file contains the rational root theorem and integral root theorem. The rational root theorem for a unique factorization domain `A` with localization `S`, states that the roots of `p : polynomial A` in `A`'s field of fractions are of the form `x / y` with `x y : A`, `x ∣ p.coeff 0` and `y ∣ p.leading_coeff`. The corollary is the integral root theorem `is_integer_of_is_root_of_monic`: if `p` is monic, its roots must be integers. Finally, we use this to show unique factorization domains are integrally closed. ## References * https://en.wikipedia.org/wiki/Rational_root_theorem -/ theorem scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero {A : Type u_1} {S : Type u_4} [integral_domain A] [comm_ring S] {M : submonoid A} {f : localization_map M S} {p : polynomial A} {r : A} {s : ↥M} (hr : coe_fn (polynomial.aeval (localization_map.mk' f r s)) p = 0) : coe_fn (polynomial.aeval (coe_fn (localization_map.to_map f) r)) (scale_roots p ↑s) = 0 := sorry theorem num_is_root_scale_roots_of_aeval_eq_zero {A : Type u_1} {K : Type u_2} [integral_domain A] [field K] [unique_factorization_monoid A] (g : fraction_map A K) {p : polynomial A} {x : localization_map.codomain g} (hr : coe_fn (polynomial.aeval x) p = 0) : polynomial.is_root (scale_roots p ↑(fraction_map.denom g x)) (fraction_map.num g x) := sorry /-- Rational root theorem part 1: if `r : f.codomain` is a root of a polynomial over the ufd `A`, then the numerator of `r` divides the constant coefficient -/ theorem num_dvd_of_is_root {A : Type u_1} {K : Type u_2} [integral_domain A] [unique_factorization_monoid A] [field K] {f : fraction_map A K} {p : polynomial A} {r : localization_map.codomain f} (hr : coe_fn (polynomial.aeval r) p = 0) : fraction_map.num f r ∣ polynomial.coeff p 0 := sorry /-- Rational root theorem part 2: if `r : f.codomain` is a root of a polynomial over the ufd `A`, then the denominator of `r` divides the leading coefficient -/ theorem denom_dvd_of_is_root {A : Type u_1} {K : Type u_2} [integral_domain A] [unique_factorization_monoid A] [field K] {f : fraction_map A K} {p : polynomial A} {r : localization_map.codomain f} (hr : coe_fn (polynomial.aeval r) p = 0) : ↑(fraction_map.denom f r) ∣ polynomial.leading_coeff p := sorry /-- Integral root theorem: if `r : f.codomain` is a root of a monic polynomial over the ufd `A`, then `r` is an integer -/ theorem is_integer_of_is_root_of_monic {A : Type u_1} {K : Type u_2} [integral_domain A] [unique_factorization_monoid A] [field K] {f : fraction_map A K} {p : polynomial A} (hp : polynomial.monic p) {r : localization_map.codomain f} (hr : coe_fn (polynomial.aeval r) p = 0) : localization_map.is_integer f r := fraction_map.is_integer_of_is_unit_denom f (is_unit_of_dvd_one (↑(fraction_map.denom f r)) (hp ▸ denom_dvd_of_is_root hr)) namespace unique_factorization_monoid theorem integer_of_integral {A : Type u_1} {K : Type u_2} [integral_domain A] [unique_factorization_monoid A] [field K] {f : fraction_map A K} {x : localization_map.codomain f} : is_integral A x → localization_map.is_integer f x := sorry theorem integrally_closed {A : Type u_1} {K : Type u_2} [integral_domain A] [unique_factorization_monoid A] [field K] {f : fraction_map A K} : integral_closure A (localization_map.codomain f) = ⊥ := iff.mpr eq_bot_iff fun (x : localization_map.codomain f) (hx : x ∈ ↑(integral_closure A (localization_map.codomain f))) => iff.mpr algebra.mem_bot (integer_of_integral hx)
be0bee8111714db0e94abcfa38401cba4aa41bf5
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/old_demos_4-8/expressions_demo_current.lean
8c678caf1f09be111c3b38a5afe0de448f728450
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
2,113
lean
import ..eval.time_expr_current /- Adapted from Dr Sullivan's phys/demo/demo.lean to highlight differences from phys and lang -/ open lang.time --Alias std time frame and space def std_fr : time_frame_expr ℚ := [(time_std_frame ℚ)] --(std_frame ℚ TIME) def std_sp : time_space_expr std_fr.value := [(time_std_space ℚ)] --(std_space ℚ TIME) /- Use of new notation -/ def launch_time : time_expr std_sp.value := [(mk_time std_sp.value 0)] def one_second := [(mk_duration std_sp.value 1)] -- TODO: Introduce concrete syntax notations /- Frame definition updated with embedding into expression -/ def mission_frame : time_frame_expr ℚ := mk_time_frame_expr ℚ launch_time one_second /- Construct a new space with this frame def mission_time := mk_space ℚ (time_frame) -/ /- Space definition updated with embedding into expression -/ def mission_space := [(mk_space ℚ mission_frame.value)] /- Define new times and durations in terms of this new frame, demonstrate -/ def ego_launch_time : time_expr mission_space.value := [(mk_time mission_space.value 0)] def one_minute : duration_expr mission_space.value := [(mk_duration mission_space.value 60)] def t_plus_one_minute' : _ := one_minute +ᵥ ego_launch_time -- coordinate free in coordinate space def t_plus_one_second : _ := one_second +ᵥ ego_launch_time -- frame error --build a transform def std_to_mission : transform_expr std_sp.value mission_space.value --type := let std_lit := std_sp.value in let mission_lit := mission_space.value in [(std_lit.time_tr mission_lit)] --value --transform original launch_time point in std_space to mission space def launch_time_in_time_frame : time_expr mission_space.value := [(std_to_mission.value.transform_time launch_time.value)] def mission_to_std : transform_expr mission_space.value std_sp.value := [(mission_space.value.time_tr std_sp.value)] --cannot deeply embed this due to type limitations def std_to_std_compose := transform_expr.compose_lit std_to_mission.value mission_to_std.value
efb6dc717a46e09f0caf9cdc1d17875ede9b66a1
66a6486e19b71391cc438afee5f081a4257564ec
/homotopy/susp.hlean
6696f6c1eec3bf9ef10e65aada69cab5aa20af60
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
3,075
hlean
import homotopy.susp types.pointed2 ..move_to_lib open susp eq pointed function is_equiv lift equiv is_trunc nat namespace susp variables {X X' Y Y' Z : Type*} definition iterate_susp_iterate_susp_rev (n m : ℕ) (A : Type*) : iterate_susp n (iterate_susp m A) ≃* iterate_susp (m + n) A := begin induction n with n e, { reflexivity }, { exact susp_pequiv e } end definition iterate_susp_pequiv [constructor] (n : ℕ) {X Y : Type*} (f : X ≃* Y) : iterate_susp n X ≃* iterate_susp n Y := begin induction n with n e, { exact f }, { exact susp_pequiv e } end open algebra nat definition iterate_susp_iterate_susp (n m : ℕ) (A : Type*) : iterate_susp n (iterate_susp m A) ≃* iterate_susp (n + m) A := iterate_susp_iterate_susp_rev n m A ⬝e* pequiv_of_eq (ap (λk, iterate_susp k A) (add.comm m n)) definition plift_susp.{u v} : Π(A : Type*), plift.{u v} (susp A) ≃* susp (plift.{u v} A) := begin intro A, calc plift.{u v} (susp A) ≃* susp A : by exact (pequiv_plift (susp A))⁻¹ᵉ* ... ≃* susp (plift.{u v} A) : by exact susp_pequiv (pequiv_plift.{u v} A) end definition is_contr_susp [instance] (A : Type) [H : is_contr A] : is_contr (susp A) := begin apply is_contr.mk north, intro x, induction x, reflexivity, exact merid !center, apply eq_pathover_constant_left_id_right, apply square_of_eq, exact whisker_left idp (ap merid !eq_of_is_contr) end definition loop_susp_pintro_phomotopy {X Y : Type*} {f g : ⅀ X →* Y} (p : f ~* g) : loop_susp_pintro X Y f ~* loop_susp_pintro X Y g := pwhisker_right (loop_susp_unit X) (Ω⇒ p) variables {A₀₀ A₂₀ A₀₂ A₂₂ : Type*} {f₁₀ : A₀₀ →* A₂₀} {f₁₂ : A₀₂ →* A₂₂} {f₀₁ : A₀₀ →* A₀₂} {f₂₁ : A₂₀ →* A₂₂} -- rename: susp_functor_psquare definition suspend_psquare (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : psquare (⅀→ f₁₀) (⅀→ f₁₂) (⅀→ f₀₁) (⅀→ f₂₁) := sorry definition susp_to_loop_psquare (f₁₀ : A₀₀ →* A₂₀) (f₁₂ : A₀₂ →* A₂₂) (f₀₁ : susp A₀₀ →* A₀₂) (f₂₁ : susp A₂₀ →* A₂₂) : (psquare (⅀→ f₁₀) f₁₂ f₀₁ f₂₁) → (psquare f₁₀ (Ω→ f₁₂) ((loop_susp_pintro A₀₀ A₀₂) f₀₁) ((loop_susp_pintro A₂₀ A₂₂) f₂₁)) := begin intro p, refine pvconcat _ (ap1_psquare p), exact loop_susp_unit_natural f₁₀ end definition loop_to_susp_square (f₁₀ : A₀₀ →* A₂₀) (f₁₂ : A₀₂ →* A₂₂) (f₀₁ : A₀₀ →* Ω A₀₂) (f₂₁ : A₂₀ →* Ω A₂₂) : (psquare f₁₀ (Ω→ f₁₂) f₀₁ f₂₁) → (psquare (⅀→ f₁₀) f₁₂ ((susp_pelim A₀₀ A₀₂) f₀₁) ((susp_pelim A₂₀ A₂₂) f₂₁)) := begin intro p, refine pvconcat (suspend_psquare p) _, exact psquare_transpose (loop_susp_counit_natural f₁₂) end end susp
131aa8b5a618c0cbbc65547f381653217bcfc94d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/real/order.lean
3a032a9260210a18d9a2254dbd75f53f6ee5ca21
[ "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
38,871
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). To do: o Rename things and possibly make theorems private -/ import data.real.basic data.rat data.nat open rat nat eq pnat local postfix `⁻¹` := pnat.inv local attribute real.real_has_zero [instance, priority real.prio] local attribute real.real_has_one [instance, priority real.prio] namespace rat_seq definition pos (s : seq) := ∃ n : ℕ+, n⁻¹ < (s n) definition nonneg (s : seq) := ∀ n : ℕ+, -(n⁻¹) ≤ s n theorem sub_sub_comm (a b c : ℚ) : a - b - c = a - c - b := by rewrite [+sub_eq_add_neg, add.assoc, {-b+_}add.comm, -add.assoc] theorem bdd_away_of_pos {s : seq} (Hs : regular s) (H : pos s) : ∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → (s n) ≥ N⁻¹ := begin cases H with [n, Hn], cases sep_by_inv Hn with [N, HN], existsi N, intro m Hm, have Habs : abs (s m - s n) ≥ s n - s m, by rewrite abs_sub; apply le_abs_self, have Habs' : s m + abs (s m - s n) ≥ s n, from (iff.mpr (le_add_iff_sub_left_le _ _ _)) Habs, have HN' : N⁻¹ + N⁻¹ ≤ s n - n⁻¹, begin rewrite sub_eq_add_neg, apply iff.mpr (le_add_iff_sub_right_le _ _ _), rewrite [sub_neg_eq_add, add.comm, -add.assoc], apply le_of_lt HN end, rewrite add.comm at Habs', have Hin : s m ≥ N⁻¹, from calc s m ≥ s n - abs (s m - s n) : (iff.mp (le_add_iff_sub_left_le _ _ _)) Habs' ... ≥ s n - (m⁻¹ + n⁻¹) : sub_le_sub_left !Hs ... = s n - m⁻¹ - n⁻¹ : by rewrite sub_add_eq_sub_sub ... = s n - n⁻¹ - m⁻¹ : by rewrite sub_sub_comm ... ≥ s n - n⁻¹ - N⁻¹ : sub_le_sub_left (inv_ge_of_le Hm) ... ≥ N⁻¹ + N⁻¹ - N⁻¹ : sub_le_sub_right HN' ... = N⁻¹ : by rewrite add_sub_cancel, apply Hin end theorem pos_of_bdd_away {s : seq} (H : ∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → (s n) ≥ N⁻¹) : pos s := begin cases H with [N, HN], existsi (N + pone), apply lt_of_lt_of_le, apply inv_add_lt_left, apply HN, apply pnat.le_of_lt, apply lt_add_left end theorem bdd_within_of_nonneg {s : seq} (Hs : regular s) (H : nonneg s) : ∀ n : ℕ+, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → s m ≥ -n⁻¹ := begin intros, existsi n, intro m Hm, apply le.trans, apply neg_le_neg, apply inv_ge_of_le, apply Hm, apply H end theorem nonneg_of_bdd_within {s : seq} (Hs : regular s) (H : ∀n : ℕ+, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → s m ≥ -n⁻¹) : nonneg s := begin rewrite ↑nonneg, intro k, apply ge_of_forall_ge_sub, intro ε Hε, cases H (pceil ((2) / ε)) with [N, HN], apply le.trans, rotate 1, apply sub_le_of_abs_sub_le_left, apply Hs, apply (max (pceil ((2)/ε)) N), rewrite [+sub_eq_add_neg, neg_add, {_ + (-k⁻¹ + _)}add.comm, *add.assoc], apply rat.add_le_add_left, apply le.trans, rotate 1, apply add_le_add, rotate 1, apply HN (max (pceil ((2)/ε)) N) !pnat.max_right, rotate_right 1, apply neg_le_neg, apply inv_ge_of_le, apply pnat.max_left, rewrite -neg_add, apply neg_le_neg, apply le.trans, apply add_le_add, repeat (apply inv_pceil_div; apply add_pos; repeat apply zero_lt_one; exact Hε), rewrite [add_halves], apply rat.le_refl end theorem pos_of_pos_equiv {s t : seq} (Hs : regular s) (Heq : s ≡ t) (Hp : pos s) : pos t := begin cases (bdd_away_of_pos Hs Hp) with [N, HN], existsi 2 * 2 * N, apply lt_of_lt_of_le, rotate 1, apply sub_le_of_abs_sub_le_right, apply Heq, have Hs4 : N⁻¹ ≤ s (2 * 2 * N), from HN _ (!pnat.mul_le_mul_left), apply lt_of_lt_of_le, rotate 1, rewrite sub_eq_add_neg, apply iff.mpr !add_le_add_right_iff, apply Hs4, rewrite [*pnat.mul_assoc, pnat.add_halves, -(pnat.add_halves N), -sub_eq_add_neg, add_sub_cancel], apply inv_two_mul_lt_inv end theorem nonneg_of_nonneg_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) (Hp : nonneg s) : nonneg t := begin apply nonneg_of_bdd_within, apply Ht, intros, cases bdd_within_of_nonneg Hs Hp (2 * 2 * n) with [Ns, HNs], existsi max Ns (2 * 2 * n), intro m Hm, apply le.trans, rotate 1, apply sub_le_of_abs_sub_le_right, apply Heq, apply le.trans, rotate 1, apply sub_le_sub_right, apply HNs, apply pnat.le_trans, rotate 1, apply Hm, rotate_right 1, apply pnat.max_left, have Hms : m⁻¹ ≤ (2 * 2 * n)⁻¹, begin apply inv_ge_of_le, apply pnat.le_trans, rotate 1, apply Hm; apply pnat.max_right end, have Hms' : m⁻¹ + m⁻¹ ≤ (2 * 2 * n)⁻¹ + (2 * 2 * n)⁻¹, from add_le_add Hms Hms, apply le.trans, rotate 1, apply sub_le_sub_left, apply Hms', rewrite [*pnat.mul_assoc, pnat.add_halves, -neg_sub, -pnat.add_halves n, sub_neg_eq_add], apply neg_le_neg, apply add_le_add_left, apply inv_two_mul_le_inv end definition s_le (a b : seq) := nonneg (sadd b (sneg a)) definition s_lt (a b : seq) := pos (sadd b (sneg a)) theorem zero_nonneg : nonneg zero := begin intros, apply neg_nonpos_of_nonneg, apply rat.le_of_lt, apply pnat.inv_pos end theorem s_zero_lt_one : s_lt zero one := begin rewrite [↑s_lt, ↑zero, ↑sadd, ↑sneg, ↑one, neg_zero, add_zero, ↑pos], existsi 2, apply inv_lt_one_of_gt, apply one_lt_two end protected theorem le_refl {s : seq} (Hs : regular s) : s_le s s := begin apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply neg_s_cancel s Hs, apply zero_nonneg, apply zero_is_reg, apply reg_add_reg Hs (reg_neg_reg Hs) end theorem s_nonneg_of_pos {s : seq} (Hs : regular s) (H : pos s) : nonneg s := begin apply nonneg_of_bdd_within, apply Hs, intros, cases bdd_away_of_pos Hs H with [N, HN], existsi N, intro m Hm, apply le.trans, rotate 1, apply HN, apply Hm, apply le.trans, rotate 1, apply rat.le_of_lt, apply pnat.inv_pos, rewrite -neg_zero, apply neg_le_neg, apply rat.le_of_lt, apply pnat.inv_pos end theorem s_le_of_s_lt {s t : seq} (Hs : regular s) (Ht : regular t) (H : s_lt s t) : s_le s t := begin rewrite [↑s_le, ↑s_lt at *], apply s_nonneg_of_pos, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end theorem s_neg_add_eq_s_add_neg (s t : seq) : sneg (sadd s t) ≡ sadd (sneg s) (sneg t) := begin rewrite [↑equiv, ↑sadd, ↑sneg], intros, rewrite [neg_add, sub_self, abs_zero], apply add_invs_nonneg end theorem equiv_cancel_middle {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : sadd (sadd u t) (sneg (sadd u s)) ≡ sadd t (sneg s) := begin note Hz := zero_is_reg, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply s_add_comm, apply s_neg_add_eq_s_add_neg, apply equiv.trans, rotate 3, apply s_add_assoc, rotate 2, apply add_well_defined, rotate 4, apply equiv.refl, apply equiv.trans, rotate 4, apply equiv.refl, rotate_right 1, apply equiv.trans, rotate 3, apply equiv.symm, apply s_add_assoc, rotate 2, apply equiv.trans, rotate 4, apply s_zero_add, rotate_right 1, apply add_well_defined, rotate 4, apply neg_s_cancel, rotate 1, apply equiv.refl, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end protected theorem add_le_add_of_le_right {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_le s t) : ∀ u : seq, regular u → s_le (sadd u s) (sadd u t) := begin intro u Hu, rewrite [↑s_le at *], apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply equiv_cancel_middle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end theorem s_add_lt_add_left {s t : seq} (Hs : regular s) (Ht : regular t) (Hst : s_lt s t) {u : seq} (Hu : regular u) : s_lt (sadd u s) (sadd u t) := begin rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 1, apply equiv.symm, apply equiv_cancel_middle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end protected theorem add_nonneg_of_nonneg {s t : seq} (Hs : nonneg s) (Ht : nonneg t) : nonneg (sadd s t) := begin intros, rewrite [-pnat.add_halves, neg_add], apply add_le_add, apply Hs, apply Ht end protected theorem le_trans {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Lst : s_le s t) (Ltu : s_le t u) : s_le s u := begin rewrite ↑s_le at *, note Rz := zero_is_reg, have Hsum : nonneg (sadd (sadd u (sneg t)) (sadd t (sneg s))), from rat_seq.add_nonneg_of_nonneg Ltu Lst, have H' : nonneg (sadd (sadd u (sadd (sneg t) t)) (sneg s)), begin apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply s_add_assoc, repeat (apply reg_add_reg | apply reg_neg_reg | assumption), apply equiv.refl, apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply s_add_assoc, rotate 2, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end, have H'' : sadd (sadd u (sadd (sneg t) t)) (sneg s) ≡ sadd u (sneg s), begin apply add_well_defined, rotate 4, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_cancel, rotate 1, apply s_add_zero, rotate 1, apply equiv.refl, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end, apply nonneg_of_nonneg_equiv, rotate 2, apply H'', apply H', repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end theorem equiv_of_le_of_ge {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_le s t) (Lts : s_le t s) : s ≡ t := begin apply equiv_of_diff_equiv_zero, rotate 2, rewrite [↑s_le at *, ↑nonneg at *, ↑equiv, ↑sadd at *, ↑sneg at *], intros, rewrite [↑zero, sub_zero], apply abs_le_of_le_of_neg_le, apply le_of_neg_le_neg, rewrite [2 neg_add, neg_neg], apply rat.le_trans, apply neg_add_neg_le_neg_of_pos, apply pnat.inv_pos, rewrite add.comm, apply Lst, apply le_of_neg_le_neg, rewrite [neg_add, neg_neg], apply rat.le_trans, apply neg_add_neg_le_neg_of_pos, apply pnat.inv_pos, apply Lts, repeat assumption end definition sep (s t : seq) := s_lt s t ∨ s_lt t s local infix `≢` : 50 := sep theorem le_and_sep_of_lt {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_lt s t) : s_le s t ∧ sep s t := begin apply and.intro, intros, cases Lst with [N, HN], let Rns := reg_neg_reg Hs, let Rtns := reg_add_reg Ht Rns, note Habs := sub_le_of_abs_sub_le_right (Rtns N n), rewrite [sub_add_eq_sub_sub at Habs], exact (calc sadd t (sneg s) n ≥ sadd t (sneg s) N - N⁻¹ - n⁻¹ : Habs ... ≥ 0 - n⁻¹: begin apply sub_le_sub_right, apply rat.le_of_lt, apply (iff.mpr (sub_pos_iff_lt _ _)), apply HN end ... = -n⁻¹ : by rewrite zero_sub), exact or.inl Lst end theorem lt_of_le_and_sep {s t : seq} (Hs : regular s) (Ht : regular t) (H : s_le s t ∧ sep s t) : s_lt s t := begin note Le := and.left H, cases and.right H with [P, Hlt], exact P, rewrite [↑s_le at Le, ↑nonneg at Le, ↑s_lt at Hlt, ↑pos at Hlt], apply exists.elim Hlt, intro N HN, let LeN := Le N, note HN' := (iff.mpr !neg_lt_neg_iff_lt) HN, rewrite [↑sadd at HN', ↑sneg at HN', neg_add at HN', neg_neg at HN', add.comm at HN'], let HN'' := not_le_of_gt HN', apply absurd LeN HN'' end theorem lt_iff_le_and_sep {s t : seq} (Hs : regular s) (Ht : regular t) : s_lt s t ↔ s_le s t ∧ sep s t := iff.intro (le_and_sep_of_lt Hs Ht) (lt_of_le_and_sep Hs Ht) theorem s_neg_zero : sneg zero ≡ zero := begin rewrite ↑[sneg, zero, equiv], intros, rewrite [sub_zero, abs_neg, abs_zero], apply add_invs_nonneg end theorem s_sub_zero {s : seq} (Hs : regular s) : sadd s (sneg zero) ≡ s := begin apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_zero, apply s_add_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end theorem s_pos_of_gt_zero {s : seq} (Hs : regular s) (Hgz : s_lt zero s) : pos s := begin rewrite [↑s_lt at *], apply pos_of_pos_equiv, rotate 1, apply s_sub_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg), apply zero_is_reg end theorem s_gt_zero_of_pos {s : seq} (Hs : regular s) (Hp : pos s) : s_lt zero s := begin rewrite ↑s_lt, apply pos_of_pos_equiv, rotate 1, apply equiv.symm, apply s_sub_zero, repeat assumption end theorem s_nonneg_of_ge_zero {s : seq} (Hs : regular s) (Hgz : s_le zero s) : nonneg s := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply s_sub_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end theorem s_ge_zero_of_nonneg {s : seq} (Hs : regular s) (Hn : nonneg s) : s_le zero s := begin rewrite ↑s_le, apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply s_sub_zero, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end theorem s_mul_pos_of_pos {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : pos s) (Hpt : pos t) : pos (smul s t) := begin rewrite [↑pos at *], cases bdd_away_of_pos Hs Hps with [Ns, HNs], cases bdd_away_of_pos Ht Hpt with [Nt, HNt], existsi 2 * max Ns Nt * max Ns Nt, rewrite ↑smul, apply lt_of_lt_of_le, rotate 1, apply mul_le_mul, apply HNs, apply pnat.le_trans, apply pnat.max_left Ns Nt, rewrite -pnat.mul_assoc, apply pnat.mul_le_mul_left, apply HNt, apply pnat.le_trans, apply pnat.max_right Ns Nt, rewrite -pnat.mul_assoc, apply pnat.mul_le_mul_left, apply rat.le_of_lt, apply pnat.inv_pos, apply rat.le_trans, rotate 1, apply HNs, apply pnat.le_trans, apply pnat.max_left Ns Nt, rewrite -pnat.mul_assoc, apply pnat.mul_le_mul_left, rewrite pnat.inv_mul_eq_mul_inv, apply mul_lt_mul, rewrite [pnat.inv_mul_eq_mul_inv, -one_mul Ns⁻¹], apply mul_lt_mul, apply inv_lt_one_of_gt, apply dec_trivial, apply inv_ge_of_le, apply pnat.max_left, apply pnat.inv_pos, apply rat.le_of_lt zero_lt_one, apply inv_ge_of_le, apply pnat.max_right, apply pnat.inv_pos, repeat (apply le_of_lt; apply pnat.inv_pos) end theorem s_mul_gt_zero_of_gt_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Hzs : s_lt zero s) (Hzt : s_lt zero t) : s_lt zero (smul s t) := s_gt_zero_of_pos (reg_mul_reg Hs Ht) (s_mul_pos_of_pos Hs Ht (s_pos_of_gt_zero Hs Hzs) (s_pos_of_gt_zero Ht Hzt)) theorem le_of_lt_or_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (Hor : (s_lt s t) ∨ (s ≡ t)) : s_le s t := or.elim Hor (begin intro Hlt, apply s_le_of_s_lt Hs Ht Hlt end) (begin intro Heq, rewrite ↑s_le, apply nonneg_of_nonneg_equiv, rotate 3, apply zero_nonneg, apply zero_is_reg, apply reg_add_reg Ht (reg_neg_reg Hs), apply equiv.symm, apply diff_equiv_zero_of_equiv, rotate 2, apply equiv.symm, apply Heq, repeat assumption end) theorem s_zero_mul {s : seq} : smul s zero ≡ zero := begin rewrite [↑equiv, ↑smul, ↑zero], intros, rewrite [mul_zero, sub_zero, abs_zero], apply add_invs_nonneg end theorem s_mul_nonneg_of_pos_of_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : pos s) (Hpt : zero ≡ t) : nonneg (smul s t) := begin apply nonneg_of_nonneg_equiv, rotate 2, apply mul_well_defined, rotate 4, apply equiv.refl, apply Hpt, apply nonneg_of_nonneg_equiv, rotate 2, apply equiv.symm, apply s_zero_mul, apply zero_nonneg, repeat (assumption | apply reg_mul_reg | apply zero_is_reg) end theorem s_mul_nonneg_of_nonneg {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : nonneg s) (Hpt : nonneg t) : nonneg (smul s t) := begin intro n, rewrite ↑smul, apply rat.le_by_cases 0 (s (((K₂ s t) * 2) * n)), intro Hsp, apply rat.le_by_cases 0 (t (((K₂ s t) * 2) * n)), intro Htp, apply rat.le_trans, rotate 1, apply rat.mul_nonneg Hsp Htp, rotate_right 1, apply le_of_lt, apply neg_neg_of_pos, apply pnat.inv_pos, intro Htn, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonpos_right, apply rat.le_trans, apply le_abs_self, apply canon_2_bound_left s t Hs, apply Htn, rotate_right 1, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonneg_left, apply Hpt, apply le_of_lt, apply rat_of_pnat_is_pos, rotate 1, rewrite -neg_mul_eq_mul_neg, apply neg_le_neg, rewrite [*pnat.mul_assoc, pnat.inv_mul_eq_mul_inv, -mul.assoc, pnat.inv_cancel_left, one_mul], apply inv_ge_of_le, apply pnat.mul_le_mul_left, intro Hsn, apply rat.le_by_cases 0 (t (((K₂ s t) * 2) * n)), intro Htp, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonpos_left, apply rat.le_trans, apply le_abs_self, apply canon_2_bound_right s t Ht, apply Hsn, rotate_right 1, apply rat.le_trans, rotate 1, apply mul_le_mul_of_nonneg_right, apply Hps, apply le_of_lt, apply rat_of_pnat_is_pos, rotate 1, rewrite -neg_mul_eq_neg_mul, apply neg_le_neg, rewrite [+pnat.mul_assoc, pnat.inv_mul_eq_mul_inv, mul.comm, -mul.assoc, pnat.inv_cancel_left, one_mul], apply inv_ge_of_le, apply pnat.mul_le_mul_left, intro Htn, apply le.trans, rotate 1, apply mul_nonneg_of_nonpos_of_nonpos, apply Hsn, apply Htn, apply le_of_lt, apply neg_neg_of_pos, apply pnat.inv_pos end theorem s_mul_ge_zero_of_ge_zero {s t : seq} (Hs : regular s) (Ht : regular t) (Hzs : s_le zero s) (Hzt : s_le zero t) : s_le zero (smul s t) := begin note Hzs' := s_nonneg_of_ge_zero Hs Hzs, note Htz' := s_nonneg_of_ge_zero Ht Hzt, apply s_ge_zero_of_nonneg, rotate 1, apply s_mul_nonneg_of_nonneg, repeat assumption, apply reg_mul_reg Hs Ht end protected theorem not_lt_self (s : seq) : ¬ s_lt s s := begin intro Hlt, rewrite [↑s_lt at Hlt, ↑pos at Hlt], apply exists.elim Hlt, intro n Hn, esimp at Hn, rewrite [↑sadd at Hn,↑sneg at Hn, -sub_eq_add_neg at Hn, sub_self at Hn], apply absurd Hn (not_lt_of_ge (rat.le_of_lt !pnat.inv_pos)) end theorem not_sep_self (s : seq) : ¬ s ≢ s := begin intro Hsep, rewrite ↑sep at Hsep, let Hsep' := (iff.mp !or_self) Hsep, apply absurd Hsep' (!rat_seq.not_lt_self) end theorem le_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Hsu : s ≡ u) (Htv : t ≡ v) : s_le s t ↔ s_le u v := iff.intro (begin intro Hle, rewrite [↑s_le at *], apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply Htv, apply neg_well_defined, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) (begin intro Hle, rewrite [↑s_le at *], apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply equiv.symm, apply Htv, apply neg_well_defined, apply equiv.symm, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) theorem lt_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Hsu : s ≡ u) (Htv : t ≡ v) : s_lt s t ↔ s_lt u v := iff.intro (begin intro Hle, rewrite [↑s_lt at *], apply pos_of_pos_equiv, rotate 1, apply add_well_defined, rotate 4, apply Htv, apply neg_well_defined, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) (begin intro Hle, rewrite [↑s_lt at *], apply pos_of_pos_equiv, rotate 1, apply add_well_defined, rotate 4, apply equiv.symm, apply Htv, apply neg_well_defined, apply equiv.symm, apply Hsu, apply Hle, repeat (apply reg_add_reg | apply reg_neg_reg | assumption) end) theorem sep_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Hsu : s ≡ u) (Htv : t ≡ v) : s ≢ t ↔ u ≢ v := begin rewrite ↑sep, apply iff.intro, intro Hor, apply or.elim Hor, intro Hlt, apply or.inl, apply iff.mp (lt_well_defined Hs Ht Hu Hv Hsu Htv), assumption, intro Hlt, apply or.inr, apply iff.mp (lt_well_defined Ht Hs Hv Hu Htv Hsu), assumption, intro Hor, apply or.elim Hor, intro Hlt, apply or.inl, apply iff.mpr (lt_well_defined Hs Ht Hu Hv Hsu Htv), assumption, intro Hlt, apply or.inr, apply iff.mpr (lt_well_defined Ht Hs Hv Hu Htv Hsu), assumption end theorem s_lt_of_lt_of_le {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hst : s_lt s t) (Htu : s_le t u) : s_lt s u := begin let Rtns := reg_add_reg Ht (reg_neg_reg Hs), let Runt := reg_add_reg Hu (reg_neg_reg Ht), have Hcan : ∀ m, sadd u (sneg s) m = (sadd t (sneg s)) m + (sadd u (sneg t)) m, begin intro m, rewrite [↑sadd, ↑sneg, -*sub_eq_add_neg, -sub_eq_sub_add_sub] end, rewrite [↑s_lt at *, ↑s_le at *], cases bdd_away_of_pos Rtns Hst with [Nt, HNt], cases bdd_within_of_nonneg Runt Htu (2 * Nt) with [Nu, HNu], apply pos_of_bdd_away, existsi max (2 * Nt) Nu, intro n Hn, rewrite Hcan, apply rat.le_trans, rotate 1, apply add_le_add, apply HNt, apply pnat.le_trans, apply pnat.mul_le_mul_left 2, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_left, apply HNu, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, rewrite [-pnat.add_halves Nt, -sub_eq_add_neg, add_sub_cancel], apply inv_ge_of_le, apply pnat.max_left end theorem s_lt_of_le_of_lt {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hst : s_le s t) (Htu : s_lt t u) : s_lt s u := begin let Rtns := reg_add_reg Ht (reg_neg_reg Hs), let Runt := reg_add_reg Hu (reg_neg_reg Ht), have Hcan : ∀ m, sadd u (sneg s) m = (sadd t (sneg s)) m + (sadd u (sneg t)) m, begin intro m, rewrite [↑sadd, ↑sneg, -*sub_eq_add_neg, -sub_eq_sub_add_sub] end, rewrite [↑s_lt at *, ↑s_le at *], cases bdd_away_of_pos Runt Htu with [Nu, HNu], cases bdd_within_of_nonneg Rtns Hst (2 * Nu) with [Nt, HNt], apply pos_of_bdd_away, existsi max (2 * Nu) Nt, intro n Hn, rewrite Hcan, apply rat.le_trans, rotate 1, apply add_le_add, apply HNt, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, apply HNu, apply pnat.le_trans, apply pnat.mul_le_mul_left 2, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_left, rewrite [-pnat.add_halves Nu, neg_add_cancel_left], apply inv_ge_of_le, apply pnat.max_left end theorem le_of_le_reprs {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : ∀ n : ℕ+, s_le s (const (t n))) : s_le s t := by intro m; apply Hle (2 * m) m theorem le_of_reprs_le {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : ∀ n : ℕ+, s_le (const (t n)) s) : s_le t s := by intro m; apply Hle (2 * m) m ----------------------------- -- of_rat theorems theorem const_le_const_of_le {a b : ℚ} (H : a ≤ b) : s_le (const a) (const b) := begin rewrite [↑s_le, ↑nonneg], intro n, rewrite [↑sadd, ↑sneg, ↑const], apply le.trans, apply neg_nonpos_of_nonneg, apply rat.le_of_lt, apply pnat.inv_pos, apply iff.mpr !sub_nonneg_iff_le, apply H end theorem le_of_const_le_const {a b : ℚ} (H : s_le (const a) (const b)) : a ≤ b := begin rewrite [↑s_le at H, ↑nonneg at H, ↑sadd at H, ↑sneg at H, ↑const at H], apply iff.mp !sub_nonneg_iff_le, apply nonneg_of_ge_neg_invs _ H end theorem nat_inv_lt_rat {a : ℚ} (H : a > 0) : ∃ n : ℕ+, n⁻¹ < a := begin existsi (pceil (1 / (a / (2)))), apply lt_of_le_of_lt, rotate 1, apply div_two_lt_of_pos H, rewrite -(one_div_one_div (a / (1 + 1))), apply pceil_helper, apply pnat.le_refl, apply one_div_pos_of_pos, apply div_pos_of_pos_of_pos H dec_trivial end theorem const_lt_const_of_lt {a b : ℚ} (H : a < b) : s_lt (const a) (const b) := begin rewrite [↑s_lt, ↑pos, ↑sadd, ↑sneg, ↑const], apply nat_inv_lt_rat, apply (iff.mpr !sub_pos_iff_lt H) end theorem lt_of_const_lt_const {a b : ℚ} (H : s_lt (const a) (const b)) : a < b := begin rewrite [↑s_lt at H, ↑pos at H, ↑const at H, ↑sadd at H, ↑sneg at H], cases H with [n, Hn], apply (iff.mp !sub_pos_iff_lt), apply lt.trans, rotate 1, exact Hn, apply pnat.inv_pos end theorem s_le_of_le_pointwise {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ n : ℕ+, s n ≤ t n) : s_le s t := begin rewrite [↑s_le, ↑nonneg, ↑sadd, ↑sneg], intros, apply le.trans, apply iff.mpr !neg_nonpos_iff_nonneg, apply le_of_lt, apply pnat.inv_pos, apply iff.mpr !sub_nonneg_iff_le, apply H end -------- lift to reg_seqs definition r_lt (s t : reg_seq) := s_lt (reg_seq.sq s) (reg_seq.sq t) definition r_le (s t : reg_seq) := s_le (reg_seq.sq s) (reg_seq.sq t) definition r_sep (s t : reg_seq) := sep (reg_seq.sq s) (reg_seq.sq t) theorem r_le_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v) : r_le s t = r_le u v := propext (le_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) Hsu Htv) theorem r_lt_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v) : r_lt s t = r_lt u v := propext (lt_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) Hsu Htv) theorem r_sep_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v) : r_sep s t = r_sep u v := propext (sep_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) (reg_seq.is_reg v) Hsu Htv) theorem r_le.refl (s : reg_seq) : r_le s s := rat_seq.le_refl (reg_seq.is_reg s) theorem r_le.trans {s t u : reg_seq} (Hst : r_le s t) (Htu : r_le t u) : r_le s u := rat_seq.le_trans (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu theorem r_equiv_of_le_of_ge {s t : reg_seq} (Hs : r_le s t) (Hu : r_le t s) : requiv s t := equiv_of_le_of_ge (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Hu theorem r_lt_iff_le_and_sep (s t : reg_seq) : r_lt s t ↔ r_le s t ∧ r_sep s t := lt_iff_le_and_sep (reg_seq.is_reg s) (reg_seq.is_reg t) theorem r_add_le_add_of_le_right {s t : reg_seq} (H : r_le s t) (u : reg_seq) : r_le (u + s) (u + t) := rat_seq.add_le_add_of_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) H (reg_seq.sq u) (reg_seq.is_reg u) theorem r_add_le_add_of_le_right_var (s t u : reg_seq) (H : r_le s t) : r_le (u + s) (u + t) := r_add_le_add_of_le_right H u theorem r_mul_pos_of_pos {s t : reg_seq} (Hs : r_lt r_zero s) (Ht : r_lt r_zero t) : r_lt r_zero (s * t) := s_mul_gt_zero_of_gt_zero (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Ht theorem r_mul_nonneg_of_nonneg {s t : reg_seq} (Hs : r_le r_zero s) (Ht : r_le r_zero t) : r_le r_zero (s * t) := s_mul_ge_zero_of_ge_zero (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Ht theorem r_not_lt_self (s : reg_seq) : ¬ r_lt s s := rat_seq.not_lt_self (reg_seq.sq s) theorem r_not_sep_self (s : reg_seq) : ¬ r_sep s s := not_sep_self (reg_seq.sq s) theorem r_le_of_lt {s t : reg_seq} (H : r_lt s t) : r_le s t := s_le_of_s_lt (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_lt_of_le_of_lt {s t u : reg_seq} (Hst : r_le s t) (Htu : r_lt t u) : r_lt s u := s_lt_of_le_of_lt (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu theorem r_lt_of_lt_of_le {s t u : reg_seq} (Hst : r_lt s t) (Htu : r_le t u) : r_lt s u := s_lt_of_lt_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu theorem r_add_lt_add_left (s t : reg_seq) (H : r_lt s t) (u : reg_seq) : r_lt (u + s) (u + t) := s_add_lt_add_left (reg_seq.is_reg s) (reg_seq.is_reg t) H (reg_seq.is_reg u) theorem r_add_lt_add_left_var (s t u : reg_seq) (H : r_lt s t) : r_lt (u + s) (u + t) := r_add_lt_add_left s t H u theorem r_zero_lt_one : r_lt r_zero r_one := s_zero_lt_one theorem r_le_of_lt_or_eq (s t : reg_seq) (H : r_lt s t ∨ requiv s t) : r_le s t := le_of_lt_or_equiv (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_const_le_const_of_le {a b : ℚ} (H : a ≤ b) : r_le (r_const a) (r_const b) := const_le_const_of_le H theorem r_le_of_const_le_const {a b : ℚ} (H : r_le (r_const a) (r_const b)) : a ≤ b := le_of_const_le_const H theorem r_const_lt_const_of_lt {a b : ℚ} (H : a < b) : r_lt (r_const a) (r_const b) := const_lt_const_of_lt H theorem r_lt_of_const_lt_const {a b : ℚ} (H : r_lt (r_const a) (r_const b)) : a < b := lt_of_const_lt_const H theorem r_le_of_le_reprs (s t : reg_seq) (Hle : ∀ n : ℕ+, r_le s (r_const (reg_seq.sq t n))) : r_le s t := le_of_le_reprs (reg_seq.is_reg s) (reg_seq.is_reg t) Hle theorem r_le_of_reprs_le (s t : reg_seq) (Hle : ∀ n : ℕ+, r_le (r_const (reg_seq.sq t n)) s) : r_le t s := le_of_reprs_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle end rat_seq open real open [class] rat_seq namespace real protected definition lt (x y : ℝ) := quot.lift_on₂ x y (λ a b, rat_seq.r_lt a b) rat_seq.r_lt_well_defined protected definition le (x y : ℝ) := quot.lift_on₂ x y (λ a b, rat_seq.r_le a b) rat_seq.r_le_well_defined attribute [instance, priority real.prio] definition real_has_lt : has_lt ℝ := has_lt.mk real.lt attribute [instance, priority real.prio] definition real_has_le : has_le ℝ := has_le.mk real.le definition sep (x y : ℝ) := quot.lift_on₂ x y (λ a b, rat_seq.r_sep a b) rat_seq.r_sep_well_defined infix `≢` : 50 := sep protected theorem le_refl (x : ℝ) : x ≤ x := quot.induction_on x (λ t, rat_seq.r_le.refl t) protected theorem le_trans {x y z : ℝ} : x ≤ y → y ≤ z → x ≤ z := quot.induction_on₃ x y z (λ s t u, rat_seq.r_le.trans) protected theorem eq_of_le_of_ge {x y : ℝ} : x ≤ y → y ≤ x → x = y := quot.induction_on₂ x y (λ s t Hst Hts, quot.sound (rat_seq.r_equiv_of_le_of_ge Hst Hts)) theorem lt_iff_le_and_sep (x y : ℝ) : x < y ↔ x ≤ y ∧ x ≢ y := quot.induction_on₂ x y (λ s t, rat_seq.r_lt_iff_le_and_sep s t) protected theorem add_le_add_left' (x y z : ℝ) : x ≤ y → z + x ≤ z + y := quot.induction_on₃ x y z (λ s t u, rat_seq.r_add_le_add_of_le_right_var s t u) protected theorem add_le_add_left (x y : ℝ) : x ≤ y → ∀ z : ℝ, z + x ≤ z + y := take H z, real.add_le_add_left' x y z H protected theorem mul_pos (x y : ℝ) : 0 < x → 0 < y → 0 < x * y := quot.induction_on₂ x y (λ s t, rat_seq.r_mul_pos_of_pos) protected theorem mul_nonneg (x y : ℝ) : 0 ≤ x → 0 ≤ y → 0 ≤ x * y := quot.induction_on₂ x y (λ s t, rat_seq.r_mul_nonneg_of_nonneg) theorem not_sep_self (x : ℝ) : ¬ x ≢ x := quot.induction_on x (λ s, rat_seq.r_not_sep_self s) protected theorem lt_irrefl (x : ℝ) : ¬ x < x := quot.induction_on x (λ s, rat_seq.r_not_lt_self s) protected theorem le_of_lt {x y : ℝ} : x < y → x ≤ y := quot.induction_on₂ x y (λ s t H', rat_seq.r_le_of_lt H') protected theorem lt_of_le_of_lt {x y z : ℝ} : x ≤ y → y < z → x < z := quot.induction_on₃ x y z (λ s t u H H', rat_seq.r_lt_of_le_of_lt H H') protected theorem lt_of_lt_of_le {x y z : ℝ} : x < y → y ≤ z → x < z := quot.induction_on₃ x y z (λ s t u H H', rat_seq.r_lt_of_lt_of_le H H') protected theorem add_lt_add_left' (x y z : ℝ) : x < y → z + x < z + y := quot.induction_on₃ x y z (λ s t u, rat_seq.r_add_lt_add_left_var s t u) protected theorem add_lt_add_left (x y : ℝ) : x < y → ∀ z : ℝ, z + x < z + y := take H z, real.add_lt_add_left' x y z H protected theorem zero_lt_one : (0 : ℝ) < (1 : ℝ) := rat_seq.r_zero_lt_one protected theorem le_of_lt_or_eq (x y : ℝ) : x < y ∨ x = y → x ≤ y := (quot.induction_on₂ x y (λ s t H, or.elim H (take H', begin apply rat_seq.r_le_of_lt_or_eq, apply or.inl H' end) (take H', begin apply rat_seq.r_le_of_lt_or_eq, apply (or.inr (quot.exact H')) end))) attribute [trans_instance] definition ordered_ring : ordered_ring ℝ := ⦃ ordered_ring, real.comm_ring, le_refl := real.le_refl, le_trans := @real.le_trans, mul_pos := real.mul_pos, mul_nonneg := real.mul_nonneg, zero_ne_one := real.zero_ne_one, add_le_add_left := real.add_le_add_left, le_antisymm := @real.eq_of_le_of_ge, lt_irrefl := real.lt_irrefl, lt_of_le_of_lt := @real.lt_of_le_of_lt, lt_of_lt_of_le := @real.lt_of_lt_of_le, le_of_lt := @real.le_of_lt, add_lt_add_left := real.add_lt_add_left ⦄ open int theorem of_rat_sub (a b : ℚ) : of_rat (a - b) = of_rat a - of_rat b := rfl theorem of_int_sub (a b : ℤ) : of_int (a - b) = of_int a - of_int b := by rewrite [of_int_eq, rat.of_int_sub, of_rat_sub] theorem of_rat_le_of_rat_of_le {a b : ℚ} : a ≤ b → of_rat a ≤ of_rat b := rat_seq.r_const_le_const_of_le theorem le_of_of_rat_le_of_rat {a b : ℚ} : of_rat a ≤ of_rat b → a ≤ b := rat_seq.r_le_of_const_le_const theorem of_rat_le_of_rat_iff (a b : ℚ) : of_rat a ≤ of_rat b ↔ a ≤ b := iff.intro le_of_of_rat_le_of_rat of_rat_le_of_rat_of_le theorem of_rat_lt_of_rat_of_lt {a b : ℚ} : a < b → of_rat a < of_rat b := rat_seq.r_const_lt_const_of_lt theorem lt_of_of_rat_lt_of_rat {a b : ℚ} : of_rat a < of_rat b → a < b := rat_seq.r_lt_of_const_lt_const theorem of_rat_lt_of_rat_iff (a b : ℚ) : of_rat a < of_rat b ↔ a < b := iff.intro lt_of_of_rat_lt_of_rat of_rat_lt_of_rat_of_lt theorem of_int_le_of_int_iff (a b : ℤ) : of_int a ≤ of_int b ↔ (a ≤ b) := begin rewrite [+of_int_eq, of_rat_le_of_rat_iff], apply rat.of_int_le_of_int_iff end theorem of_int_le_of_int_of_le {a b : ℤ} : (a ≤ b) → of_int a ≤ of_int b := iff.mpr !of_int_le_of_int_iff theorem le_of_of_int_le_of_int {a b : ℤ} : of_int a ≤ of_int b → (a ≤ b) := iff.mp !of_int_le_of_int_iff theorem of_int_lt_of_int_iff (a b : ℤ) : of_int a < of_int b ↔ (a < b) := by rewrite [*of_int_eq, of_rat_lt_of_rat_iff]; apply rat.of_int_lt_of_int_iff theorem of_int_lt_of_int_of_lt {a b : ℤ} : (a < b) → of_int a < of_int b := iff.mpr !of_int_lt_of_int_iff theorem lt_of_of_int_lt_of_int {a b : ℤ} : of_int a < of_int b → (a < b) := iff.mp !of_int_lt_of_int_iff theorem of_nat_le_of_nat_iff (a b : ℕ) : of_nat a ≤ of_nat b ↔ (a ≤ b) := by rewrite [*of_nat_eq, of_rat_le_of_rat_iff]; apply rat.of_nat_le_of_nat_iff theorem of_nat_le_of_nat_of_le {a b : ℕ} : (a ≤ b) → of_nat a ≤ of_nat b := iff.mpr !of_nat_le_of_nat_iff theorem le_of_of_nat_le_of_nat {a b : ℕ} : of_nat a ≤ of_nat b → (a ≤ b) := iff.mp !of_nat_le_of_nat_iff theorem of_nat_lt_of_nat_iff (a b : ℕ) : of_nat a < of_nat b ↔ (a < b) := by rewrite [*of_nat_eq, of_rat_lt_of_rat_iff]; apply rat.of_nat_lt_of_nat_iff theorem of_nat_lt_of_nat_of_lt {a b : ℕ} : (a < b) → of_nat a < of_nat b := iff.mpr !of_nat_lt_of_nat_iff theorem lt_of_of_nat_lt_of_nat {a b : ℕ} : of_nat a < of_nat b → (a < b) := iff.mp !of_nat_lt_of_nat_iff theorem of_rat_pos_of_pos {q : ℚ} (Hq : q > 0) : of_rat q > 0 := of_rat_lt_of_rat_of_lt Hq theorem of_rat_nonneg_of_nonneg {q : ℚ} (Hq : q ≥ 0) : of_rat q ≥ 0 := of_rat_le_of_rat_of_le Hq theorem of_rat_neg_of_neg {q : ℚ} (Hq : q < 0) : of_rat q < 0 := of_rat_lt_of_rat_of_lt Hq theorem of_rat_nonpos_of_nonpos {q : ℚ} (Hq : q ≤ 0) : of_rat q ≤ 0 := of_rat_le_of_rat_of_le Hq theorem of_nat_nonneg (a : ℕ) : of_nat a ≥ 0 := of_rat_le_of_rat_of_le !rat.of_nat_nonneg theorem of_nat_succ_pos (k : ℕ) : 0 < of_nat k + 1 := add_pos_of_nonneg_of_pos (of_nat_nonneg k) real.zero_lt_one theorem of_rat_pow (a : ℚ) (n : ℕ) : of_rat (a^n) = (of_rat a)^n := begin induction n with n ih, apply eq.refl, rewrite [2 pow_succ, of_rat_mul, ih] end theorem of_int_pow (a : ℤ) (n : ℕ) : of_int (#int a^n) = (of_int a)^n := by rewrite [of_int_eq, rat.of_int_pow, of_rat_pow] theorem of_nat_pow (a : ℕ) (n : ℕ) : of_nat (#nat a^n) = (of_nat a)^n := by rewrite [of_nat_eq, rat.of_nat_pow, of_rat_pow] open rat_seq theorem le_of_le_reprs (x : ℝ) (t : seq) (Ht : regular t) : (∀ n : ℕ+, x ≤ t n) → x ≤ quot.mk (reg_seq.mk t Ht) := quot.induction_on x (take s Hs, show r_le s (reg_seq.mk t Ht), from have H' : ∀ n : ℕ+, r_le s (r_const (t n)), from Hs, by apply r_le_of_le_reprs; apply Hs) theorem le_of_reprs_le (x : ℝ) (t : seq) (Ht : regular t) : (∀ n : ℕ+, t n ≤ x) → x ≥ ((quot.mk (reg_seq.mk t Ht)) : ℝ) := quot.induction_on x (take s Hs, show r_le (reg_seq.mk t Ht) s, from have H' : ∀ n : ℕ+, r_le (r_const (t n)) s, from Hs, by apply r_le_of_reprs_le; apply Hs) end real
b34746037f8782984d7111a716d76dd6493dbb21
69bc7d0780be17e452d542a93f9599488f1c0c8e
/exam-2-study-guide.lean
ea665c30dbcc00d2957425db11aff0483bd73acd
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
3,444
lean
/- *** I. FORMAL LANGUAGES *** -/ /- Using our implementation of the syntax and semantics of propositional logic, know how to implement the syntax and semantics of simple arithmetic expressions, with natural number literal expressions, natural number-valued variable expressions, and natural number unary and binary operators. -/ /- *** II. PREDICATE LOGIC *** -/ /- Be able to write *formal* propositions and predicates n predicate logic to "formalize" natural language statements of propositions and predicates i. Such propositions and predicates can involve both universal and existential quantifiers, alone or in combination: e.g., forall x, exists y, not P x y. -/ /- Be able to *naturalize* formal propositions and predicates by translating formal versions into natural language. You will have to go beyond just "saying words for symbols." Rather, you'll need to find "natural" ways to say what propositions mean. For example, \all x, exists y, P x y should not be translated as "for all x there exists some y such that P x y." It will be necessary to say something like "every x P some y." -/ inductive dog : Type variable fido : dog inductive has_legs {α : Type} : α → Prop /- All dogs have legs -/ axiom dogs_have_legs : ∀ (d : dog), has_legs d /- Fido has legs -/ theorem fido_has_legs : has_legs fido := begin apply dogs_have_legs, end inductive person : Type inductive likes : person → person → Prop axiom everyone_likes_self : ∀ p : person, likes p p axiom everyone_likes_someone : ∀ p : person, ∃ q : person, likes p q axiom someone_likes_everyone : ∃ p: person, ∀ q : person, likes p q def nobody_likes_someone : Prop := ∃ p : person, ∀ q : person, ¬likes q p variable bill : person example : ¬nobody_likes_someone := begin apply not.intro, unfold nobody_likes_someone, assume h, apply exists.elim h, assume a, assume ha, have a_dislikes_self : ¬likes a a := (ha a), have a_likes_self : likes a a := everyone_likes_self a, contradiction end /- *** II. PROOFS *** -/ /- Give both natural language and formal proofs of propositions, including proofs for "inductively defined families of propositions" (such as we did for is_even). We will not ask you to prove propositions with negation or existential quantification except perhaps for extra credit, as we have not covered them yet. -/ inductive id_nat : nat → nat → Prop | mk : ∀ (a b : nat), a = b → id_nat a b def transitive' {α : Type} (r : α → α → Prop) : Prop := ∀ (a b c : α), r a b → r b c → r a c theorem id_nat_transitive : transitive' id_nat := begin unfold transitive', assume a b c, assume hab, assume hbc, induction hab with a b ab, induction hbc with b c bc, apply id_nat.mk, exact eq.trans ab bc, end theorem id_nat_transitive' : transitive' id_nat := λ (a b c : nat), λ (hab : id_nat a b) (hbc : id_nat b c), sorry /- EXTRA CREDIT -/ /- Show that you've gone beyond what we've covered in class, e.g., to an understanding of negation in the constructive logic of the Lean proof assistant. More details to come. -/ theorem test (P: Prop) : ¬ (P ∧ ¬P) := begin apply not.intro, assume PnP, have hp : P, from (and.elim_left PnP), have hnp : ¬P, from (and.elim_right PnP), contradiction end theorem is_2 : ∃ (n : nat), n = 2 := exists.intro 2 (eq.refl 2)
5467487a75b1ea39fe3fbf5db708a037f4e31727
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world6/level2.lean
86540e4848cbc2843c4df73cabf2460c363cc9f9
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
2,121
lean
/- # Proposition world. ## Level 2 : `intro`. Let's prove an implication. Let $P$ be a true/false statement, and let's prove that $P\implies P$. If you delete the `sorry` you will see that our goal is `P → P`. Constructing a term of type `P → P` (which is what solving this goal *means*) in this case amounts to proving that $P\implies P$, and computer scientists think of this as coming up with a function which sends proofs of $P$ to proofs of $P$. To define an implication $P\implies Q$ we need to choose an arbitrary proof $p : P$ of $P$ and then, perhaps using $p$, construct a proof of $Q$. The Lean way to say "let's assume $P$ is true" is `intro p`, i.e., "let's assume we have a proof of $P$". Those of you who know something about the subtle differences between truth and provability discovered by Goedel -- I would strongly advise that you completely forget about them for the moment because this issue is not relevant here. $p$ doesn't have to be thought of as a proof of $P$, it can be interpreted as some sort of more abstract "evidence for the truth of $P$" or "witness to the truth of $P$" if you like. This is however philosophy rather than mathematics, and it's easiest to just think of $p$ as a proof of $P$. ## Rule of thumb: If your goal is to prove `P → Q` (i.e. that $P\implies Q$) then `intro p`, meaning "assume $P$ is true", will make progress. To solve the goal below, you have to come up with a function from `P` (thought of as the set of proofs of $P$!) to itself. Start with `intro p,` (i.e. "let $p$ be a proof of $P$") and note that our local context now looks like this: ``` P : Prop, p : P ⊢ P ``` Our job now is to construct a proof of $P$. But $p$ is a proof of $P$. So `exact p,` will close the goal. Note that `exact P` will not work -- don't confuse a true/false statement (which could be false!) with a proof. We will stick with the convention of capital letters for propositions and small letters for proofs. -/ /- Lemma : no-side-bar If $P$ is a proposition then $P\implies P$. -/ lemma level2 (P : Prop) : P → P := begin intro p, exact p, end
7fab046ed5b8701098f731c19ca7dba4a4aa71e7
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/group_action/group.lean
ce036680ff4ae59b81be58490f191057692feac9
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,968
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action.defs import algebra.group.units import algebra.group_with_zero import data.equiv.mul_add import group_theory.perm.basic /-! # Group actions applied to various types of group This file contains lemmas about `smul` on `units`, `group_with_zero`, and `group`. -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section mul_action section units variables [monoid α] [mul_action α β] @[simp, to_additive] lemma units.inv_smul_smul (u : units α) (x : β) : (↑u⁻¹:α) • (u:α) • x = x := by rw [smul_smul, u.inv_mul, one_smul] @[simp, to_additive] lemma units.smul_inv_smul (u : units α) (x : β) : (u:α) • (↑u⁻¹:α) • x = x := by rw [smul_smul, u.mul_inv, one_smul] /-- If a monoid `α` acts on `β`, then each `u : units α` defines a permutation of `β`. -/ @[to_additive] def units.smul_perm (u : units α) : equiv.perm β := ⟨λ x, (u:α) • x, λ x, (↑u⁻¹:α) • x, u.inv_smul_smul, u.smul_inv_smul⟩ /-- If an additive monoid `α` acts on `β`, then each `u : add_units α` defines a permutation of `β`. -/ add_decl_doc add_units.vadd_perm /-- If a monoid `α` acts on `β`, then each `u : units α` defines a permutation of `β`. -/ def units.smul_perm_hom : units α →* equiv.perm β := { to_fun := units.smul_perm, map_one' := equiv.ext $ one_smul α, map_mul' := λ u₁ u₂, equiv.ext $ mul_smul (u₁:α) u₂ } /-- If an additive monoid `α` acts on `β`, then each `u : add_units α` defines a permutation of `β`. -/ def add_units.vadd_perm_hom {M : Type*} [add_monoid M] [add_action M β] : add_units M →+ additive (equiv.perm β) := { to_fun := λ u, additive.of_mul u.vadd_perm, map_zero' := equiv.ext $ zero_vadd M, map_add' := λ u₁ u₂, equiv.ext $ add_vadd (u₁:M) u₂ } @[simp, to_additive] lemma units.smul_left_cancel (u : units α) {x y : β} : (u:α) • x = (u:α) • y ↔ x = y := u.smul_perm.apply_eq_iff_eq @[to_additive] lemma units.smul_eq_iff_eq_inv_smul (u : units α) {x y : β} : (u:α) • x = y ↔ x = (↑u⁻¹:α) • y := u.smul_perm.apply_eq_iff_eq_symm_apply @[to_additive] lemma is_unit.smul_left_cancel {a : α} (ha : is_unit a) {x y : β} : a • x = a • y ↔ x = y := let ⟨u, hu⟩ := ha in hu ▸ u.smul_left_cancel end units section gwz variables [group_with_zero α] [mul_action α β] @[simp] lemma inv_smul_smul' {c : α} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x := (units.mk0 c hc).inv_smul_smul x @[simp] lemma smul_inv_smul' {c : α} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x := (units.mk0 c hc).smul_inv_smul x lemma inv_smul_eq_iff' {a : α} (ha : a ≠ 0) {x y : β} : a⁻¹ • x = y ↔ x = a • y := (units.mk0 a ha).smul_perm.symm_apply_eq lemma eq_inv_smul_iff' {a : α} (ha : a ≠ 0) {x y : β} : x = a⁻¹ • y ↔ a • x = y := (units.mk0 a ha).smul_perm.eq_symm_apply end gwz section group variables [group α] [mul_action α β] @[simp, to_additive] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x := (to_units c).inv_smul_smul x @[simp, to_additive] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x := (to_units c).smul_inv_smul x @[to_additive] lemma inv_smul_eq_iff {a : α} {x y : β} : a⁻¹ • x = y ↔ x = a • y := (to_units a).smul_perm.symm_apply_eq @[to_additive] lemma eq_inv_smul_iff {a : α} {x y : β} : x = a⁻¹ • y ↔ a • x = y := (to_units a).smul_perm.eq_symm_apply variables (α) (β) /-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ def mul_action.to_perm : α →* equiv.perm β := units.smul_perm_hom.comp to_units.to_monoid_hom variables {α} {β} @[to_additive] protected lemma mul_action.bijective (g : α) : function.bijective (λ b : β, g • b) := (to_units g).smul_perm.bijective @[to_additive] protected lemma mul_action.injective (g : α) : function.injective (λ b : β, g • b) := (mul_action.bijective g).injective @[to_additive] lemma smul_left_cancel (g : α) {x y : β} (h : g • x = g • y) : x = y := mul_action.injective g h @[simp, to_additive] lemma smul_left_cancel_iff (g : α) {x y : β} : g • x = g • y ↔ x = y := (mul_action.injective g).eq_iff end group end mul_action section distrib_mul_action variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem units.smul_eq_zero (u : units α) {x : β} : (u : α) • x = 0 ↔ x = 0 := ⟨λ h, by rw [← u.inv_smul_smul x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩ theorem units.smul_ne_zero (u : units α) {x : β} : (u : α) • x ≠ 0 ↔ x ≠ 0 := not_congr u.smul_eq_zero @[simp] theorem is_unit.smul_eq_zero {u : α} (hu : is_unit u) {x : β} : u • x = 0 ↔ x = 0 := exists.elim hu $ λ u hu, hu ▸ u.smul_eq_zero end distrib_mul_action
fa76aaf8508d73a36a170a85c6a217aacc0ba456
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/nat_antidiagonal.lean
67d4ebf2debfb203062adeb1bbb70ae40f3f107a
[]
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,465
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.nodup import Mathlib.data.list.nat_antidiagonal import Mathlib.PostPort namespace Mathlib /-! # The "antidiagonal" {(0,n), (1,n-1), ..., (n,0)} as a multiset. -/ namespace multiset namespace nat /-- The antidiagonal of a natural number `n` is the multiset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) := ↑(list.nat.antidiagonal n) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] theorem mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ prod.fst x + prod.snd x = n := sorry /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] theorem card_antidiagonal (n : ℕ) : coe_fn card (antidiagonal n) = n + 1 := sorry /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] theorem antidiagonal_zero : antidiagonal 0 = singleton (0, 0) := rfl /-- The antidiagonal of `n` does not contain duplicate entries. -/ @[simp] theorem nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := iff.mpr coe_nodup (list.nat.nodup_antidiagonal n) @[simp] theorem antidiagonal_succ {n : ℕ} : antidiagonal (n + 1) = (0, n + 1) ::ₘ map (prod.map Nat.succ id) (antidiagonal n) := sorry
6e9b69c149d6d924bebe1a2805429e1e9ab00565
aa2345b30d710f7e75f13157a35845ee6d48c017
/algebra/group_power.lean
5f30344874fc227bd7f605e6e56bdbc99c1eae75
[ "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
23,258
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis The power operation on monoids and groups. We separate this from group, because it depends on nat, which in turn depends on other parts of algebra. We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation a^n is used for the first, but users can locally redefine it to gpow when needed. Note: power adopts the convention that 0^0=1. -/ import algebra.char_zero algebra.group algebra.ordered_field import data.int.basic data.list.basic universes u v variable {α : Type u} @[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] @[simp] theorem inv_inv' [discrete_field α] {a:α} : a⁻¹⁻¹ = a := by rw [inv_eq_one_div, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_one] /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [monoid α] (a : α) : ℕ → α | 0 := 1 | (n+1) := a * monoid.pow n def add_monoid.smul [add_monoid α] (n : ℕ) (a : α) : α := @monoid.pow (multiplicative α) _ a n precedence `•`:70 local infix ` • ` := add_monoid.smul @[priority 5] instance monoid.has_pow [monoid α] : has_pow α ℕ := ⟨monoid.pow⟩ /- monoid -/ section monoid variables [monoid α] {β : Type u} [add_monoid β] @[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl @[simp] theorem add_monoid.zero_smul (a : β) : 0 • a = 0 := rfl attribute [to_additive add_monoid.zero_smul] pow_zero theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_smul (a : β) (n : ℕ) : (n+1)•a = a + n•a := rfl attribute [to_additive succ_smul] pow_succ @[simp] theorem pow_one (a : α) : a^1 = a := mul_one _ @[simp] theorem add_monoid.one_smul (a : β) : 1•a = a := add_zero _ attribute [to_additive add_monoid.one_smul] pow_one theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; [rw [pow_zero, one_mul, mul_one], rw [pow_succ, mul_assoc, ih]] theorem smul_add_comm' : ∀ (a : β) (n : ℕ), n•a + a = a + n•a := @pow_mul_comm' (multiplicative β) _ theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_smul' (a : β) (n : ℕ) : (n+1)•a = n•a + a := by rw [succ_smul, smul_add_comm'] attribute [to_additive succ_smul'] pow_succ' theorem pow_two (a : α) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_smul (a : β) : 2•a = a + a := show a+(a+0)=a+a, by rw add_zero attribute [to_additive two_smul] pow_two theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl theorem add_monoid.add_smul : ∀ (a : β) (m n : ℕ), (m + n)•a = m•a + n•a := @pow_add (multiplicative β) _ attribute [to_additive add_monoid.add_smul] pow_add @[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : β) = (0:β) := by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]] attribute [to_additive add_monoid.smul_zero] one_pow theorem pow_mul (a : α) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem add_monoid.mul_smul' : ∀ (a : β) (m n : ℕ), m * n • a = n•(m•a) := @pow_mul (multiplicative β) _ attribute [to_additive add_monoid.mul_smul'] pow_mul theorem pow_mul' (a : α) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem add_monoid.mul_smul (a : β) (m n : ℕ) : m * n • a = m•(n•a) := by rw [mul_comm, add_monoid.mul_smul'] attribute [to_additive add_monoid.mul_smul] pow_mul' @[simp] theorem add_monoid.smul_one [has_one β] : ∀ n : ℕ, n • (1 : β) = n := nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _) theorem pow_bit0 (a : α) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_smul (a : β) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _ attribute [to_additive bit0_smul] pow_bit0 theorem pow_bit1 (a : α) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_smul : ∀ (a : β) (n : ℕ), bit1 n • a = n•a + n•a + a := @pow_bit1 (multiplicative β) _ attribute [to_additive bit1_smul] pow_bit1 theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] theorem smul_add_comm : ∀ (a : β) (m n : ℕ), m•a + n•a = n•a + m•a := @pow_mul_comm (multiplicative β) _ attribute [to_additive smul_add_comm] pow_mul_comm @[simp] theorem list.prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n := by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl @[simp] theorem list.sum_repeat : ∀ (a : β) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative β) _ attribute [to_additive list.sum_repeat] list.prod_repeat @[simp] lemma units.coe_pow (u : units α) (n : ℕ) : ((u ^ n : units α) : α) = u ^ n := by induction n; simp [*, pow_succ] end monoid @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]] @[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul], rw [succ_smul', ih, nat.succ_mul]] /- commutative monoid -/ section comm_monoid variables [comm_monoid α] {β : Type*} [add_comm_monoid β] theorem mul_pow (a b : α) (n : ℕ) : (a * b)^n = a^n * b^n := by induction n with n ih; [exact (mul_one _).symm, simp only [pow_succ, ih, mul_assoc, mul_left_comm]] theorem add_monoid.smul_add : ∀ (a b : β) (n : ℕ), n•(a + b) = n•a + n•b := @mul_pow (multiplicative β) _ attribute [to_additive add_monoid.add_smul] mul_pow end comm_monoid section group variables [group α] {β : Type*} [add_group β] section nat @[simp] theorem inv_pow (a : α) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem add_monoid.neg_smul : ∀ (a : β) (n : ℕ), n•(-a) = -(n•a) := @inv_pow (multiplicative β) _ attribute [to_additive add_monoid.neg_smul] inv_pow theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem add_monoid.smul_sub : ∀ (a : β) {m n : ℕ}, m ≥ n → (m - n)•a = m•a - n•a := @pow_sub (multiplicative β) _ attribute [to_additive add_monoid.smul_sub] inv_pow theorem pow_inv_comm (a : α) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _) theorem add_monoid.smul_neg_comm : ∀ (a : β) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) := @pow_inv_comm (multiplicative β) _ attribute [to_additive add_monoid.smul_neg_comm] pow_inv_comm end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : α) : ℤ → α | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ def gsmul (n : ℤ) (a : β) : β := @gpow (multiplicative β) _ a n @[priority 10] instance group.has_pow : has_pow α ℤ := ⟨gpow⟩ local infix ` • `:70 := gsmul local infix ` •ℕ `:70 := add_monoid.smul @[simp] theorem gpow_coe_nat (a : α) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : β) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl attribute [to_additive gsmul_coe_nat] gpow_coe_nat @[simp] theorem gpow_of_nat (a : α) (n : ℕ) : a ^ of_nat n = a ^ n := rfl @[simp] theorem gsmul_of_nat (a : β) (n : ℕ) : of_nat n • a = n •ℕ a := rfl attribute [to_additive gsmul_of_nat] gpow_of_nat @[simp] theorem gpow_neg_succ (a : α) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ (a : β) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl attribute [to_additive gsmul_neg_succ] gpow_neg_succ local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : α) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : β) : (0:ℤ) • a = 0 := rfl attribute [to_additive zero_gsmul] gpow_zero @[simp] theorem gpow_one (a : α) : a ^ (1:ℤ) = a := mul_one _ @[simp] theorem one_gsmul (a : β) : (1:ℤ) • a = a := add_zero _ attribute [to_additive one_gsmul] gpow_one @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : α) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:α), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : β) = 0 := @one_gpow (multiplicative β) _ attribute [to_additive gsmul_zero] one_gpow @[simp] theorem gpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm @[simp] theorem neg_gsmul : ∀ (a : β) (n : ℤ), -n • a = -(n • a) := @gpow_neg (multiplicative β) _ attribute [to_additive neg_gsmul] gpow_neg theorem gpow_neg_one (x : α) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : β) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x attribute [to_additive neg_one_gsmul] gpow_neg_one theorem inv_gpow (a : α) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) private lemma gpow_add_aux (a : α) (m n : nat) : a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] := or.elim (nat.lt_or_ge m (nat.succ n)) (assume h1 : m < succ n, have h2 : m ≤ n, from le_of_lt_succ h1, suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by rwa [of_nat_add_neg_succ_of_nat_of_lt h1], show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl) (assume : m ≥ succ n, suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : α) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux, gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm] | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this, by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem add_gsmul : ∀ (a : β) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative β) _ theorem gpow_mul_comm (a : α) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : β) (i j), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative β) _ attribute [to_additive gsmul_add_comm] gpow_mul_comm theorem gpow_mul (a : α) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n | (m : ℕ) (n : ℕ) := pow_mul _ _ _ | (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $ show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl | -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $ show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl | -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv] theorem gsmul_mul' : ∀ (a : β) (m n : ℤ), m * n • a = n • (m • a) := @gpow_mul (multiplicative β) _ attribute [to_additive gsmul_mul'] gpow_mul theorem gpow_mul' (a : α) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : β) (m n : ℤ) : m * n • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] attribute [to_additive gsmul_mul] gpow_mul' theorem gpow_bit0 (a : α) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : β) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _ attribute [to_additive bit0_gsmul] gpow_bit0 theorem gpow_bit1 (a : α) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : β) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative β) _ attribute [to_additive bit1_gsmul] gpow_bit1 theorem gsmul_neg (a : β) (n : ℤ) : gsmul n (- a) = - gsmul n a := begin induction n using int.induction_on with z ih z ih, { simp }, { rw [add_comm] {occs := occurrences.pos [1]}, simp [add_gsmul, ih, -add_comm] }, { rw [sub_eq_add_neg, add_comm] {occs := occurrences.pos [1]}, simp [ih, add_gsmul, neg_gsmul, -add_comm] } end attribute [to_additive gsmul_neg] gpow_neg end group namespace is_group_hom variables {β : Type v} [group α] [group β] (f : α → β) [is_group_hom f] theorem pow (a : α) (n : ℕ) : f (a ^ n) = f a ^ n := by induction n with n ih; [exact is_group_hom.one f, rw [pow_succ, is_group_hom.mul f, ih]]; refl theorem gpow (a : α) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact is_group_hom.pow f _ _, exact (is_group_hom.inv f _).trans (congr_arg _ $ is_group_hom.pow f _ _)] end is_group_hom namespace is_add_group_hom variables {β : Type v} [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] theorem smul (a : α) (n : ℕ) : f (n • a) = n • f a := by induction n with n ih; [exact is_add_group_hom.zero f, rw [succ_smul, is_add_group_hom.add f, ih]]; refl theorem gsmul (a : α) (n : ℤ) : f (gsmul n a) = gsmul n (f a) := begin induction n using int.induction_on with z ih z ih, { simp [is_add_group_hom.zero f] }, { simp [is_add_group_hom.add f, add_gsmul, ih] }, { simp [is_add_group_hom.add f, is_add_group_hom.neg f, add_gsmul, ih] } end end is_add_group_hom local infix ` •ℤ `:70 := gsmul section comm_monoid variables [comm_group α] {β : Type*} [add_comm_group β] theorem mul_gpow (a b : α) : ∀ n:ℤ, (a * b)^n = a^n * b^n | (n : ℕ) := mul_pow a b n | -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm] theorem gsmul_add : ∀ (a b : β) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative β) _ attribute [to_additive gsmul_add] mul_gpow theorem gsmul_sub : ∀ (a b : β) (n : ℤ), gsmul n (a - b) = gsmul n a - gsmul n b := by simp [gsmul_add, gsmul_neg] end comm_monoid section group @[instance] theorem is_add_group_hom_gsmul {α β} [add_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] (z : ℤ) : is_add_group_hom (λa, gsmul z (f a)) := ⟨assume a b, by rw [is_add_group_hom.add f, gsmul_add]⟩ end group theorem add_monoid.smul_eq_mul' [semiring α] (a : α) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero], rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]] theorem add_monoid.smul_eq_mul [semiring α] (n : ℕ) (a : α) : n • a = n * a := by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm] theorem add_monoid.mul_smul_left [semiring α] (a b : α) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc] theorem add_monoid.mul_smul_assoc [semiring α] (a b : α) (n : ℕ) : n • (a * b) = n • a * b := by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc] lemma zero_pow [semiring α] : ∀ {n : ℕ}, 0 < n → (0 : α) ^ n = 0 | (n+1) _ := zero_mul _ @[simp] theorem nat.cast_pow [semiring α] (n m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] theorem is_semiring_hom.map_pow {β} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] (x : α) (n : ℕ) : f (x ^ n) = f x ^ n := by induction n with n ih; [exact is_semiring_hom.map_one f, rw [pow_succ, pow_succ, is_semiring_hom.map_mul f, ih]] theorem neg_one_pow_eq_or {R} [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) theorem gsmul_eq_mul [ring α] (a : α) : ∀ n, n •ℤ a = n * a | (n : ℕ) := add_monoid.smul_eq_mul _ _ | -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring α] (a : α) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, int.mul_cast_comm] theorem mul_gsmul_left [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] theorem int.cast_pow [ring α] (n : ℤ) (m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring α] {n : ℕ} : (-1 : α) ^ n = -1 ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem pow_ne_zero [domain α] {a : α} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := begin induction n with n ih, {exact one_ne_zero}, intro H, cases mul_eq_zero.1 H with h1 h1, exacts [h h1, ih h1] end @[simp] theorem one_div_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : (1 / a) ^ n = 1 / a ^ n := by induction n with n ih; [exact (div_one _).symm, rw [pow_succ', ih, division_ring.one_div_mul_one_div (pow_ne_zero _ ha) ha]]; refl @[simp] theorem division_ring.inv_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ := by simpa only [inv_eq_one_div] using one_div_pow ha n @[simp] theorem div_pow [field α] (a : α) {b : α} (hb : b ≠ 0) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_one_div, mul_pow, one_div_pow hb, ← div_eq_mul_one_div] theorem add_monoid.smul_nonneg [ordered_comm_monoid α] {a : α} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a | 0 := le_refl _ | (n+1) := add_nonneg' H (add_monoid.smul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring α] (a : α) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma inv_pow' [discrete_field α] (a : α) (n : ℕ) : (a ^ n)⁻¹ = a⁻¹ ^ n := by induction n; simp [*, pow_succ, mul_inv', mul_comm] lemma pow_inv [division_ring α] (a : α) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n | 0 ha := inv_one | (n+1) ha := by rw [pow_succ, pow_succ', mul_inv_eq (pow_ne_zero _ ha) ha, pow_inv _ ha] section linear_ordered_semiring variable [linear_ordered_semiring α] theorem pow_pos {a : α} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : α} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) theorem pow_ge_one_add_mul {a : α} (H : a ≥ 0) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := begin rw [pow_succ', succ_smul'], refine le_trans _ (mul_le_mul_of_nonneg_right (pow_ge_one_add_mul n) (add_nonneg zero_le_one H)), rw [mul_add, mul_one, ← add_assoc, add_le_add_iff_left], simpa only [one_mul] using mul_le_mul_of_nonneg_right ((le_add_iff_nonneg_right 1).2 (add_monoid.smul_nonneg H n)) H end theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_le_pow_of_le_left {a b : α} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) private lemma pow_lt_pow_of_lt_one_aux {a : α} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp, rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : α} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : α} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : α} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : α} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : α) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring α] (a : α) : 0 ≤ a ^ 2 := by rw pow_two; exact mul_self_nonneg _ theorem pow_ge_one_add_sub_mul [linear_ordered_ring α] {a : α} (H : a ≥ 1) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n := by simpa only [add_sub_cancel'_right] using pow_ge_one_add_mul (sub_nonneg.2 H) n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma div_sq_cancel {α} [field α] {a : α} (ha : a ≠ 0) (b : α) : a^2 * b / a = a * b := by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
a3acc2bc61546c8af58d214dab9225ad9f4c691d
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/limits/shapes/kernels.lean
a3711dc997eb99d4caedf71a5368a9ddc548eb4a
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
15,648
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.zero import category_theory.limits.shapes.equalizers /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is just the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.) We don't yet prove much here, just provide * `kernel : (X ⟶ Y) → C` * `kernel.ι : kernel f ⟶ X` * `kernel.condition : kernel.ι f ≫ f = 0` and * `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, * `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism ## Future work * TODO: images and coimages, and then abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ universes v u open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables [has_zero_morphisms C] /-- A morphism `f` has a kernel if the functor `parallel_pair f 0` has a limit. -/ abbreviation has_kernel {X Y : C} (f : X ⟶ Y) : Type (max u v) := has_limit (parallel_pair f 0) /-- A morphism `f` has a cokernel if the functor `parallel_pair f 0` has a colimit. -/ abbreviation has_cokernel {X Y : C} (f : X ⟶ Y) : Type (max u v) := has_colimit (parallel_pair f 0) variables {X Y : C} (f : X ⟶ Y) section /-- A kernel fork is just a fork where the second morphism is a zero morphism. -/ abbreviation kernel_fork := fork f 0 variables {f} @[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 := by erw [fork.condition, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 := by rw [←fork.app_zero_left, kernel_fork.condition] /-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/ abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f := fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero] /-- If `s` is a limit kernel fork and `k : W ⟶ X` satisfies ``k ≫ f = 0`, then there is some `l : W ⟶ s.X` sich that `l ≫ fork.ι s = k`. -/ def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ kernel_fork.of_ι _ h, hs.fac _ _⟩ end section variables [has_kernel f] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0 @[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 := kernel_fork.condition _ /-- Given any morphism `k : W ⟶ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ι f` via `kernel.lift : W ⟶ kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f := limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h) @[simp, reassoc] lemma kernel.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ι f = k := limit.lift_π _ _ /-- Any morphism `k : W ⟶ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟶ kernel f` such that `l ≫ kernel.ι f = k`. -/ def kernel.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ kernel f // l ≫ kernel.ι f = k} := ⟨kernel.lift f k h, kernel.lift_ι _ _ _⟩ /-- Every kernel of the zero morphism is an isomorphism -/ def kernel.ι_zero_is_iso [has_kernel (0 : X ⟶ Y)] : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ lemma eq_zero_of_epi_kernel [epi (kernel.ι f)] : f = 0 := (cancel_epi (kernel.ι f)).1 (by simp) variables {f} lemma kernel_not_epi_of_nonzero (w : f ≠ 0) : ¬epi (kernel.ι f) := λ I, by exactI w (eq_zero_of_epi_kernel f) lemma kernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (kernel.ι f)) → false := λ I, kernel_not_epi_of_nonzero w $ by { resetI, apply_instance } end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_cone : cone (parallel_pair f 0) := { X := 0, π := { app := λ j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) := fork.is_limit.mk _ (λ s, 0) (λ s, by { erw has_zero_morphisms.zero_comp, convert (zero_of_comp_mono f _).symm, exact kernel_fork.condition _ }) (λ _ _ _, has_zero_object.zero_of_to_zero _) /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_kernel f] [mono f] : kernel f ≅ 0 := functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ι_of_mono [has_kernel f] [mono f] : kernel.ι f = 0 := by rw [←category.id_comp (kernel.ι f), ←iso.hom_inv_id (kernel.of_mono f), category.assoc, has_zero_object.zero_of_to_zero (kernel.of_mono f).hom, has_zero_morphisms.zero_comp] end has_zero_object section transport /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then any kernel of `f` is a kernel of `l`.-/ def is_kernel.of_comp_iso {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) {s : kernel_fork f} (hs : is_limit s) : is_limit (kernel_fork.of_ι (fork.ι s) $ show fork.ι s ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := fork.is_limit.mk _ (λ s, hs.lift $ kernel_fork.of_ι (fork.ι s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply fork.is_limit.hom_ext hs, simpa using h walking_parallel_pair.zero }) /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then the kernel of `f` is a kernel of `l`.-/ def kernel.of_comp_iso [has_kernel f] {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) : is_limit (kernel_fork.of_ι (kernel.ι f) $ show kernel.ι f ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := is_kernel.of_comp_iso f l i h $ limit.is_limit _ /-- If `s` is any limit kernel cone over `f` and if `i` is an isomorphism such that `i.hom ≫ s.ι = l`, then `l` is a kernel of `f`. -/ def is_kernel.iso_kernel {Z : C} (l : Z ⟶ X) {s : kernel_fork f} (hs : is_limit s) (i : Z ≅ s.X) (h : i.hom ≫ fork.ι s = l) : is_limit (kernel_fork.of_ι l $ show l ≫ f = 0, by simp [←h]) := is_limit.of_iso_limit hs $ cones.ext i.symm $ λ j, by { cases j, { exact (iso.eq_inv_comp i).2 h }, { simp } } /-- If `i` is an isomorphism such that `i.hom ≫ kernel.ι f = l`, then `l` is a kernel of `f`. -/ def kernel.iso_kernel [has_kernel f] {Z : C} (l : Z ⟶ X) (i : Z ≅ kernel f) (h : i.hom ≫ kernel.ι f = l) : is_limit (kernel_fork.of_ι l $ by simp [←h]) := is_kernel.iso_kernel f l (limit.is_limit _) i h end transport section variables (X Y) /-- The kernel morphism of a zero morphism is an isomorphism -/ def kernel.ι_of_zero [has_kernel (0 : X ⟶ Y)] : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ end section /-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/ abbreviation cokernel_cofork := cofork f 0 variables {f} @[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.π s = 0 := by rw [cofork.condition, has_zero_morphisms.zero_comp] @[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ι.app zero = 0 := by rw [←cofork.left_app_one, cokernel_cofork.condition] /-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/ abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f := cofork.of_π π $ by rw [w, has_zero_morphisms.zero_comp] /-- If `s` is a colimit cokernel cofork, then every `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cokernel_cofork.is_colimit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cokernel_cofork.of_π _ h, hs.fac _ _⟩ end section variables [has_cokernel f] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0 @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 := cokernel_cofork.condition _ /-- Given any morphism `k : Y ⟶ W` such that `f ≫ k = 0`, `k` factors through `cokernel.π f` via `cokernel.desc : cokernel f ⟶ W`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W := colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h) @[simp, reassoc] lemma cokernel.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel.π f ≫ cokernel.desc f k h = k := colimit.ι_desc _ _ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟶ W` such that `cokernel.π f ≫ l = k`. -/ def cokernel.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : cokernel f ⟶ W // cokernel.π f ≫ l = k} := ⟨cokernel.desc f k h, cokernel.π_desc _ _ _⟩ /-- The cokernel of the zero morphism is an isomorphism -/ def cokernel.π_zero_is_iso [has_colimit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ lemma eq_zero_of_mono_cokernel [mono (cokernel.π f)] : f = 0 := (cancel_mono (cokernel.π f)).1 (by simp) variables {f} lemma cokernel_not_mono_of_nonzero (w : f ≠ 0) : ¬mono (cokernel.π f) := λ I, by exactI w (eq_zero_of_mono_cokernel f) lemma cokernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (cokernel.π f)) → false := λ I, cokernel_not_mono_of_nonzero w $ by { resetI, apply_instance } end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cocone : cocone (parallel_pair f 0) := { X := 0, ι := { app := λ j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by { erw has_zero_morphisms.zero_comp, convert (zero_of_epi_comp f _).symm, exact cokernel_cofork.condition _ }) (λ _ _ _, has_zero_object.zero_of_from_zero _) /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_cokernel f] [epi f] : cokernel f ≅ 0 := functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism if an epimorphism is a zero morphism -/ lemma cokernel.π_of_epi [has_cokernel f] [epi f] : cokernel.π f = 0 := by rw [←category.comp_id (cokernel.π f), ←iso.hom_inv_id (cokernel.of_epi f), ←category.assoc, has_zero_object.zero_of_from_zero (cokernel.of_epi f).inv, has_zero_morphisms.comp_zero] end has_zero_object section variables (X Y) /-- The cokernel of a zero morphism is an isomorphism -/ def cokernel.π_of_zero [has_cokernel (0 : X ⟶ Y)] : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ instance kernel.of_cokernel_of_epi [has_cokernel f] [has_kernel (cokernel.π f)] [epi f] : is_iso (kernel.ι (cokernel.π f)) := equalizer.ι_of_eq $ cokernel.π_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ instance cokernel.of_kernel_of_mono [has_kernel f] [has_cokernel (kernel.ι f)] [mono f] : is_iso (cokernel.π (kernel.ι f)) := coequalizer.π_of_eq $ kernel.ι_of_mono f end has_zero_object section transport /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then any cokernel of `f` is a cokernel of `l`. -/ def is_cokernel.of_iso_comp {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) {s : cokernel_cofork f} (hs : is_colimit s) : is_colimit (cokernel_cofork.of_π (cofork.π s) $ show l ≫ cofork.π s = 0, by simp [i.eq_inv_comp.2 h]) := cofork.is_colimit.mk _ (λ s, hs.desc $ cokernel_cofork.of_π (cofork.π s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply cofork.is_colimit.hom_ext hs, simpa using h walking_parallel_pair.one }) /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then the cokernel of `f` is a cokernel of `l`. -/ def cokernel.of_iso_comp [has_cokernel f] {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) : is_colimit (cokernel_cofork.of_π (cokernel.π f) $ show l ≫ cokernel.π f = 0, by simp [i.eq_inv_comp.2 h]) := is_cokernel.of_iso_comp f l i h $ colimit.is_colimit _ /-- If `s` is any colimit cokernel cocone over `f` and `i` is an isomorphism such that `s.π ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def is_cokernel.cokernel_iso {Z : C} (l : Y ⟶ Z) {s : cokernel_cofork f} (hs : is_colimit s) (i : s.X ≅ Z) (h : cofork.π s ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ show f ≫ l = 0, by simp [←h]) := is_colimit.of_iso_colimit hs $ cocones.ext i $ λ j, by { cases j, { simp }, { exact h } } /-- If `i` is an isomorphism such that `cokernel.π f ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def cokernel.cokernel_iso [has_cokernel f] {Z : C} (l : Y ⟶ Z) (i : cokernel f ≅ Z) (h : cokernel.π f ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ by simp [←h]) := is_cokernel.cokernel_iso f l (colimit.is_colimit _) i h end transport end category_theory.limits namespace category_theory.limits variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] /-- `has_kernels` represents a choice of kernel for every morphism -/ class has_kernels := (has_limit : Π {X Y : C} (f : X ⟶ Y), has_kernel f) /-- `has_cokernels` represents a choice of cokernel for every morphism -/ class has_cokernels := (has_colimit : Π {X Y : C} (f : X ⟶ Y), has_cokernel f) attribute [instance, priority 100] has_kernels.has_limit has_cokernels.has_colimit /-- Kernels are finite limits, so if `C` has all finite limits, it also has all kernels -/ def has_kernels_of_has_finite_limits [has_finite_limits C] : has_kernels C := { has_limit := infer_instance } /-- Cokernels are finite limits, so if `C` has all finite colimits, it also has all cokernels -/ def has_cokernels_of_has_finite_colimits [has_finite_colimits C] : has_cokernels C := { has_colimit := infer_instance } end category_theory.limits
d88fbc37eb739df657527dd05cccd5dc49922109
618003631150032a5676f229d13a079ac875ff77
/archive/100-theorems-list/82_cubing_a_cube.lean
a1b698a3069d1aa70335182486d7012f81e3c539
[ "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
23,047
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import data.real.basic import data.set.disjointed import data.set.intervals import set_theory.cardinal /-! Proof that a cube (in dimension n ≥ 3) cannot be cubed: There does not exist a partition of a cube into finitely many smaller cubes (at least two) of different sizes. We follow the proof described here: http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof -/ open real set function fin noncomputable theory variable {n : ℕ} /-- Given three intervals `I, J, K` such that `J ⊂ I`, neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and `K` does not lie completely to the left nor completely to the right of `J`. Then `I ∩ K \ J` is nonempty. -/ lemma Ico_lemma {α} [decidable_linear_order α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α} (h₁ : x₁ < y₁) (hy : y₁ < y₂) (h₂ : y₂ < x₂) (hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) : ∃w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ := begin simp at hw, refine ⟨max x₁ (min w y₂), _, _, _⟩, { simp [le_refl, lt_trans h₁ (lt_trans hy h₂), h₂] }, { simp [lt_irrefl, not_le_of_lt h₁], intros, apply hw.1, assumption }, { simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂] at ⊢ } end /-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point of the cube, a width `w` and a proof that `w > 0`. We use functions from `fin n` to denote vectors. -/ structure cube (n : ℕ) : Type := (b : fin n → ℝ) -- bottom-left coordinate (w : ℝ) -- width (hw : 0 < w) namespace cube lemma hw' (c : cube n) : 0 ≤ c.w := le_of_lt c.hw /-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/ def side (c : cube n) (j : fin n) : set ℝ := Ico (c.b j) (c.b j + c.w) @[simp] lemma b_mem_side (c : cube n) (j : fin n) : c.b j ∈ c.side j := by simp [side, cube.hw, le_refl] def to_set (c : cube n) : set (fin n → ℝ) := { x | ∀j, x j ∈ side c j } def to_set_subset {c c' : cube n} : c.to_set ⊆ c'.to_set ↔ ∀j, c.side j ⊆ c'.side j := begin split, intros h j x hx, let f : fin n → ℝ := λ j', if j' = j then x else c.b j', have : f ∈ c.to_set, { intro j', by_cases hj' : j' = j; simp [f, hj', if_pos, if_neg, hx] }, convert h this j, { simp [f, if_pos] }, intros h f hf j, exact h j (hf j) end def to_set_disjoint {c c' : cube n} : disjoint c.to_set c'.to_set ↔ ∃j, disjoint (c.side j) (c'.side j) := begin split, intros h, classical, by_contra h', simp only [not_disjoint_iff, classical.skolem, not_exists] at h', cases h' with f hf, apply not_disjoint_iff.mpr ⟨f, _, _⟩ h; intro j, exact (hf j).1, exact (hf j).2, rintro ⟨j, hj⟩, rw [set.disjoint_iff], rintros f ⟨h1f, h2f⟩, apply not_disjoint_iff.mpr ⟨f j, h1f j, h2f j⟩ hj end lemma b_mem_to_set (c : cube n) : c.b ∈ c.to_set := by simp [to_set] protected def tail (c : cube (n+1)) : cube n := ⟨tail c.b, c.w, c.hw⟩ lemma side_tail (c : cube (n+1)) (j : fin n) : c.tail.side j = c.side j.succ := rfl def bottom (c : cube (n+1)) : set (fin (n+1) → ℝ) := { x | x 0 = c.b 0 ∧ tail x ∈ c.tail.to_set } lemma b_mem_bottom (c : cube (n+1)) : c.b ∈ c.bottom := by simp [bottom, to_set, side, cube.hw, le_refl, cube.tail] def xm (c : cube (n+1)) : ℝ := c.b 0 + c.w lemma b_lt_xm (c : cube (n+1)) : c.b 0 < c.xm := by simp [xm, hw] lemma b_ne_xm (c : cube (n+1)) : c.b 0 ≠ c.xm := ne_of_lt c.b_lt_xm def shift_up (c : cube (n+1)) : cube (n+1) := ⟨cons c.xm $ tail c.b, c.w, c.hw⟩ @[simp] lemma tail_shift_up (c : cube (n+1)) : c.shift_up.tail = c.tail := by simp [shift_up, cube.tail] @[simp] lemma head_shift_up (c : cube (n+1)) : c.shift_up.b 0 = c.xm := rfl def unit_cube : cube n := ⟨λ _, 0, 1, by norm_num⟩ @[simp] lemma side_unit_cube {j : fin n} : unit_cube.side j = Ico 0 1 := by norm_num [unit_cube, side] end cube open cube variables {ι : Type} [fintype ι] {cs : ι → cube (n+1)} {i i' : ι} /-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/ def correct (cs : ι → cube n) : Prop := pairwise (disjoint on (cube.to_set ∘ cs)) ∧ (⋃(i : ι), (cs i).to_set) = unit_cube.to_set ∧ injective (cube.w ∘ cs) ∧ 2 ≤ cardinal.mk ι ∧ 3 ≤ n variable (h : correct cs) include h lemma to_set_subset_unit_cube {i} : (cs i).to_set ⊆ unit_cube.to_set := by { rw [←h.2.1], exact subset_Union _ i } lemma side_subset {i j} : (cs i).side j ⊆ Ico 0 1 := by { have := to_set_subset_unit_cube h, rw [to_set_subset] at this, convert this j, norm_num [unit_cube] } lemma zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x := (side_subset h hx).1 lemma zero_le_of_mem {i p} (hp : p ∈ (cs i).to_set) (j) : 0 ≤ p j := zero_le_of_mem_side h (hp j) lemma zero_le_b {i j} : 0 ≤ (cs i).b j := zero_le_of_mem h (cs i).b_mem_to_set j lemma b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 := by { have := side_subset h, rw [side, Ico_subset_Ico_iff] at this, convert this.2, simp [hw] } /-- The width of any cube in the partition cannot be 1. -/ lemma w_ne_one (i : ι) : (cs i).w ≠ 1 := begin intro hi, have := h.2.2.2.1, rw [cardinal.two_le_iff' i] at this, cases this with i' hi', let p := (cs i').b, have hp : p ∈ (cs i').to_set := (cs i').b_mem_to_set, have h2p : p ∈ (cs i).to_set, { intro j, split, transitivity (0 : ℝ), { rw [←add_le_add_iff_right (1 : ℝ)], convert b_add_w_le_one h, rw hi, rw zero_add }, apply zero_le_b h, apply lt_of_lt_of_le (side_subset h $ (cs i').b_mem_side j).2, simp [hi, zero_le_b h] }, apply not_disjoint_iff.mpr ⟨p, hp, h2p⟩, apply h.1, exact hi'.symm end /-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by bottoms of (other) cubes in the family. -/ lemma shift_up_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) : (cs i).shift_up.bottom ⊆ ⋃(i : ι), (cs i).bottom := begin intros p hp, cases hp with hp0 hps, rw [tail_shift_up] at hps, have : p ∈ (unit_cube : cube (n+1)).to_set, { simp only [to_set, forall_fin_succ, hp0, side_unit_cube, mem_set_of_eq, mem_Ico, head_shift_up], refine ⟨⟨_, _⟩, _⟩, { rw [←zero_add (0 : ℝ)], apply add_le_add, apply zero_le_b h, apply (cs i).hw' }, { exact lt_of_le_of_ne (b_add_w_le_one h) hc }, intro j, exact side_subset h (hps j) }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i', rfl⟩, hi'⟩, rw [mem_Union], use i', refine ⟨_, λ j, hi' j.succ⟩, have : i ≠ i', { rintro rfl, apply not_le_of_lt (hi' 0).2, rw [hp0], refl }, have := h.1 i i' this, rw [on_fun, to_set_disjoint, exists_fin_succ] at this, rcases this with h0|⟨j, hj⟩, rw [hp0], symmetry, apply eq_of_Ico_disjoint h0 (by simp [hw]) _, convert hi' 0, rw [hp0], refl, exfalso, apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj end omit h /-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes completely cover the valley and none of those cubes is partially outside the square. We also require that no cube on it has the same size as the valley (so that there are at least two cubes on the valley). This is the main concept in the formalization. We prove that the smallest cube on a valley has another valley on the top of it, which gives an infinite sequence of cubes in the partition, which contradicts the finiteness. A valley is characterized by a cube `c` (which is not a cube in the family cs) by considering the bottom face of `c`. -/ def valley (cs : ι → cube (n+1)) (c : cube (n+1)) : Prop := c.bottom ⊆ (⋃(i : ι), (cs i).bottom) ∧ (∀i, (cs i).b 0 = c.b 0 → (∃x, x ∈ (cs i).tail.to_set ∩ c.tail.to_set) → (cs i).tail.to_set ⊆ c.tail.to_set) ∧ ∀(i : ι), (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w variables {c : cube (n+1)} (v : valley cs c) /-- The bottom of the unit cube is a valley -/ lemma valley_unit_cube (h : correct cs) : valley cs unit_cube := begin refine ⟨_, _, _⟩, { intro v, simp [bottom], intros h0 hv, have : v ∈ (unit_cube : cube (n+1)).to_set, { dsimp [to_set], rw [forall_fin_succ, h0], split, norm_num [side, unit_cube], exact hv }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i, rfl⟩, hi⟩, use i, split, { apply le_antisymm, rw h0, exact zero_le_b h, exact (hi 0).1 }, intro j, exact hi _ }, { intros i hi h', rw to_set_subset, intro j, convert side_subset h, simp [side_tail] }, { intros i hi, exact w_ne_one h i } end /-- the cubes which lie in the valley `c` -/ def bcubes (cs : ι → cube (n+1)) (c : cube (n+1)) : set ι := { i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.to_set ⊆ c.tail.to_set } /-- A cube which lies on the boundary of a valley in dimension `j` -/ def on_boundary (hi : i ∈ bcubes cs c) (j : fin n) : Prop := c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w lemma tail_sub (hi : i ∈ bcubes cs c) : ∀j, (cs i).tail.side j ⊆ c.tail.side j := by { rw [←to_set_subset], exact hi.2 } lemma bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 := by { convert b_mem_side (cs i) _ using 1, rw hi.1 } lemma b_le_b (hi : i ∈ bcubes cs c) (j : fin n) : c.b j.succ ≤ (cs i).b j.succ := (tail_sub hi j $ b_mem_side _ _).1 lemma t_le_t (hi : i ∈ bcubes cs c) (j : fin n) : (cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w := begin have h' := tail_sub hi j, dsimp only [side] at h', rw [Ico_subset_Ico_iff] at h', exact h'.2, simp [hw] end include h v /-- Every cube in the valley must be smaller than it -/ lemma w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w := begin apply lt_of_le_of_ne _ (v.2.2 i hi.1), have j : fin n := ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩, rw [←add_le_add_iff_left ((cs i).b j.succ)], apply le_trans (t_le_t hi j), rw [add_le_add_iff_right], apply b_le_b hi, end open cardinal /-- There are at least two cubes in a valley -/ lemma two_le_mk_bcubes : 2 ≤ cardinal.mk (bcubes cs c) := begin rw [two_le_iff], rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩, have h2i : i ∈ bcubes cs c := ⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, λ j, c.b_mem_side j.succ⟩⟩, let j : fin (n+1) := ⟨2, h.2.2.2.2⟩, have hj : 0 ≠ j := by { intro h', have := congr_arg fin.val h', contradiction }, let p : fin (n+1) → ℝ := λ j', if j' = j then c.b j + (cs i).w else c.b j', have hp : p ∈ c.bottom, { split, { simp only [bottom, p, if_neg hj] }, intro j', simp [tail, side_tail], by_cases hj' : j'.succ = j, { simp [p, -add_comm, if_pos, side, hj', hw', w_lt_w h v h2i] }, { simp [p, -add_comm, if_neg hj'] }}, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, refine ⟨⟨i, h2i⟩, ⟨i', h2i'⟩, _⟩, intro hii', cases congr_arg subtype.val hii', apply not_le_of_lt (hi'.2 ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩).2, simp only [-add_comm, tail, cube.tail, p], rw [if_pos], simp [-add_comm], exact (hi.2 _).1, refl end /-- There is a cube in the valley -/ lemma nonempty_bcubes : (bcubes cs c).nonempty := begin rw [←set.ne_empty_iff_nonempty], intro h', have := two_le_mk_bcubes h v, rw h' at this, apply not_lt_of_le this, rw mk_emptyc, norm_cast, norm_num end /-- There is a smallest cube in the valley -/ lemma exists_mi : ∃(i : ι), i ∈ bcubes cs c ∧ ∀(i' ∈ bcubes cs c), (cs i).w ≤ (cs i').w := by simpa using (bcubes cs c).exists_min_image (λ i, (cs i).w) (finite.of_fintype _) (nonempty_bcubes h v) /-- We let `mi` be the (index for the) smallest cube in the valley `c` -/ def mi : ι := classical.some $ exists_mi h v variables {h v} lemma mi_mem_bcubes : mi h v ∈ bcubes cs c := (classical.some_spec $ exists_mi h v).1 lemma mi_minimal (hi : i ∈ bcubes cs c) : (cs $ mi h v).w ≤ (cs i).w := (classical.some_spec $ exists_mi h v).2 i hi lemma mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) : (cs $ mi h v).w < (cs i).w := by { apply lt_of_le_of_ne (mi_minimal hi), apply h.2.2.1.ne, apply hii' } /-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/ lemma mi_xm_ne_one : (cs $ mi h v).xm ≠ 1 := begin apply ne_of_lt, rcases (two_le_iff' _).mp (two_le_mk_bcubes h v) with ⟨⟨i, hi⟩, h2i⟩, swap, exact ⟨mi h v, mi_mem_bcubes⟩, apply lt_of_lt_of_le _ (b_add_w_le_one h), exact i, exact 0, rw [xm, mi_mem_bcubes.1, hi.1, _root_.add_lt_add_iff_left], apply mi_strict_minimal _ hi, intro h', apply h2i, rw subtype.ext, exact h' end /-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all other cubes on the same boundary extend further from the boundary. More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`, such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th coordinate `x` -/ lemma smallest_on_boundary {j} (bi : on_boundary (mi_mem_bcubes : mi h v ∈ _) j) : ∃(x : ℝ), x ∈ c.side j.succ \ (cs $ mi h v).side j.succ ∧ ∀{{i'}} (hi' : i' ∈ bcubes cs c), i' ≠ mi h v → (cs $ mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, cases bi, { refine ⟨(cs i).b j.succ + (cs i).w, ⟨_, _⟩, _⟩, { simp [side, bi, hw', w_lt_w h v hi] }, { intro h', simpa [i, lt_irrefl] using h'.2 }, intros i' hi' i'_i h2i', split, apply le_trans h2i'.1, { simp [hw'] }, apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _), simp [bi.symm, b_le_b hi'] }, let s := bcubes cs c \ { i }, have hs : s.nonempty, { rcases (two_le_iff' (⟨i, hi⟩ : bcubes cs c)).mp (two_le_mk_bcubes h v) with ⟨⟨i', hi'⟩, h2i'⟩, refine ⟨i', hi', _⟩, simp only [mem_singleton_iff], intro h, apply h2i', simp [h] }, rcases set.exists_min_image s (w ∘ cs) (finite.of_fintype _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩, rw [mem_singleton_iff] at h2i', let x := c.b j.succ + c.w - (cs i').w, have hx : x < (cs i).b j.succ, { dsimp only [x], rw [←bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero], apply mi_strict_minimal (ne.symm h2i') hi' }, refine ⟨x, ⟨_, _⟩, _⟩, { simp only [side, x, -add_comm, -add_assoc, neg_lt_zero, hw, add_lt_iff_neg_left, and_true, mem_Ico, sub_eq_add_neg], rw [add_assoc, le_add_iff_nonneg_right, ←sub_eq_add_neg, sub_nonneg], apply le_of_lt (w_lt_w h v hi') }, { simp only [side, not_and_distrib, not_lt, add_comm, not_le, mem_Ico], left, exact hx }, intros i'' hi'' h2i'' h3i'', split, swap, apply lt_trans hx h3i''.2, simp only [x], rw [le_sub_iff_add_le], refine le_trans _ (t_le_t hi'' j), rw [add_le_add_iff_left], apply h3i' i'' ⟨hi'', _⟩, simp [mem_singleton, h2i''] end variables (h v) /-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/ lemma mi_not_on_boundary (j : fin n) : ¬on_boundary (mi_mem_bcubes : mi h v ∈ _) j := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, rcases (two_le_iff' j).mp _ with ⟨j', hj'⟩, swap, { rw [mk_fin, ←nat.cast_two, nat_cast_le], apply nat.le_of_succ_le_succ h.2.2.2.2 }, intro hj, rcases smallest_on_boundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩, let p : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j then x else (cs i).b j₂.succ), have hp : p ∈ c.bottom, { simp [bottom, p, to_set, tail, side_tail], intro j₂, by_cases hj₂ : j₂ = j, simp [hj₂, hx], simp [hj₂], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, have i_i' : i ≠ i', { rintro rfl, simpa [p, side_tail, i, h2x] using hi'.2 j }, have : nonempty ↥((cs i').tail.side j' \ (cs i).tail.side j'), { apply nonempty_Ico_sdiff, apply mi_strict_minimal i_i' h2i', apply hw }, rcases this with ⟨⟨x', hx'⟩⟩, let p' : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j' then x' else (cs i).b j₂.succ), have hp' : p' ∈ c.bottom, { simp [bottom, p', to_set, tail, side_tail], intro j₂, by_cases hj₂ : j₂ = j', simp [hj₂], apply tail_sub h2i', apply hx'.1, simp [hj₂], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩, have i'_i'' : i' ≠ i'', { rintro ⟨⟩, have : (cs i).b ∈ (cs i').to_set, { simp [to_set, forall_fin_succ, hi.1, bottom_mem_side h2i'], intro j₂, by_cases hj₂ : j₂ = j, simpa [side_tail, p', hj', hj₂] using hi''.2 j, simpa [hj₂] using hi'.2 j₂ }, apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_to_set, this⟩ (h.1 i i' i_i') }, have i_i'' : i ≠ i'', { intro h, induction h, simpa [hx'.2] using hi''.2 j' }, apply not.elim _ (h.1 i' i'' i'_i''), simp only [on_fun, to_set_disjoint, not_disjoint_iff, forall_fin_succ, not_exists, comp_app], refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, _⟩, intro j₂, by_cases hj₂ : j₂ = j, { cases hj₂, refine ⟨x, _, _⟩, { convert hi'.2 j, simp [p] }, apply h3x h2i'' i_i''.symm, convert hi''.2 j, simp [p', hj'] }, by_cases h2j₂ : j₂ = j', { cases h2j₂, refine ⟨x', hx'.1, _⟩, convert hi''.2 j', simp }, refine ⟨(cs i).b j₂.succ, _, _⟩, { convert hi'.2 j₂, simp [hj₂] }, { convert hi''.2 j₂, simp [h2j₂] } end variables {h v} /-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/ lemma mi_not_on_boundary' (j : fin n) : c.tail.b j < (cs (mi h v)).tail.b j ∧ (cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w := begin have := mi_not_on_boundary h v j, simp only [on_boundary, not_or_distrib] at this, cases this with h1 h2, split, apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1, apply lt_of_le_of_ne _ h2, apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2, simp [hw] end /-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward than `mi`. -/ def valley_mi : valley cs ((cs (mi h v)).shift_up) := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, refine ⟨_, _, _⟩, { intro p, apply shift_up_bottom_subset_bottoms h mi_xm_ne_one }, { rintros i' hi' ⟨p2, hp2, h2p2⟩, simp only [head_shift_up] at hi', classical, by_contra h2i', rw [tail_shift_up] at h2p2, simp only [not_subset, tail_shift_up] at h2i', rcases h2i' with ⟨p1, hp1, h2p1⟩, have : ∃p3, p3 ∈ (cs i').tail.to_set ∧ p3 ∉ (cs i).tail.to_set ∧ p3 ∈ c.tail.to_set, { simp [to_set, not_forall] at h2p1, cases h2p1 with j hj, rcases Ico_lemma (mi_not_on_boundary' j).1 (by simp [hw]) (mi_not_on_boundary' j).2 (le_trans (hp2 j).1 $ le_of_lt (h2p2 j).2) (le_trans (h2p2 j).1 $ le_of_lt (hp2 j).2) ⟨hj, hp1 j⟩ with ⟨w, hw, h2w, h3w⟩, refine ⟨λ j', if j' = j then w else p2 j', _, _, _⟩, { intro j', by_cases h : j' = j, simp [if_pos h], convert h3w, simp [if_neg h], exact hp2 j' }, { simp [to_set, not_forall], use j, rw [if_pos rfl], convert h2w }, { intro j', by_cases h : j' = j, simp [if_pos h, side_tail], convert hw, simp [if_neg h], apply hi.2, apply h2p2 }}, rcases this with ⟨p3, h1p3, h2p3, h3p3⟩, let p := @cons n (λ_, ℝ) (c.b 0) p3, have hp : p ∈ c.bottom, { refine ⟨rfl, _⟩, rwa [tail_cons] }, rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c, { use hi''.1.symm, apply v.2.1 i'' hi''.1.symm, use tail p, split, exact hi''.2, rw [tail_cons], exact h3p3 }, have h3i'' : (cs i).w < (cs i'').w, { apply mi_strict_minimal _ h2i'', rintro rfl, apply h2p3, convert hi''.2, rw [tail_cons] }, let p' := @cons n (λ_, ℝ) (cs i).xm p3, have hp' : p' ∈ (cs i').to_set, { simpa [to_set, forall_fin_succ, p', hi'.symm] using h1p3 }, have h2p' : p' ∈ (cs i'').to_set, { simp [to_set, forall_fin_succ, p'], refine ⟨_, by simpa [to_set, p] using hi''.2⟩, have : (cs i).b 0 = (cs i'').b 0, { by rw [hi.1, h2i''.1] }, simp [side, hw', xm, this, h3i''] }, apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩, apply h.1, rintro rfl, apply (cs i).b_ne_xm, rw [←hi', ←hi''.1, hi.1], refl }, { intros i' hi' h2i', dsimp [shift_up] at h2i', replace h2i' := h.2.2.1 h2i'.symm, induction h2i', exact b_ne_xm (cs i) hi' } end variables (h) omit v /-- We get a sequence of cubes whose size is decreasing -/ noncomputable def sequence_of_cubes : ℕ → { i : ι // valley cs ((cs i).shift_up) } | 0 := let v := valley_unit_cube h in ⟨mi h v, valley_mi⟩ | (k+1) := let v := (sequence_of_cubes k).2 in ⟨mi h v, valley_mi⟩ def decreasing_sequence (k : ℕ) : order_dual ℝ := (cs (sequence_of_cubes h k).1).w lemma strict_mono_sequence_of_cubes : strict_mono $ decreasing_sequence h := strict_mono.nat $ begin intro k, let v := (sequence_of_cubes h k).2, dsimp [decreasing_sequence, sequence_of_cubes], apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _), end omit h /-- The infinite sequence of cubes contradicts the finiteness of the family. -/ theorem not_correct : ¬correct cs := begin intro h, apply not_le_of_lt (lt_omega_iff_fintype.mpr ⟨_inst_1⟩), rw [omega, lift_id], fapply mk_le_of_injective, exact λ n, (sequence_of_cubes h n).1, intros n m hnm, apply strict_mono.injective (strict_mono_sequence_of_cubes h), dsimp only [decreasing_sequence], rw hnm end /-- A cube cannot be cubed. -/ theorem cannot_cube_a_cube : ∀{n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3 ∀{ι : Type} [fintype ι] {cs : ι → cube n}, -- given a finite collection of (hyper)cubes 2 ≤ cardinal.mk ι → -- containing at least two elements pairwise (disjoint on (cube.to_set ∘ cs)) → -- which is pairwise disjoint (⋃(i : ι), (cs i).to_set) = unit_cube.to_set → -- whose union is the unit cube injective (cube.w ∘ cs) → -- such that the widths of all cubes are different false := -- then we can derive a contradiction begin intros n hn ι hι cs h1 h2 h3 h4, resetI, rcases n, cases hn, exact not_correct ⟨h2, h3, h4, h1, hn⟩ end
78c1bf9abd25e329b36c31d9c0eb11012f693e00
4fa161becb8ce7378a709f5992a594764699e268
/src/data/list/basic.lean
2ad5b7cf7925a4edb4a13d86a6274899c4f83ed6
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
155,161
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import algebra.group import deprecated.group import data.nat.basic import order.rel_classes /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_injective {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_injective e, congr_arg _⟩ /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma length_injective [subsingleton α] : injective (length : list α → ℕ) := length_injective_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := left_inverse.injective reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-! ### is_nil -/ lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] := list.cases_on l (by simp [is_nil]) (by simp [is_nil]) /-! ### last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl /-! ### sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /-! ### nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } end monoid @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_add_right (le_refl _) }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] section variables {G : Type*} [comm_group G] attribute [to_additive] alternating_prod @[simp, to_additive] lemma alternating_prod_nil : alternating_prod ([] : list G) = 1 := rfl @[simp, to_additive] lemma alternating_prod_singleton (g : G) : alternating_prod [g] = g := rfl @[simp, to_additive alternating_sum_cons_cons'] lemma alternating_prod_cons_cons (g h : G) (l : list G) : alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) : alternating_sum (g :: h :: l) = g - h + alternating_sum l := rfl end /-! ### join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /-! ### all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /-! ### count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /-! ### prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix theorem tail_subset (l : list α) : tail l ⊆ l := (sublist_of_suffix (tail_suffix l)).subset theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /-! ### sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, nat.pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_injective reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /-! ### sublists_len -/ /-- Auxiliary function to construct the list of all sublists of a given length. Given an integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) /-- The list of all sublists of a list `l` that are of length `n`. For instance, for `l = [0, 1, 2, 3]` and `n = 2`, one gets `[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/ def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact (sublists_len_sublist_sublists' _ _).append ((sublists_len_sublist_sublists' _ _).map _) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact IH.append ((IHn s).map _) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 ((sublists_len_sublist_sublists' _ _).subset h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /-! ### permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /-! ### insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /-! ### sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /-! ### union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /-! ### inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose -- A jumble of lost lemmas: theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r end list
e1c61db6a46d297e1b4608e242629919d64afb96
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic15.lean
42f5e2cdaa2b9bd804bfac199d2bfc817c0aef53
[ "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
274
lean
import logic open tactic constant A : Type.{1} constant f : A → A → A open eq theorem tst {a b c : A} (H1 : a = b) (H2 : b = c) : f a (f b b) = f b (f c c) := by apply (subst H1); trace "trying again... "; state; apply (subst H2); apply eq.refl
2301718ee3a5890985f3a614d363557dae26db82
ea4aee6b11f86433e69bb5e50d0259e056d0ae61
/src/tidy/congr_struct.lean
ebf08627d7baa947ab336d6cb1198c8a3190780b
[]
no_license
timjb/lean-tidy
e18feff0b7f0aad08c614fb4d34aaf527bf21e20
e767e259bf76c69edfd4ab8af1b76e6f1ed67f48
refs/heads/master
1,624,861,693,182
1,504,411,006,000
1,504,411,006,000
103,740,824
0
0
null
1,505,553,968,000
1,505,553,968,000
null
UTF-8
Lean
false
false
3,274
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 .applicable open tactic namespace tactic open expr /-- Given a fully applied structure type `ty` with fields `f1`...`fn`, synthesize the proof `∀ x : ty, ty.mk x.f1 ... x.fn = x`. The proof can be extracted into a new definition using ``` def ty.eta := by mk_struct_eta ```(ty) >>= exact ``` -/ meta def mk_struct_eta (ty : expr) : tactic expr := do (const n ls) ← pure ty.get_app_fn | fail "not a structure", env ← get_env, fields ← env.structure_fields n <|> fail "not a structure", [ctor] ← pure $ env.constructors_of n, let ctor := (const ctor ls).mk_app ty.get_app_args, x ← mk_local_def `x ty, fields ← fields.mmap $ λ f, to_expr (pexpr.mk_field_macro (pexpr.of_expr x) f), proof_ty ← mk_app ``eq [ctor.mk_app fields, x], prod.snd <$> solve_aux (pis [x] proof_ty) (do x ← intro `_, cases x, reflexivity) end tactic namespace tactic.interactive open expr tactic private meta def common_app_prefix : expr → expr → tactic expr | (app e₁ e₁') (app e₂ e₂') := (is_def_eq e₁ e₂ *> pure e₁) <|> common_app_prefix e₁ e₂ | e₁ e₂ := fail "no common head symbol" /-- Given a goal of form `f a₁ ... aₙ == f a₁' ... aₙ'`, this tactic breaks it down to subgoals `a₁ == a₁'`, ... Subgoals provable by reflexivity are dispensed automatically. The goal can also be a homogenous equality. New subgoals will use homogenous equalities where possible. -/ meta def congr_args : tactic unit := do tgt ← target, (lhs, rhs) ← match tgt with | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs == %%rhs) := pure (lhs, rhs) | _ := fail "goal is not an equality" end, pre ← common_app_prefix lhs rhs, l ← mk_hcongr_lemma pre, tactic.apply l.proof, all_goals $ try refl /-- Given a goal that equates two structure values, this tactic breaks it down to subgoals equating each pair of fields. -/ meta def congr_struct : tactic unit := do `(%%lhs = %%rhs) ← target | fail "goal is not an equality", ty ← infer_type lhs, eta ← mk_struct_eta ty, apply ``(@eq.rec _ _ (λ lhs, lhs = %%rhs) _ _ %%(app eta lhs)), `(%%new_lhs = %%rhs) ← target, apply ``(@eq.rec _ _ (λ rhs, %%new_lhs = rhs) _ _ %%(app eta rhs)), congr_args end tactic.interactive -- congr_struct needs various helper lemmas. @[applicable] lemma heq_prop { α β : Prop } { a : α } { b : β } ( h : α = β ) : a == b := begin induction h, reflexivity end @[applicable] theorem {u v w z} funext_prop_001 { α : Type u } { β : Type v } { Z : α → β → Type w } { X : Π ( a : α ) ( b : β ) ( g : Z a b ), Type z } { p q r s : Π ( a : α ) ( b : β ) ( g : Z a b ), X a b g } ( h1 : p = r ) ( h2 : q = s ) : (∀ ( a : α ) ( b : β ) ( g : Z a b ), p a b g = q a b g ) = (∀ ( a : α ) ( b : β ) ( g : Z a b), r a b g = s a b g ) := begin induction h1, induction h2, reflexivity end
7ca5ada584d01a3be42ab08f2193020d040f34c3
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.20.lean
998f577085c76d12d1f6aa0ac73ddc6432a98329
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
140
lean
/- page 39 -/ import standard variables p q : Prop -- BEGIN example (H : p ∧ q) : q ∧ p := and.intro (and.right H) (and.left H) -- END
66b1dd722ececf1d678f93cbeb21bbd253ce4e79
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/int_eval.lean
971ac6cbab94b5ff7cf78fa6781bf68336ad4992
[ "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
557
lean
#eval (1073741823:int) #eval (1073741824:int) #eval ((1073741824:int) + (1:int) - (3:int)) #eval - (2:int) #eval - (1000:int) #eval 10 - (1000:int) #eval (1073741824:int) * 10 #eval (100000:int) * (-3:int) #eval -(1073741823:int) #eval ((1073741824:int) + (1:int) - (1:int)) #eval int.of_nat 1000 #eval int.of_nat 1073741823 def Abs : int → nat | (int.of_nat n) := n | (int.neg_succ_of_nat n) := n + 1 #eval 10000 #eval Abs (- 10000) #eval Abs (-1073741823) #eval Abs (-1073741824) #eval Abs (-1073741825) #eval -(1073741823:int) * 1000000000
be4c04d5cda38bee08f6deb20ab4a8e3e2b0634e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/match2.lean
34117a680c0f6dbfc3157fa1935ec3f38f3057f0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,903
lean
#print "---- Op" inductive Op : Nat → Nat → Type | mk : ∀ n, Op n n structure Node : Type where id₁ : Nat id₂ : Nat o : Op id₁ id₂ def h1 (x : List Node) : Bool := match x with | _ :: Node.mk _ _ (Op.mk 0) :: _ => true | _ => false def mkNode (n : Nat) : Node := { id₁ := n, id₂ := n, o := Op.mk n } #eval h1 [mkNode 1, mkNode 0, mkNode 3] #eval h1 [mkNode 1, mkNode 1, mkNode 3] #eval h1 [mkNode 0] #eval h1 [] #print "---- Foo 1" inductive Foo : Bool → Type | bar : Foo false | baz : Foo false def h2 {b : Bool} (x : Foo b) : Bool := match b, x with | _, Foo.bar => true | _, Foo.baz => false #eval h2 Foo.bar #eval h2 Foo.baz def h2' {b : Bool} (x : Foo b) : Bool := match x with | Foo.bar => true | Foo.baz => false #print "---- Foo 2" def h3 {b : Bool} (x : Foo b) : Bool := match b, x with | _, Foo.bar => true | _, _ => false #eval h3 Foo.bar #eval h3 Foo.baz #print "---- Op 2" def h4 (x : List Node) : Bool := match x with | _ :: ⟨1, 1, Op.mk 1⟩ :: _ => true | _ => false #eval h4 [mkNode 1, mkNode 0, mkNode 3] #eval h4 [mkNode 1, mkNode 1, mkNode 3] #eval h4 [mkNode 0] #eval h4 [] #print "---- Foo 3" set_option pp.all true def h5 {b : Bool} (x : Foo b) : Bool := match b, x with | _, Foo.bar => true | c, y => false def h5' {b : Bool} (x : Foo b) : Bool := match x with | Foo.bar => true | y => false def h6 {b : Bool} (x : Foo b) : Bool := match b, x with | _, Foo.bar => true | b, x => false def h6' {b : Bool} (x : Foo b) : Bool := match (generalizing := true) b, x : (b : Bool) → Foo b → Bool with | _, Foo.bar => true | b, x => false def h6'' {b : Bool} (x : Foo b) : Bool := match (generalizing := false) b, x : (b : Bool) → Foo b → Bool with | _, Foo.bar => true | b, x => false
589c40bce1bdc91cefd366e56c874661855ea018
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/nary_overload2.lean
cdd13d0dacf3ca72d84e6bc73b0433ce282ca326
[ "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
390
lean
import data.list data.examples.vector open nat list vector check [(1:nat), 2, 3] check ([1, 2, 3] : vector nat _) check ([1, 2, 3] : list nat) check (#list [(1:nat), 2, 3]) check (#vector [(1:nat), 2, 3]) example : (#vector [1, 2, 3]) = [(1:nat), 2, 3] := rfl example : (#vector [1, 2, 3]) = ([1, 2, 3] : vector nat _) := rfl example : (#list [1, 2, 3]) = ([1, 2, 3] : list nat) := rfl
948f755e74e4cff972edc4e42a54a82dd1386123
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/duplicate.lean
638c67ce66c5f9d89a9e9a95aca3d8e16427e291
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,323
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky, Chris Hughes -/ import data.list.nodup /-! # List duplicates ## Main definitions * `list.duplicate x l : Prop` is an inductive property that holds when `x` is a duplicate in `l` ## Implementation details In this file, `x ∈+ l` notation is shorthand for `list.duplicate x l`. -/ variable {α : Type*} namespace list /-- Property that an element `x : α` of `l : list α` can be found in the list more than once. -/ inductive duplicate (x : α) : list α → Prop | cons_mem {l : list α} : x ∈ l → duplicate (x :: l) | cons_duplicate {y : α} {l : list α} : duplicate l → duplicate (y :: l) local infix ` ∈+ `:50 := list.duplicate variables {l : list α} {x : α} lemma mem.duplicate_cons_self (h : x ∈ l) : x ∈+ x :: l := duplicate.cons_mem h lemma duplicate.duplicate_cons (h : x ∈+ l) (y : α) : x ∈+ y :: l := duplicate.cons_duplicate h lemma duplicate.mem (h : x ∈+ l) : x ∈ l := begin induction h with l' h y l' h hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ hm } end lemma duplicate.mem_cons_self (h : x ∈+ x :: l) : x ∈ l := begin cases h with _ h _ _ h, { exact h }, { exact h.mem } end @[simp] lemma duplicate_cons_self_iff : x ∈+ x :: l ↔ x ∈ l := ⟨duplicate.mem_cons_self, mem.duplicate_cons_self⟩ lemma duplicate.ne_nil (h : x ∈+ l) : l ≠ [] := λ H, (mem_nil_iff x).mp (H ▸ h.mem) @[simp] lemma not_duplicate_nil (x : α) : ¬ x ∈+ [] := λ H, H.ne_nil rfl lemma duplicate.ne_singleton (h : x ∈+ l) (y : α) : l ≠ [y] := begin induction h with l' h z l' h hm, { simp [ne_nil_of_mem h] }, { simp [ne_nil_of_mem h.mem] } end @[simp] lemma not_duplicate_singleton (x y : α) : ¬ x ∈+ [y] := λ H, H.ne_singleton _ rfl lemma duplicate.elim_nil (h : x ∈+ []) : false := not_duplicate_nil x h lemma duplicate.elim_singleton {y : α} (h : x ∈+ [y]) : false := not_duplicate_singleton x y h lemma duplicate_cons_iff {y : α} : x ∈+ y :: l ↔ (y = x ∧ x ∈ l) ∨ x ∈+ l := begin refine ⟨λ h, _, λ h, _⟩, { cases h with _ hm _ _ hm, { exact or.inl ⟨rfl, hm⟩ }, { exact or.inr hm } }, { rcases h with ⟨rfl|h⟩|h, { simpa }, { exact h.cons_duplicate } } end lemma duplicate.of_duplicate_cons {y : α} (h : x ∈+ y :: l) (hx : x ≠ y) : x ∈+ l := by simpa [duplicate_cons_iff, hx.symm] using h lemma duplicate_cons_iff_of_ne {y : α} (hne : x ≠ y) : x ∈+ y :: l ↔ x ∈+ l := by simp [duplicate_cons_iff, hne.symm] lemma duplicate.mono_sublist {l' : list α} (hx : x ∈+ l) (h : l <+ l') : x ∈+ l' := begin induction h with l₁ l₂ y h IH l₁ l₂ y h IH, { exact hx }, { exact (IH hx).duplicate_cons _ }, { rw duplicate_cons_iff at hx ⊢, rcases hx with ⟨rfl, hx⟩|hx, { simp [h.subset hx] }, { simp [IH hx] } } end /-- The contrapositive of `list.nodup_iff_sublist`. -/ lemma duplicate_iff_sublist : x ∈+ l ↔ [x, x] <+ l := begin induction l with y l IH, { simp }, { by_cases hx : x = y, { simp [hx, cons_sublist_cons_iff, singleton_sublist] }, { rw [duplicate_cons_iff_of_ne hx, IH], refine ⟨sublist_cons_of_sublist y, λ h, _⟩, cases h, { assumption }, { contradiction } } } end lemma nodup_iff_forall_not_duplicate : nodup l ↔ ∀ (x : α), ¬ x ∈+ l := by simp_rw [nodup_iff_sublist, duplicate_iff_sublist] lemma exists_duplicate_iff_not_nodup : (∃ (x : α), x ∈+ l) ↔ ¬ nodup l := by simp [nodup_iff_forall_not_duplicate] lemma duplicate.not_nodup (h : x ∈+ l) : ¬ nodup l := λ H, nodup_iff_forall_not_duplicate.mp H _ h lemma duplicate_iff_two_le_count [decidable_eq α] : (x ∈+ l) ↔ 2 ≤ count x l := by simp [duplicate_iff_sublist, le_count_iff_repeat_sublist] instance decidable_duplicate [decidable_eq α] (x : α) : ∀ (l : list α), decidable (x ∈+ l) | [] := is_false (not_duplicate_nil x) | (y :: l) := match decidable_duplicate l with | is_true h := is_true (h.duplicate_cons y) | is_false h := if hx : y = x ∧ x ∈ l then is_true (hx.left.symm ▸ hx.right.duplicate_cons_self) else is_false (by simpa [duplicate_cons_iff, h] using hx) end end list
89b1f5e1f48ebb611c171016263e70ee14ab3b69
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/data/fintype.lean
11844a2c5a427b3307908aa407b1a781a4ba8804
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
33,039
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin change multiset.card s = multiset.card s' at e', revert nd nd' h h' e', refine quotient.induction_on₂ s s' (λ l₁ l₂ (nd₁ : l₁.nodup) (nd₂ : l₂.nodup) (h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂) (e' : l₁.length = l₂.length), _), haveI := classical.dec_eq α, refine ⟨equiv.of_bijective ⟨_, _⟩⟩, { refine λ a, l₂.nth_le (l₁.index_of a) _, rw ← e', exact list.index_of_lt_length.2 (h₁ a) }, { intros a b h, simpa [h₁] using congr_arg l₁.nth (list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) }, { have := classical.dec_eq β, refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩, { rw e', exact list.index_of_lt_length.2 (h₂ b) }, { simp [nd₁] } } end end, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem fintype.univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem fintype.card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1), list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩, λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := by rw [fin.fintype]; simp [fintype.card, card, univ] @[instance, priority 0] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_card_gt_one [fintype α] (h : fintype.card α > 1) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive finset.sum_attach_univ] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 0] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, not_le_of_gt (nat.lt_succ_self (s.sum id)) $ @finset.single_le_sum _ _ _ id _ _ (λ _ _, nat.zero_le _) _ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
ba14d3f26565d1d9e7ba453dc0f8879c3f28d9a9
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/coercion_bug2.lean
6698eab4dae501e4e1c30acbc080b6a36b57f123
[ "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
261
lean
import data.nat open nat inductive list (T : Type) : Type := nil {} : list T, cons : T → list T → list T definition length {T : Type} : list T → nat := list.rec 0 (fun x l m, succ m) theorem length_nil {T : Type} : length (@list.nil T) = 0 := eq.refl _
8c22a9cbb7d4dc3fcbfd0e9636a9268ba50a2f49
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/extra/rec4.lean
eef6d94ebf837d8efef853b2edec02984820573e
[ "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
259
lean
import data.examples.vector open nat vector set_option pp.implicit true set_option pp.notation false definition diag {A : Type} : Π {n}, vector (vector A n) n → vector A n, diag nil := nil, diag ((a :: va) :: vs) := a :: diag (map tail vs)
cd673daef8c50acdefb1f133be71fa432984c08e
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/monoid_algebra.lean
451baaeda9cdbf2efd344ee1b0bb89f202780f42
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
26,060
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, Yury G. Kudryashov, Scott Morrison -/ import data.finsupp import ring_theory.algebra /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynominal σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k end namespace monoid_algebra variables {k G} local attribute [reducible] monoid_algebra section variables [semiring k] [monoid G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp [hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end end section variables [semiring k] [monoid G] lemma support_mul (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : monoid_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : monoid_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : monoid_algebra k G) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : monoid_algebra k G) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := monoid_algebra.zero_mul, mul_zero := monoid_algebra.mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } @[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := rfl | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by rw [single_mul_single, one_mul] } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma single_mul_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr, ext; split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] end instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [ring k] : has_neg (monoid_algebra k G) := by apply_instance instance [ring k] [monoid G] : ring (monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} instance [semiring k] : has_scalar k (monoid_algebra k G) := finsupp.has_scalar instance [semiring k] : semimodule k (monoid_algebra k G) := finsupp.semimodule G k lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- As a preliminary to defining the `k`-algebra structure on `add_monoid_algebra k G`, we define the underlying ring homomorphism. -/ def algebra_map' [semiring k] [monoid G] : k →+* monoid_algebra k G := { to_fun := single 1, map_one' := rfl, map_mul' := λ x y, by rw [single_mul_single, one_mul], map_zero' := single_zero, map_add' := λ x y, single_add, } instance [comm_semiring k] [monoid G] : algebra k (monoid_algebra k G) := { smul_def' := λ r a, ext (λ _, smul_apply.trans (single_one_mul_apply _ _ _).symm), commutes' := λ r f, ext $ λ _, by simp [algebra_map', single_one_mul_apply, mul_single_one_apply, mul_comm], ..algebra_map' } @[simp] lemma coe_algebra_map [comm_semiring k] [monoid G] : (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) = single 1 := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) b * of k G a := by simp instance [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self section lift variables (k G) [comm_semiring k] [monoid G] (R : Type u₃) [semiring R] [algebra k R] /-- Any monoid homomorphism `G →* R` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] R`. -/ def lift : (G →* R) ≃ (monoid_algebra k G →ₐ[k] R) := { inv_fun := λ f, (f : monoid_algebra k G →* R).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul, F.map_one], apply zero_smul }, map_mul' := begin intros f g, rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a ha, _), simp only, rw [finsupp.mul_sum, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a' ha', _), simp only, rw [sum_single_index, F.map_mul, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul end, map_zero' := sum_zero_index, map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul], commutes' := λ r, by rw [coe_algebra_map, sum_single_index, F.map_one, algebra.smul_def, mul_one]; apply zero_smul }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } variables {k G R} lemma lift_apply (F : G →* R) (f : monoid_algebra k G) : lift k G R F f = f.sum (λ a b, b • F a) := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] R) (x : G) : (lift k G R).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* R) (x) : lift k G R F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* R) (a b) : lift k G R F (single a b) = b • F a := by rw [single_eq_algebra_map_mul_of, ← algebra.smul_def, alg_hom.map_smul, lift_of] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] R) : F = lift k G R ((F : monoid_algebra k G →* R).comp (of k G)) := ((lift k G R).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] R) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] R⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := (lift k G R).symm.injective $ monoid_hom.ext h end lift section variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) : (module.restrict_scalars k (monoid_algebra k G) V) →ₗ[k] (module.restrict_scalars k (monoid_algebra k G) V) := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, by simp only [module.restrict_scalars_smul_def, coe_algebra_map, ←mul_smul, single_one_comm], }. @[simp] lemma group_smul.linear_map_apply [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [group G] [comm_ring k] {V : Type u₃} {gV : add_comm_group V} {mV : module (monoid_algebra k G) V} {W : Type u₃} {gW : add_comm_group W} {mW : module (monoid_algebra k G) W} (f : (module.restrict_scalars k (monoid_algebra k G) V) →ₗ[k] (module.restrict_scalars k (monoid_algebra k G) W)) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, rw [add_smul, linear_map.map_add, w, add_smul, add_left_inj, single_eq_algebra_map_mul_of, ←smul_smul, ←smul_smul], erw [f.map_smul, h g v], refl, } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a (f a) * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a (g a)) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end end monoid_algebra section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def add_monoid_algebra := G →₀ k end namespace add_monoid_algebra variables {k G} local attribute [reducible] add_monoid_algebra section variables [semiring k] [add_monoid G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma support_mul (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : add_monoid_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : add_monoid_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : add_monoid_algebra k G) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : add_monoid_algebra k G) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := add_monoid_algebra.zero_mul, mul_zero := add_monoid_algebra.mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : add_monoid_algebra k G) * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ + a₂ = z) (b₁ * b₂) 0) = ite (a₁ + x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_zero_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x + a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x + a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr, ext; split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_zero_mul_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] end instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. add_monoid_algebra.semiring } instance [ring k] : has_neg (add_monoid_algebra k G) := by apply_instance instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} instance [semiring k] : has_scalar k (add_monoid_algebra k G) := finsupp.has_scalar instance [semiring k] : semimodule k (add_monoid_algebra k G) := finsupp.semimodule G k /-- As a preliminary to defining the `k`-algebra structure on `add_monoid_algebra k G`, we define the underlying ring homomorphism. -/ def algebra_map' [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G := { to_fun := single 0, map_one' := rfl, map_mul' := λ x y, by rw [single_mul_single, zero_add], map_zero' := single_zero, map_add' := λ x y, single_add, } instance [comm_semiring k] [add_monoid G] : algebra k (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext x, exact smul_apply.trans (single_zero_mul_apply _ _ _).symm }, commutes' := λ r f, show single 0 r * f = f * single 0 r, by ext; rw [single_zero_mul_apply, mul_single_zero_apply, mul_comm], ..algebra_map', } @[simp] lemma coe_algebra_map [comm_semiring k] [add_monoid G] : (algebra_map k (add_monoid_algebra k G) : k → add_monoid_algebra k G) = single 0 := rfl /-- Any monoid homomorphism `multiplicative G →* R` can be lifted to an algebra homomorphism `add_monoid_algebra k G →ₐ[k] R`. -/ def lift [comm_semiring k] [add_monoid G] {R : Type u₃} [semiring R] [algebra k R] : (multiplicative G →* R) ≃ (add_monoid_algebra k G →ₐ[k] R) := { inv_fun := λ f, ((f : add_monoid_algebra k G →+* R) : add_monoid_algebra k G →* R).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul], erw [F.map_one], apply zero_smul }, map_mul' := begin intros f g, rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a ha, _), simp only, rw [finsupp.mul_sum, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a' ha', _), simp only, rw [sum_single_index], erw [F.map_mul], rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul end, map_zero' := sum_zero_index, map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul], commutes' := λ r, begin rw [coe_algebra_map, sum_single_index], erw [F.map_one], rw [algebra.smul_def, mul_one], apply zero_smul end, }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } -- It is hard to state the equivalent of `distrib_mul_action G (monoid_algebra k G)` -- because we've never discussed actions of additive groups. universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end add_monoid_algebra
a004a75227b639ef893444a5878b2d71f7ee1ba7
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/set_theory/zfc/basic.lean
7b7600f04ced7acfac026a4e369214ac12b29f4c
[ "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
41,030
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.set.lattice import logic.small import order.well_founded /-! # A model of ZFC In this file, we model Zermelo-Fraenkel set theory (+ Choice) using Lean's underlying type theory. We do this in four main steps: * Define pre-sets inductively. * Define extensional equivalence on pre-sets and give it a `setoid` instance. * Define ZFC sets by quotienting pre-sets by extensional equivalence. * Define classes as sets of ZFC sets. Then the rest is usual set theory. ## The model * `pSet`: Pre-set. A pre-set is inductively defined by its indexing type and its members, which are themselves pre-sets. * `Set`: ZFC set. Defined as `pSet` quotiented by `pSet.equiv`, the extensional equivalence. * `Class`: Class. Defined as `set Set`. * `Set.choice`: Axiom of choice. Proved from Lean's axiom of choice. ## Other definitions * `arity α n`: `n`-ary function `α → α → ... → α`. Defined inductively. * `arity.const a n`: `n`-ary constant function equal to `a`. * `pSet.type`: Underlying type of a pre-set. * `pSet.func`: Underlying family of pre-sets of a pre-set. * `pSet.equiv`: Extensional equivalence of pre-sets. Defined inductively. * `pSet.omega`, `Set.omega`: The von Neumann ordinal `ω` as a `pSet`, as a `Set`. * `pSet.arity.equiv`: Extensional equivalence of `n`-ary `pSet`-valued functions. Extension of `pSet.equiv`. * `pSet.resp`: Collection of `n`-ary `pSet`-valued functions that respect extensional equivalence. * `pSet.eval`: Turns a `pSet`-valued function that respect extensional equivalence into a `Set`-valued function. * `classical.all_definable`: All functions are classically definable. * `Set.is_func` : Predicate that a ZFC set is a subset of `x × y` that can be considered as a ZFC function `x → y`. That is, each member of `x` is related by the ZFC set to exactly one member of `y`. * `Set.funs`: ZFC set of ZFC functions `x → y`. * `Class.iota`: Definite description operator. ## Notes To avoid confusion between the Lean `set` and the ZFC `Set`, docstrings in this file refer to them respectively as "`set`" and "ZFC set". ## TODO Prove `Set.map_definable_aux` computably. -/ universes u v /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : ℕ → Type u | 0 := α | (n+1) := α → arity n @[simp] theorem arity_zero (α : Type u) : arity α 0 = α := rfl @[simp] theorem arity_succ (α : Type u) (n : ℕ) : arity α n.succ = (α → arity α n) := rfl namespace arity /-- Constant `n`-ary function with value `a`. -/ def const {α : Type u} (a : α) : ∀ n, arity α n | 0 := a | (n+1) := λ _, const n @[simp] theorem const_zero {α : Type u} (a : α) : const a 0 = a := rfl @[simp] theorem const_succ {α : Type u} (a : α) (n : ℕ) : const a n.succ = λ _, const a n := rfl theorem const_succ_apply {α : Type u} (a : α) (n : ℕ) (x : α) : const a n.succ x = const a n := rfl instance arity.inhabited {α n} [inhabited α] : inhabited (arity α n) := ⟨const default _⟩ end arity /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u | ⟨α, A⟩ := α /-- The underlying pre-set family of a pre-set -/ def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A @[simp] theorem mk_type (α A) : type ⟨α, A⟩ = α := rfl @[simp] theorem mk_func (α A) : func ⟨α, A⟩ = A := rfl @[simp] theorem eta : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x y : pSet) : Prop := pSet.rec (λ α z m ⟨β, B⟩, (∀ a, ∃ b, m a (B b)) ∧ (∀ b, ∃ a, m a (B b))) x y theorem equiv_iff : Π {x y : pSet}, equiv x y ↔ (∀ i, ∃ j, equiv (x.func i) (y.func j)) ∧ (∀ j, ∃ i, equiv (x.func i) (y.func j)) | ⟨α, A⟩ ⟨β, B⟩ := iff.rfl theorem equiv.exists_left {x y : pSet} (h : equiv x y) : ∀ i, ∃ j, equiv (x.func i) (y.func j) := (equiv_iff.1 h).1 theorem equiv.exists_right {x y : pSet} (h : equiv x y) : ∀ j, ∃ i, equiv (x.func i) (y.func j) := (equiv_iff.1 h).2 @[refl] protected theorem equiv.refl (x) : equiv x x := pSet.rec_on x $ λ α A IH, ⟨λ a, ⟨a, IH a⟩, λ a, ⟨a, IH a⟩⟩ protected theorem equiv.rfl : ∀ {x}, equiv x x := equiv.refl protected theorem equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λ α A IH y, pSet.cases_on y $ λ β B ⟨γ, Γ⟩ ⟨αβ, βα⟩ ⟨γβ, βγ⟩, ⟨λ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, IH a ab bc⟩, λ c, let ⟨b, cb⟩ := γβ c, ⟨a, ba⟩ := βα b in ⟨a, IH a ba cb⟩⟩ @[symm] protected theorem equiv.symm {x y} : equiv x y → equiv y x := (equiv.refl y).euc @[trans] protected theorem equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := h1.euc h2.symm protected theorem equiv_of_is_empty (x y : pSet) [is_empty x.type] [is_empty y.type] : equiv x y := equiv_iff.2 $ by simp instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λ x y, equiv.symm, λ x y z, equiv.trans⟩ /-- A pre-set is a subset of another pre-set if every element of the first family is extensionally equivalent to some element of the second family.-/ protected def subset (x y : pSet) : Prop := ∀ a, ∃ b, equiv (x.func a) (y.func b) instance : has_subset pSet := ⟨pSet.subset⟩ instance : is_refl pSet (⊆) := ⟨λ x a, ⟨a, equiv.refl _⟩⟩ instance : is_trans pSet (⊆) := ⟨λ x y z hxy hyz a, begin cases hxy a with b hb, cases hyz b with c hc, exact ⟨c, hb.trans hc⟩ end⟩ theorem equiv.ext : Π (x y : pSet), equiv x y ↔ (x ⊆ y ∧ y ⊆ x) | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ ⟨αβ, βα⟩, ⟨αβ, λ b, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩, λ ⟨αβ, βα⟩, ⟨αβ, λ b, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩⟩ theorem subset.congr_left : Π {x y z : pSet}, equiv x y → (x ⊆ z ↔ y ⊆ z) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λ αγ b, let ⟨a, ba⟩ := βα b, ⟨c, ac⟩ := αγ a in ⟨c, (equiv.symm ba).trans ac⟩, λ βγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ theorem subset.congr_right : Π {x y z : pSet}, equiv x y → (z ⊆ x ↔ z ⊆ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λ γα c, let ⟨a, ca⟩ := γα c, ⟨b, ab⟩ := αβ a in ⟨b, ca.trans ab⟩, λ γβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, cb.trans (equiv.symm ab)⟩⟩ /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ protected def mem (x y : pSet.{u}) : Prop := ∃ b, equiv x (y.func b) instance : has_mem pSet pSet := ⟨pSet.mem⟩ theorem mem.mk {α : Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := ⟨a, equiv.refl (A a)⟩ theorem func_mem (x : pSet) (i : x.type) : x.func i ∈ x := by { cases x, apply mem.mk } theorem mem.ext : Π {x y : pSet.{u}}, (∀ w : pSet.{u}, w ∈ x ↔ w ∈ y) → equiv x y | ⟨α, A⟩ ⟨β, B⟩ h := ⟨λ a, (h (A a)).1 (mem.mk A a), λ b, let ⟨a, ha⟩ := (h (B b)).2 (mem.mk B b) in ⟨a, ha.symm⟩⟩ theorem mem.congr_right : Π {x y : pSet.{u}}, equiv x y → (∀ {w : pSet.{u}}, w ∈ x ↔ w ∈ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩ w := ⟨λ ⟨a, ha⟩, let ⟨b, hb⟩ := αβ a in ⟨b, ha.trans hb⟩, λ ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, hb.euc ha⟩⟩ theorem equiv_iff_mem {x y : pSet.{u}} : equiv x y ↔ (∀ {w : pSet.{u}}, w ∈ x ↔ w ∈ y) := ⟨mem.congr_right, match x, y with | ⟨α, A⟩, ⟨β, B⟩, h := ⟨λ a, h.1 (mem.mk A a), λ b, let ⟨a, h⟩ := h.2 (mem.mk B b) in ⟨a, h.symm⟩⟩ end⟩ theorem mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀ {w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ ⟨a, ha⟩, ⟨a, h.symm.trans ha⟩, λ ⟨a, ha⟩, ⟨a, h.trans ha⟩⟩ private theorem mem_wf_aux : Π {x y : pSet.{u}}, equiv x y → acc (∈) y | ⟨α, A⟩ ⟨β, B⟩ H := ⟨_, begin rintros ⟨γ, C⟩ ⟨b, hc⟩, cases H.exists_right b with a ha, have H := ha.trans hc.symm, rw mk_func at H, exact mem_wf_aux H end⟩ theorem mem_wf : @well_founded pSet (∈) := ⟨λ x, mem_wf_aux $ equiv.refl x⟩ instance : has_well_founded pSet := ⟨_, mem_wf⟩ instance : is_asymm pSet (∈) := mem_wf.is_asymm theorem mem_asymm {x y : pSet} : x ∈ y → y ∉ x := asymm theorem mem_irrefl (x : pSet) : x ∉ x := irrefl x /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} @[simp] theorem mem_to_set (a u : pSet.{u}) : a ∈ u.to_set ↔ a ∈ u := iff.rfl /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x y : pSet} : equiv x y ↔ to_set x = to_set y := equiv_iff_mem.trans set.ext_iff.symm instance : has_coe pSet (set pSet) := ⟨to_set⟩ /-- The empty pre-set -/ protected def empty : pSet := ⟨_, pempty.elim⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ instance : inhabited pSet := ⟨∅⟩ instance : is_empty (type (∅)) := pempty.is_empty @[simp] theorem mem_empty (x : pSet.{u}) : x ∉ (∅ : pSet.{u}) := is_empty.exists_iff.1 @[simp] theorem to_set_empty : to_set ∅ = ∅ := by simp [to_set] @[simp] theorem empty_subset (x : pSet.{u}) : (∅ : pSet) ⊆ x := λ x, x.elim protected theorem equiv_empty (x : pSet) [is_empty x.type] : equiv x ∅ := pSet.equiv_of_is_empty x _ /-- Insert an element into a pre-set -/ protected def insert (x y : pSet) : pSet := ⟨option y.type, λ o, option.rec x y.func o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ instance : has_singleton pSet pSet := ⟨λ s, insert s ∅⟩ instance : is_lawful_singleton pSet pSet := ⟨λ _, rfl⟩ instance (x y : pSet) : inhabited (insert x y).type := option.inhabited _ /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := insert (of_nat n) (of_nat n) /-- The von Neumann ordinal ω -/ def omega : pSet := ⟨ulift ℕ, λ n, of_nat n.down⟩ /-- The pre-set separation operation `{x ∈ a | p x}` -/ protected def sep (p : pSet → Prop) (x : pSet) : pSet := ⟨{a // p (x.func a)}, λ y, x.func y.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ /-- The pre-set powerset operator -/ def powerset (x : pSet) : pSet := ⟨set x.type, λ p, ⟨{a // p a}, λ y, x.func y.1⟩⟩ @[simp] theorem mem_powerset : Π {x y : pSet}, y ∈ powerset x ↔ y ⊆ x | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ ⟨p, e⟩, (subset.congr_left e).2 $ λ ⟨a, pa⟩, ⟨a, equiv.refl (A a)⟩, λ βα, ⟨{a | ∃ b, equiv (B b) (A a)}, λ b, let ⟨a, ba⟩ := βα b in ⟨⟨a, b, ba⟩, ba⟩, λ ⟨a, b, ba⟩, ⟨b, ba⟩⟩⟩ /-- The pre-set union operator -/ def sUnion (a : pSet) : pSet := ⟨Σ x, (a.func x).type, λ ⟨x, y⟩, (a.func x).func y⟩ prefix `⋃₀ `:110 := pSet.sUnion @[simp] theorem mem_sUnion : Π {x y : pSet.{u}}, y ∈ ⋃₀ x ↔ ∃ z ∈ x, y ∈ z | ⟨α, A⟩ y := ⟨λ ⟨⟨a, c⟩, (e : equiv y ((A a).func c))⟩, have func (A a) c ∈ mk (A a).type (A a).func, from mem.mk (A a).func c, ⟨_, mem.mk _ _, (mem.congr_left e).2 (by rwa eta at this)⟩, λ ⟨⟨β, B⟩, ⟨a, (e : equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by { rw ←(eta (A a)) at e, exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, yb.trans bc⟩ }⟩ @[simp] theorem to_set_sUnion (x : pSet.{u}) : (⋃₀ x).to_set = ⋃₀ (to_set '' x.to_set) := by { ext, simp } /-- The image of a function from pre-sets to pre-sets. -/ def image (f : pSet.{u} → pSet.{u}) (x : pSet.{u}) : pSet := ⟨x.type, f ∘ x.func⟩ theorem mem_image {f : pSet.{u} → pSet.{u}} (H : ∀ {x y}, equiv x y → equiv (f x) (f y)) : Π {x y : pSet.{u}}, y ∈ image f x ↔ ∃ z ∈ x, equiv y (f z) | ⟨α, A⟩ y := ⟨λ ⟨a, ya⟩, ⟨A a, mem.mk A a, ya⟩, λ ⟨z, ⟨a, za⟩, yz⟩, ⟨a, yz.trans (H za)⟩⟩ /-- Universe lift operation -/ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ ⟨x⟩, lift (A x)⟩ /-- Embedding of one universe in another -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ theorem lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λ x, ⟨⟨x⟩, equiv.rfl⟩ /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of `n`-ary functions. -/ def arity.equiv : Π {n}, arity pSet.{u} n → arity pSet.{u} n → Prop | 0 a b := equiv a b | (n+1) a b := ∀ x y, equiv x y → arity.equiv (a x) (b y) lemma arity.equiv_const {a : pSet.{u}} : ∀ n, arity.equiv (arity.const a n) (arity.const a n) | 0 := equiv.rfl | (n+1) := λ x y h, arity.equiv_const _ /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n) := {x : arity pSet.{u} n // arity.equiv x x} instance resp.inhabited {n} : inhabited (resp n) := ⟨⟨arity.const default _, arity.equiv_const _⟩⟩ /-- The `n`-ary image of a `(n + 1)`-ary function respecting equivalence as a function respecting equivalence. -/ def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ /-- Function equivalence for functions respecting equivalence. See `pSet.arity.equiv`. -/ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 protected theorem resp.equiv.refl {n} (a : resp n) : resp.equiv a a := a.2 protected theorem resp.equiv.euc : Π {n} {a b c : resp n}, resp.equiv a b → resp.equiv c b → resp.equiv a c | 0 a b c hab hcb := equiv.euc hab hcb | (n+1) a b c hab hcb := λ x y h, @resp.equiv.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) protected theorem resp.equiv.symm {n} {a b : resp n} : resp.equiv a b → resp.equiv b a := (resp.equiv.refl b).euc protected theorem resp.equiv.trans {n} {x y z : resp n} (h1 : resp.equiv x y) (h2 : resp.equiv y z) : resp.equiv x z := h1.euc h2.symm instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.equiv.refl, λ x y, resp.equiv.symm, λ x y z, resp.equiv.trans⟩ end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp /-- Helper function for `pSet.eval`. -/ def eval_aux : Π {n}, {f : resp n → arity Set.{u} n // ∀ (a b : resp n), resp.equiv a b → f a = f b} | 0 := ⟨λ a, ⟦a.1⟧, λ a b h, quotient.sound h⟩ | (n+1) := let F : resp (n + 1) → arity Set (n + 1) := λ a, @quotient.lift _ _ pSet.setoid (λ x, eval_aux.1 (a.f x)) (λ b c h, eval_aux.2 _ _ (a.2 _ _ h)) in ⟨F, λ b c h, funext $ @quotient.ind _ _ (λ q, F b q = F c q) $ λ z, eval_aux.2 (resp.f b z) (resp.f c z) (h _ _ (pSet.equiv.refl z))⟩ /-- An equivalence-respecting function yields an n-ary ZFC set function. -/ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 theorem eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (resp.f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ class inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval n f) attribute [instance] definable.mk /-- The evaluation of a function respecting equivalence is definable, by that same function. -/ def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ /-- Turns a definable function into a function that respects equivalence. -/ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f theorem definable.eq {n} : Π (s : arity Set.{u} n) [H : definable n s], (@definable.resp n s H).eval _ = s | ._ ⟨f⟩ := rfl end pSet namespace classical open pSet /-- All functions are classically definable. -/ noncomputable def all_definable : Π {n} (F : arity Set.{u} n), definable n F | 0 F := let p := @quotient.exists_rep pSet _ F in definable.eq_mk ⟨some p, equiv.rfl⟩ (some_spec p) | (n+1) (F : arity Set.{u} (n + 1)) := begin have I := λ x, (all_definable (F x)), refine definable.eq_mk ⟨λ x : pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp [arity.equiv], introsI x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, refine funext (λ q, quotient.induction_on q $ λ x, _), simp_rw [resp.eval_val, resp.f, subtype.val_eq_coe, subtype.coe_eta], exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧), end end classical namespace Set open pSet /-- Turns a pre-set into a ZFC set. -/ def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : @eq Set ⟦x⟧ (mk x) := rfl @[simp] theorem mk_out : ∀ x : Set, mk x.out = x := quotient.out_eq theorem eq {x y : pSet} : mk x = mk y ↔ equiv x y := quotient.eq theorem sound {x y : pSet} (h : pSet.equiv x y) : mk x = mk y := quotient.sound h theorem exact {x y : pSet} : mk x = mk y → pSet.equiv x y := quotient.exact @[simp] lemma eval_mk {n f x} : (@resp.eval (n+1) f : Set → arity Set n) (mk x) = resp.eval n (resp.f f x) := rfl /-- The membership relation for ZFC sets is inherited from the membership relation for pre-sets. -/ protected def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λ x y x' y' hx hy, propext ((mem.congr_left hx).trans (mem.congr_right hy))) instance : has_mem Set Set := ⟨Set.mem⟩ @[simp] theorem mk_mem_iff {x y : pSet} : mk x ∈ mk y ↔ x ∈ y := iff.rfl /-- Convert a ZFC set into a `set` of ZFC sets -/ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} @[simp] theorem mem_to_set (a u : Set.{u}) : a ∈ u.to_set ↔ a ∈ u := iff.rfl instance small_to_set (x : Set.{u}) : small.{u} x.to_set := quotient.induction_on x $ λ a, begin let f : a.type → (mk a).to_set := λ i, ⟨mk $ a.func i, func_mem a i⟩, suffices : function.surjective f, { exact small_of_surjective this }, rintro ⟨y, hb⟩, induction y using quotient.induction_on, cases hb with i h, exact ⟨i, subtype.coe_injective (quotient.sound h.symm)⟩ end /-- `x ⊆ y` as ZFC sets means that all members of `x` are members of `y`. -/ protected def subset (x y : Set.{u}) := ∀ ⦃z⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ lemma subset_def {x y : Set.{u}} : x ⊆ y ↔ ∀ ⦃z⦄, z ∈ x → z ∈ y := iff.rfl instance : is_refl Set (⊆) := ⟨λ x a, id⟩ instance : is_trans Set (⊆) := ⟨λ x y z hxy hyz a ha, hyz (hxy ha)⟩ @[simp] theorem subset_iff : Π {x y : pSet}, mk x ⊆ mk y ↔ x ⊆ y | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ h a, @h ⟦A a⟧ (mem.mk A a), λ h z, quotient.induction_on z (λ z ⟨a, za⟩, let ⟨b, ab⟩ := h a in ⟨b, za.trans ab⟩)⟩ @[simp] theorem to_set_subset_iff {x y : Set} : x.to_set ⊆ y.to_set ↔ x ⊆ y := by simp [subset_def, set.subset_def] @[ext] theorem ext {x y : Set.{u}} : (∀ z : Set.{u}, z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y (λ u v h, quotient.sound (mem.ext (λ w, h ⟦w⟧))) theorem ext_iff {x y : Set.{u}} : x = y ↔ (∀ z : Set.{u}, z ∈ x ↔ z ∈ y) := ⟨λ h, by simp [h], ext⟩ theorem to_set_injective : function.injective to_set := λ x y h, ext $ set.ext_iff.1 h @[simp] theorem to_set_inj {x y : Set} : x.to_set = y.to_set ↔ x = y := to_set_injective.eq_iff instance : is_antisymm Set (⊆) := ⟨λ a b hab hba, ext $ λ c, ⟨@hab c, @hba c⟩⟩ /-- The empty ZFC set -/ protected def empty : Set := mk ∅ instance : has_emptyc Set := ⟨Set.empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] theorem mem_empty (x) : x ∉ (∅ : Set.{u}) := quotient.induction_on x pSet.mem_empty @[simp] theorem to_set_empty : to_set ∅ = ∅ := by simp [to_set] @[simp] theorem empty_subset (x : Set.{u}) : (∅ : Set) ⊆ x := quotient.induction_on x $ λ y, subset_iff.2 $ pSet.empty_subset y theorem eq_empty (x : Set.{u}) : x = ∅ ↔ ∀ y : Set.{u}, y ∉ x := ⟨λ h y, (h.symm ▸ mem_empty y), λ h, ext (λ y, ⟨λ yx, absurd yx (h y), λ y0, absurd y0 (mem_empty _)⟩)⟩ /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := resp.eval 2 ⟨pSet.insert, λ u v uv ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ o, match o with | some a := let ⟨b, hb⟩ := αβ a in ⟨some b, hb⟩ | none := ⟨none, uv⟩ end, λ o, match o with | some b := let ⟨a, ha⟩ := βα b in ⟨some a, ha⟩ | none := ⟨none, uv⟩ end⟩⟩ instance : has_insert Set Set := ⟨Set.insert⟩ instance : has_singleton Set Set := ⟨λ x, insert x ∅⟩ instance : is_lawful_singleton Set Set := ⟨λ x, rfl⟩ @[simp] theorem mem_insert_iff {x y z : Set.{u}} : x ∈ insert y z ↔ x = y ∨ x ∈ z := quotient.induction_on₃ x y z (λ x y ⟨α, A⟩, show x ∈ pSet.mk (option α) (λ o, option.rec y A o) ↔ mk x = mk y ∨ x ∈ pSet.mk α A, from ⟨λ m, match m with | ⟨some a, ha⟩ := or.inr ⟨a, ha⟩ | ⟨none, h⟩ := or.inl (quotient.sound h) end, λ m, match m with | or.inr ⟨a, ha⟩ := ⟨some a, ha⟩ | or.inl h := ⟨none, quotient.exact h⟩ end⟩) theorem mem_insert (x y : Set) : x ∈ insert x y := mem_insert_iff.2 $ or.inl rfl theorem mem_insert_of_mem {y z : Set} (x) (h : z ∈ y): z ∈ insert x y := mem_insert_iff.2 $ or.inr h @[simp] theorem to_set_insert (x y : Set) : (insert x y).to_set = insert x y.to_set := by { ext, simp } @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ y ↔ x = y := iff.trans mem_insert_iff ⟨λ o, or.rec (λ h, h) (λ n, absurd n (mem_empty _)) o, or.inl⟩ @[simp] theorem to_set_singleton (x : Set) : ({x} : Set).to_set = {x} := by { ext, simp } @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ ({y, z} : Set) ↔ x = y ∨ x = z := iff.trans mem_insert_iff $ or_congr iff.rfl mem_singleton /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk omega @[simp] theorem omega_zero : ∅ ∈ omega := ⟨⟨0⟩, equiv.rfl⟩ @[simp] theorem omega_succ {n} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λ x ⟨⟨n⟩, h⟩, ⟨⟨n+1⟩, Set.exact $ show insert (mk x) (mk x) = insert (mk $ of_nat n) (mk $ of_nat n), { rw Set.sound h, refl } ⟩) /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λ y, p (mk y)), λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa [mk_func, ←Set.sound hb]⟩, hb⟩, λ ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa [mk_func, Set.sound ha]⟩, ha⟩⟩⟩ instance : has_sep Set Set := ⟨Set.sep⟩ @[simp] theorem mem_sep {p : Set.{u} → Prop} {x y : Set.{u}} : y ∈ {y ∈ x | p y} ↔ y ∈ x ∧ p y := quotient.induction_on₂ x y (λ ⟨α, A⟩ y, ⟨λ ⟨⟨a, pa⟩, h⟩, ⟨⟨a, h⟩, by rwa (@quotient.sound pSet _ _ _ h)⟩, λ ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by { rw mk_func at h, rwa [mk_func, ←Set.sound h] }⟩, h⟩⟩) @[simp] theorem to_set_sep (a : Set) (p : Set → Prop) : {x ∈ a | p x}.to_set = {x ∈ a.to_set | p x} := by { ext, simp } /-- The powerset operation, the collection of subsets of a ZFC set -/ def powerset : Set → Set := resp.eval 1 ⟨powerset, λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ p, ⟨{b | ∃ a, p a ∧ equiv (A a) (B b)}, λ ⟨a, pa⟩, let ⟨b, ab⟩ := αβ a in ⟨⟨b, a, pa, ab⟩, ab⟩, λ ⟨b, a, pa, ab⟩, ⟨⟨a, pa⟩, ab⟩⟩, λ q, ⟨{a | ∃ b, q b ∧ equiv (A a) (B b)}, λ ⟨a, b, qb, ab⟩, ⟨⟨b, qb⟩, ab⟩, λ ⟨b, qb⟩, let ⟨a, ab⟩ := βα b in ⟨⟨a, b, qb, ab⟩, ab⟩⟩⟩⟩ @[simp] theorem mem_powerset {x y : Set.{u}} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y ( λ ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet.{u}) ∈ (pSet.powerset.{u} ⟨α, A⟩) ↔ _, by simp [mem_powerset, subset_iff]) theorem sUnion_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀ a, ∃ b, equiv (A a) (B b)) : ∀ a, ∃ b, (equiv ((sUnion ⟨α, A⟩).func a) ((sUnion ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin induction ea : A a with γ Γ, induction eb : B b with δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have pSet.equiv ((A a).func c) ((B b).func (eq.rec d (eq.symm eb))), from match A a, B b, ea, eb, c, d, hd with ._, ._, rfl, rfl, x, y, hd := hd end, ⟨⟨b, by { rw mk_func, exact eq.rec d (eq.symm eb) }⟩, this⟩ end /-- The union operator, the collection of elements of elements of a ZFC set -/ def sUnion : Set → Set := resp.eval 1 ⟨pSet.sUnion, λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨sUnion_lem A B αβ, λ a, exists.elim (sUnion_lem B A (λ b, exists.elim (βα b) (λ c hc, ⟨c, pSet.equiv.symm hc⟩)) a) (λ b hb, ⟨b, pSet.equiv.symm hb⟩)⟩⟩ prefix `⋃₀ `:110 := Set.sUnion @[simp] theorem mem_sUnion {x y : Set.{u}} : y ∈ ⋃₀ x ↔ ∃ z ∈ x, y ∈ z := quotient.induction_on₂ x y (λ x y, iff.trans mem_sUnion ⟨λ ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ ⟨z, h⟩, quotient.induction_on z (λ z h, ⟨z, h⟩) h⟩) theorem mem_sUnion_of_mem {x y z : Set} (hy : y ∈ z) (hz : z ∈ x) : y ∈ ⋃₀ x := mem_sUnion.2 ⟨z, hz, hy⟩ @[simp] theorem sUnion_singleton {x : Set.{u}} : ⋃₀ ({x} : Set) = x := ext $ λ y, by simp_rw [mem_sUnion, exists_prop, mem_singleton, exists_eq_left] theorem singleton_injective : function.injective (@singleton Set Set _) := λ x y H, let this := congr_arg sUnion H in by rwa [sUnion_singleton, sUnion_singleton] at this @[simp] theorem singleton_inj {x y : Set} : ({x} : Set) = {y} ↔ x = y := singleton_injective.eq_iff @[simp] theorem to_set_sUnion (x : Set.{u}) : (⋃₀ x).to_set = ⋃₀ (to_set '' x.to_set) := by { ext, simp } /-- The binary union operation -/ protected def union (x y : Set.{u}) : Set.{u} := ⋃₀ {x, y} /-- The binary intersection operation -/ protected def inter (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∈ y} /-- The set difference operation -/ protected def diff (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∉ y} instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem to_set_union (x y : Set.{u}) : (x ∪ y).to_set = x.to_set ∪ y.to_set := by { unfold has_union.union, rw Set.union, simp } @[simp] theorem to_set_inter (x y : Set.{u}) : (x ∩ y).to_set = x.to_set ∩ y.to_set := by { unfold has_inter.inter, rw Set.inter, ext, simp } @[simp] theorem to_set_sdiff (x y : Set.{u}) : (x \ y).to_set = x.to_set \ y.to_set := by { change {z ∈ x | z ∉ y}.to_set = _, ext, simp } @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := by { rw ←mem_to_set, simp } @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := @@mem_sep (λ z : Set.{u}, z ∈ y) @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ z ∈ x ∧ z ∉ y := @@mem_sep (λ z : Set.{u}, z ∉ y) /-- Induction on the `∈` relation. -/ @[elab_as_eliminator] theorem induction_on {p : Set → Prop} (x) (h : ∀ x, (∀ y ∈ x, p y) → p x) : p x := quotient.induction_on x $ λ u, pSet.rec_on u $ λ α A IH, h _ $ λ y, show @has_mem.mem _ _ Set.has_mem y ⟦⟨α, A⟩⟧ → p y, from quotient.induction_on y (λ v ⟨a, ha⟩, by { rw (@quotient.sound pSet _ _ _ ha), exact IH a }) theorem mem_wf : @well_founded Set (∈) := ⟨λ x, induction_on x acc.intro⟩ instance : has_well_founded Set := ⟨_, mem_wf⟩ instance : is_asymm Set (∈) := mem_wf.is_asymm theorem mem_asymm {x y : Set} : x ∈ y → y ∉ x := asymm theorem mem_irrefl (x : Set) : x ∉ x := irrefl x theorem regularity (x : Set.{u}) (h : x ≠ ∅) : ∃ y ∈ x, x ∩ y = ∅ := classical.by_contradiction $ λ ne, h $ (eq_empty x).2 $ λ y, induction_on y $ λ z (IH : ∀ w : Set.{u}, w ∈ z → w ∉ x), show z ∉ x, from λ zx, ne ⟨z, zx, (eq_empty _).2 (λ w wxz, let ⟨wx, wz⟩ := mem_inter.1 wxz in IH w wz wx)⟩ /-- The image of a (definable) ZFC set function -/ def image (f : Set → Set) [H : definable 1 f] : Set → Set := let r := @definable.resp 1 f _ in resp.eval 1 ⟨image r.1, λ x y e, mem.ext $ λ z, iff.trans (mem_image r.2) $ iff.trans (by exact ⟨λ ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).1 h1, h2⟩, λ ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).2 h1, h2⟩⟩) $ iff.symm (mem_image r.2)⟩ theorem image.mk : Π (f : Set.{u} → Set.{u}) [H : definable 1 f] (x) {y} (h : y ∈ x), f y ∈ @image f H x | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ ⟨α, A⟩ y ⟨a, ya⟩, ⟨a, F.2 _ _ ya⟩ @[simp] theorem mem_image : Π {f : Set.{u} → Set.{u}} [H : definable 1 f] {x y : Set.{u}}, y ∈ @image f H x ↔ ∃ z ∈ x, f z = y | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ ⟨α, A⟩ y, ⟨λ ⟨a, ya⟩, ⟨⟦A a⟧, mem.mk A a, eq.symm $ quotient.sound ya⟩, λ ⟨z, hz, e⟩, e ▸ image.mk _ _ hz⟩ @[simp] theorem to_set_image (f : Set → Set) [H : definable 1 f] (x : Set) : (image f x).to_set = f '' x.to_set := by { ext, simp } /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} @[simp] theorem to_set_pair (x y : Set.{u}) : (pair x y).to_set = {{x}, {x, y}} := by simp [pair] /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃ a ∈ x, ∃ b ∈ y, z = pair a b ∧ p a b} @[simp] theorem mem_pair_sep {p} {x y z : Set.{u}} : z ∈ pair_sep p x y ↔ ∃ a ∈ x, ∃ b ∈ y, z = pair a b ∧ p a b := begin refine mem_sep.trans ⟨and.right, λ e, ⟨_, e⟩⟩, rcases e with ⟨a, ax, b, bY, rfl, pab⟩, simp only [mem_powerset, subset_def, mem_union, pair, mem_pair], rintros u (rfl|rfl) v; simp only [mem_singleton, mem_pair], { rintro rfl, exact or.inl ax }, { rintro (rfl|rfl); [left, right]; assumption } end theorem pair_injective : function.injective2 pair := λ x x' y y' H, begin have ae := ext_iff.1 H, simp only [pair, mem_pair] at ae, obtain rfl : x = x', { cases (ae {x}).1 (by simp) with h h, { exact singleton_injective h }, { have m : x' ∈ ({x} : Set), { simp [h] }, rw mem_singleton.mp m } }, have he : x = y → y = y', { rintro rfl, cases (ae {x, y'}).2 (by simp only [eq_self_iff_true, or_true]) with xy'x xy'xx, { rw [eq_comm, ←mem_singleton, ←xy'x, mem_pair], exact or.inr rfl }, { simpa [eq_comm] using (ext_iff.1 xy'xx y').1 (by simp) } }, obtain xyx | xyy' := (ae {x, y}).1 (by simp), { obtain rfl := mem_singleton.mp ((ext_iff.1 xyx y).1 $ by simp), simp [he rfl] }, { obtain rfl | yy' := mem_pair.mp ((ext_iff.1 xyy' y).1 $ by simp), { simp [he rfl] }, { simp [yy'] } } end @[simp] theorem pair_inj {x y x' y' : Set} : pair x y = pair x' y' ↔ x = x' ∧ y = y' := pair_injective.eq_iff /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λ a b, true) @[simp] theorem mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃ a ∈ x, ∃ b ∈ y, z = pair a b := by simp [prod] @[simp] theorem pair_mem_prod {x y a b : Set.{u}} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := ⟨λ h, let ⟨a', a'x, b', b'y, e⟩ := mem_prod.1 h in match a', b', pair_injective e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ ⟨ax, bY⟩, mem_prod.2 ⟨a, ax, b, bY, rfl⟩⟩ /-- `is_func x y f` is the assertion that `f` is a subset of `x × y` which relates to each element of `x` a unique element of `y`, so that we can consider `f`as a ZFC function `x → y`. -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀ z : Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] theorem mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp [funs, is_func] -- TODO(Mario): Prove this computably noncomputable instance map_definable_aux (f : Set → Set) [H : definable 1 f] : definable 1 (λ y, pair y (f y)) := @classical.all_definable 1 _ /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ noncomputable def map (f : Set → Set) [H : definable 1 f] : Set → Set := image (λ y, pair y (f y)) @[simp] theorem mem_map {f : Set → Set} [H : definable 1 f] {x y : Set} : y ∈ map f x ↔ ∃ z ∈ x, pair z (f z) = y := mem_image theorem map_unique {f : Set.{u} → Set.{u}} [H : definable 1 f] {x z : Set.{u}} (zx : z ∈ x) : ∃! w, pair z w ∈ map f x := ⟨f z, image.mk _ _ zx, λ y yx, let ⟨w, wx, we⟩ := mem_image.1 yx, ⟨wz, fy⟩ := pair_injective we in by rw[←fy, wz]⟩ @[simp] theorem map_is_func {f : Set → Set} [H : definable 1 f] {x y : Set} : is_func x y (map f x) ↔ ∀ z ∈ x, f z ∈ y := ⟨λ ⟨ss, h⟩ z zx, let ⟨t, t1, t2⟩ := h z zx in (t2 (f z) (image.mk _ _ zx)).symm ▸ (pair_mem_prod.1 (ss t1)).right, λ h, ⟨λ y yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in ze ▸ pair_mem_prod.2 ⟨zx, h z zx⟩, λ z, map_unique⟩⟩ end Set /-- The collection of all classes. We define `Class` as `set Set`, as this allows us to get many instances automatically. However, in practice, we treat it as (the definitionally equal) `Set → Prop`. This means, the preferred way to state that `x : Set` belongs to `A : Class` is to write `A x`. -/ @[derive [has_subset, has_sep Set, has_emptyc, inhabited, has_insert Set, has_union, has_inter, has_compl, has_sdiff]] def Class := set Set namespace Class /-- Coerce a ZFC set into a class -/ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a ZFC set satisfying `B` -/ def to_Set (B : Class.{u}) (A : Class.{u}) : Prop := ∃ x, ↑x = A ∧ B x /-- `A ∈ B` if `A` is a ZFC set which satisfies `B` -/ protected def mem (A B : Class.{u}) : Prop := to_Set.{u} B A instance : has_mem Class Class := ⟨Class.mem⟩ theorem mem_univ {A : Class.{u}} : A ∈ univ.{u} ↔ ∃ x : Set.{u}, ↑x = A := exists_congr $ λ x, and_true _ theorem mem_wf : @well_founded Class.{u} (∈) := ⟨begin have H : ∀ x : Set.{u}, @acc Class.{u} (∈) ↑x, { refine λ a, Set.induction_on a (λ x IH, ⟨x, _⟩), rintros A ⟨z, rfl, hz⟩, exact IH z hz }, { refine λ A, ⟨A, _⟩, rintros B ⟨x, rfl, hx⟩, exact H x } end⟩ instance : has_well_founded Class := ⟨_, mem_wf⟩ instance : is_asymm Class (∈) := mem_wf.is_asymm theorem mem_asymm {x y : Class} : x ∈ y → y ∉ x := asymm theorem mem_irrefl (x : Class) : x ∉ x := irrefl x /-- There is no universal set. -/ theorem univ_not_mem_univ : univ ∉ univ := mem_irrefl _ /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} /-- The power class of a class is the class of all subclasses that are ZFC sets -/ def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) /-- The union of a class is the class of all members of ZFC sets in the class -/ def sUnion (x : Class) : Class := ⋃₀ (Class_to_Cong x) prefix `⋃₀ `:110 := Class.sUnion theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λ z, by { change (x : Class.{u}) z ↔ (y : Class.{u}) z, rw h } @[simp] theorem to_Set_of_Set (A : Class.{u}) (x : Set.{u}) : to_Set A x ↔ A x := ⟨λ ⟨y, yx, py⟩, by rwa of_Set.inj yx at py, λ px, ⟨x, rfl, px⟩⟩ @[simp] theorem mem_hom_left (x : Set.{u}) (A : Class.{u}) : (x : Class.{u}) ∈ A ↔ A x := to_Set_of_Set _ _ @[simp] theorem mem_hom_right (x y : Set.{u}) : (y : Class.{u}) x ↔ x ∈ y := iff.rfl @[simp] theorem subset_hom (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.rfl @[simp] theorem sep_hom (p : Class.{u}) (x : Set.{u}) : (↑{y ∈ x | p y} : Class.{u}) = {y ∈ x | p y} := set.ext $ λ y, Set.mem_sep @[simp] theorem empty_hom : ↑(∅ : Set.{u}) = (∅ : Class.{u}) := set.ext $ λ y, (iff_false _).2 (Set.mem_empty y) @[simp] theorem insert_hom (x y : Set.{u}) : (@insert Set.{u} Class.{u} _ x y) = ↑(insert x y) := set.ext $ λ z, iff.symm Set.mem_insert_iff @[simp] theorem union_hom (x y : Set.{u}) : (x : Class.{u}) ∪ y = (x ∪ y : Set.{u}) := set.ext $ λ z, iff.symm Set.mem_union @[simp] theorem inter_hom (x y : Set.{u}) : (x : Class.{u}) ∩ y = (x ∩ y : Set.{u}) := set.ext $ λ z, iff.symm Set.mem_inter @[simp] theorem diff_hom (x y : Set.{u}) : (x : Class.{u}) \ y = (x \ y : Set.{u}) := set.ext $ λ z, iff.symm Set.mem_diff @[simp] theorem powerset_hom (x : Set.{u}) : powerset.{u} x = Set.powerset x := set.ext $ λ z, iff.symm Set.mem_powerset @[simp] theorem sUnion_hom (x : Set.{u}) : ⋃₀ (x : Class.{u}) = ⋃₀ x := set.ext $ λ z, by { refine iff.trans _ Set.mem_sUnion.symm, exact ⟨λ ⟨._, ⟨a, rfl, ax⟩, za⟩, ⟨a, ax, za⟩, λ ⟨a, ax, za⟩, ⟨_, ⟨a, rfl, ax⟩, za⟩⟩ } /-- The definite description operator, which is `{x}` if `{y | A y} = {x}` and `∅` otherwise. -/ def iota (A : Class) : Class := ⋃₀ {x | ∀ y, A y ↔ y = x} theorem iota_val (A : Class) (x : Set) (H : ∀ y, A y ↔ y = x) : iota A = ↑x := set.ext $ λ y, ⟨λ ⟨._, ⟨x', rfl, h⟩, yx'⟩, by rwa ←((H x').1 $ (h x').2 rfl), λ yx, ⟨_, ⟨x, rfl, H⟩, yx⟩⟩ /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `Class → Set` function. -/ theorem iota_ex (A) : iota.{u} A ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃ x, ∀ y, A y ↔ y = x) (λ ⟨x, h⟩, ⟨x, eq.symm $ iota_val A x h⟩) (λ hn, ⟨∅, set.ext (λ z, empty_hom.symm ▸ ⟨false.rec _, λ ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) /-- Function value -/ def fval (F A : Class.{u}) : Class.{u} := iota (λ y, to_Set (λ x, F (Set.pair x y)) A) infixl `′`:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] theorem map_fval {f : Set.{u} → Set.{u}} [H : pSet.definable 1 f] {x y : Set.{u}} (h : y ∈ x) : (Set.map f x ′ y : Class.{u}) = f y := Class.iota_val _ _ (λ z, by { rw [Class.to_Set_of_Set, Class.mem_hom_right, mem_map], exact ⟨λ ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_injective pr in by rw[←fw, wy], λ e, by { subst e, exact ⟨_, h, rfl⟩ }⟩ }) variables (x : Set.{u}) (h : ∅ ∉ x) /-- A choice function on the class of nonempty ZFC sets. -/ noncomputable def choice : Set := @map (λ y, classical.epsilon (λ z, z ∈ y)) (classical.all_definable _) x include h theorem choice_mem_aux (y : Set.{u}) (yx : y ∈ x) : classical.epsilon (λ z : Set.{u}, z ∈ y) ∈ y := @classical.epsilon_spec _ (λ z : Set.{u}, z ∈ y) $ classical.by_contradiction $ λ n, h $ by rwa ←((eq_empty y).2 $ λ z zx, n ⟨z, zx⟩) theorem choice_is_func : is_func x (⋃₀ x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λ y yx, mem_sUnion.2 ⟨y, yx, choice_mem_aux x h y yx⟩ theorem choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := begin delta choice, rw [map_fval yx, Class.mem_hom_left, Class.mem_hom_right], exact choice_mem_aux x h y yx end end Set
e91245bcdac1138ff78ed67864204346fcdaa753
ac89c256db07448984849346288e0eeffe8b20d0
/stage0/src/Init/Prelude.lean
383e5c6e07111d65af23eec2d739ee4e61d39d2a
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
75,418
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude universe u v w @[inline] def id {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a set_option checkBinderAnnotations false in @[reducible] def inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type set_option bootstrap.inductiveCheckResultingUniverse false in inductive PEmpty : Sort u where def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary deriving instance Inhabited for Bool /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.up_down {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.up_down {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decide_eq_true : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decide_eq_false : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem of_decide_eq_true [s : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁)) theorem of_decide_eq_false [s : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) s with | isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class LE (α : Type u) where le : α → α → Prop class LT (α : Type u) where lt : α → α → Prop @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a @[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α := ite (LT.lt b a) a b @[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α := ite (LE.le a b) a b class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) where pow : α → α → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α] : HPow α α α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eq_of_beq_eq_true this this ▸ rfl theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eq_of_beq_eq_true h) | false => isFalse (ne_of_beq_eq_false h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : LE Nat where le := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) := not_succ_le_zero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m theorem Nat.zero_le : (n : Nat) → LE.le 0 n | zero => rfl | succ n => rfl theorem Nat.succ_le_succ {n m : Nat} (h : LE.le n m) : LE.le (succ n) (succ m) := h theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) := succ_le_succ (zero_le n) theorem Nat.le_step : {n m : Nat} → LE.le n m → LE.le n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : LE.le n m := h have : LE.le n (succ m) := le_step this succ_le_succ this protected theorem Nat.le_trans : {n m k : Nat} → LE.le n m → LE.le m k → LE.le n k | zero, m, k, h₁, h₂ => zero_le _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LE.le n m := h₁ have h₂' : LE.le m k := h₂ show LE.le n k from Nat.le_trans h₁' h₂' protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.le_trans (le_step h₁) theorem Nat.le_succ : (n : Nat) → LE.le n (succ n) | zero => rfl | succ n => le_succ n theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.le_trans h (le_succ m) protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zero_le n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : LE.le n m := h match Nat.eq_or_lt_of_le this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succ_le_succ h) protected def Nat.le_refl : (n : Nat) → LE.le n n | zero => rfl | succ n => Nat.le_refl n protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zero_le n) | succ m => match Nat.lt_or_ge n m with | Or.inl h => Or.inl (le_succ_of_le h) | Or.inr h => match Nat.eq_or_lt_of_le h with | Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.le_antisymm : {n m : Nat} → LE.le n m → LE.le m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LE.le n m := h₁ have h₂' : LE.le m n := h₂ (Nat.le_antisymm h₁' h₂') ▸ rfl protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.lt_or_ge n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂ set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zero_le n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := pred_le_pred theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n := le_of_succ_le_succ @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : LT.lt val n theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eq_of_val_eq h) | isFalse h => isFalse (Fin.ne_of_val_ne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBits_eq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usize_size_eq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := { val := { val := n isLt := match USize.size, usize_size_eq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.lt_trans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.lt_trans h (by decide) | Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (val_eq_of_eq h') h theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eq_of_val_eq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eq_of_val_eq h) | isFalse h => isFalse (Char.ne_of_val_ne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none @[macroInline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α | nil, i, h => absurd h (Nat.not_lt_zero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have : LT.lt i.succ as.length.succ := length_cons .. ▸ h get as i (Nat.le_of_succ_le_succ this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → f β → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y x seqLeft x y := bind x fun a => bind y (fun _ => pure a) seqRight x y := bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → UInt64 export Hashable (hash) @[extern c inline "(size_t)#1"] constant UInt64.toUSize (u : UInt64) : USize @[extern c inline "(uint64_t)#1"] constant USize.toUInt64 (u : USize) : UInt64 @[extern "lean_uint64_mix_hash"] constant mixHash (u₁ u₂ : UInt64) : UInt64 @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → UInt64 → Name | num : Name → Nat → UInt64 → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → UInt64 | Name.anonymous => UInt64.ofNatCore 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom (SourceInfo.fromRef src) val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ private constant MethodsRefPointed : PointedType.{0} private def MethodsRef : Type := MethodsRefPointed.type structure Context where methods : MethodsRef mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception structure State where macroScope : MacroScope traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope structure Methods where expandMacro? : Syntax → MacroM (Option Syntax) getCurrNamespace : MacroM Name hasDecl : Name → MacroM Bool resolveNamespace? : Name → MacroM (Option Name) resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods @[implementedBy mkMethodsImp] constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val instance : Inhabited MethodsRef where default := mkMethods arbitrary unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) @[implementedBy getMethodsImp] constant getMethods : MacroM Methods /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Return `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace def resolveNamespace? (n : Name) : MacroM (Option Name) := do (← getMethods).resolveNamespace? n def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
89ea0175bede8a4f87ecc0da890ae7940dbf3bfe
b412a6d3e313459a241fcd7941e1ec91263762eb
/move_to_lib.hlean
ced7791ada34c998ce92f0c23f8dbcc5a069a774
[ "Apache-2.0" ]
permissive
avigad/Spectral
fb5b87f7d25746b2203fbe6fdc0c80f7035158c9
6e2d8807f467e9662bace347bdfcaed593cba147
refs/heads/master
1,607,307,431,821
1,503,349,559,000
1,503,349,559,000
47,590,774
0
0
null
null
null
null
UTF-8
Lean
false
false
41,271
hlean
-- definitions, theorems and attributes which should be moved to files in the HoTT library import homotopy.sphere2 homotopy.cofiber homotopy.wedge hit.prop_trunc hit.set_quotient eq2 types.pointed2 open eq nat int susp pointed sigma is_equiv equiv fiber algebra trunc pi group is_trunc function unit prod bool attribute pType.sigma_char sigma_pi_equiv_pi_sigma sigma.coind_unc [constructor] attribute ap1_gen [unfold 8 9 10] attribute ap010 [unfold 7] -- TODO: homotopy_of_eq and apd10 should be the same -- TODO: there is also apd10_eq_of_homotopy in both pi and eq(?) namespace eq definition apd10_prepostcompose_nondep {A B C D : Type} (h : C → D) {g g' : B → C} (p : g = g') (f : A → B) (a : A) : apd10 (ap (λg a, h (g (f a))) p) a = ap h (apd10 p (f a)) := begin induction p, reflexivity end definition apd10_prepostcompose {A B : Type} {C : B → Type} {D : A → Type} (f : A → B) (h : Πa, C (f a) → D a) {g g' : Πb, C b} (p : g = g') (a : A) : apd10 (ap (λg a, h a (g (f a))) p) a = ap (h a) (apd10 p (f a)) := begin induction p, reflexivity end definition eq.rec_to {A : Type} {a₀ : A} {P : Π⦃a₁⦄, a₀ = a₁ → Type} {a₁ : A} (p₀ : a₀ = a₁) (H : P p₀) ⦃a₂ : A⦄ (p : a₀ = a₂) : P p := begin induction p₀, induction p, exact H end definition eq.rec_to2 {A : Type} {P : Π⦃a₀ a₁⦄, a₀ = a₁ → Type} {a₀ a₀' a₁' : A} (p' : a₀' = a₁') (p₀ : a₀ = a₀') (H : P p') ⦃a₁ : A⦄ (p : a₀ = a₁) : P p := begin induction p₀, induction p', induction p, exact H end definition eq.rec_right_inv {A : Type} (f : A ≃ A) {P : Π⦃a₀ a₁⦄, f a₀ = a₁ → Type} (H : Πa, P (right_inv f a)) ⦃a₀ a₁ : A⦄ (p : f a₀ = a₁) : P p := begin revert a₀ p, refine equiv_rect f⁻¹ᵉ _ _, intro a₀ p, exact eq.rec_to (right_inv f a₀) (H a₀) p, end definition eq.rec_equiv {A B : Type} {a₀ : A} (f : A ≃ B) {P : Π{a₁}, f a₀ = f a₁ → Type} (H : P (idpath (f a₀))) ⦃a₁ : A⦄ (p : f a₀ = f a₁) : P p := begin assert qr : Σ(q : a₀ = a₁), ap f q = p, { exact ⟨eq_of_fn_eq_fn f p, ap_eq_of_fn_eq_fn' f p⟩ }, cases qr with q r, apply transport P r, induction q, exact H end definition eq.rec_equiv_symm {A B : Type} {a₁ : A} (f : A ≃ B) {P : Π{a₀}, f a₀ = f a₁ → Type} (H : P (idpath (f a₁))) ⦃a₀ : A⦄ (p : f a₀ = f a₁) : P p := begin assert qr : Σ(q : a₀ = a₁), ap f q = p, { exact ⟨eq_of_fn_eq_fn f p, ap_eq_of_fn_eq_fn' f p⟩ }, cases qr with q r, apply transport P r, induction q, exact H end definition eq.rec_equiv_to_same {A B : Type} {a₀ : A} (f : A ≃ B) {P : Π{a₁}, f a₀ = f a₁ → Type} ⦃a₁' : A⦄ (p' : f a₀ = f a₁') (H : P p') ⦃a₁ : A⦄ (p : f a₀ = f a₁) : P p := begin revert a₁' p' H a₁ p, refine eq.rec_equiv f _, exact eq.rec_equiv f end definition eq.rec_equiv_to {A A' B : Type} {a₀ : A} (f : A ≃ B) (g : A' ≃ B) {P : Π{a₁}, f a₀ = g a₁ → Type} ⦃a₁' : A'⦄ (p' : f a₀ = g a₁') (H : P p') ⦃a₁ : A'⦄ (p : f a₀ = g a₁) : P p := begin assert qr : Σ(q : g⁻¹ (f a₀) = a₁), (right_inv g (f a₀))⁻¹ ⬝ ap g q = p, { exact ⟨eq_of_fn_eq_fn g (right_inv g (f a₀) ⬝ p), whisker_left _ (ap_eq_of_fn_eq_fn' g _) ⬝ !inv_con_cancel_left⟩ }, assert q'r' : Σ(q' : g⁻¹ (f a₀) = a₁'), (right_inv g (f a₀))⁻¹ ⬝ ap g q' = p', { exact ⟨eq_of_fn_eq_fn g (right_inv g (f a₀) ⬝ p'), whisker_left _ (ap_eq_of_fn_eq_fn' g _) ⬝ !inv_con_cancel_left⟩ }, induction qr with q r, induction q'r' with q' r', induction q, induction q', induction r, induction r', exact H end definition eq.rec_grading {A A' B : Type} {a : A} (f : A ≃ B) (g : A' ≃ B) {P : Π{b}, f a = b → Type} {a' : A'} (p' : f a = g a') (H : P p') ⦃b : B⦄ (p : f a = b) : P p := begin revert b p, refine equiv_rect g _ _, exact eq.rec_equiv_to f g p' H end definition eq.rec_grading_unbased {A B B' C : Type} (f : A ≃ B) (g : B ≃ C) (h : B' ≃ C) {P : Π{b c}, g b = c → Type} {a' : A} {b' : B'} (p' : g (f a') = h b') (H : P p') ⦃b : B⦄ ⦃c : C⦄ (q : f a' = b) (p : g b = c) : P p := begin induction q, exact eq.rec_grading (f ⬝e g) h p' H p end -- definition homotopy_group_homomorphism_pinv (n : ℕ) {A B : Type*} (f : A ≃* B) : -- π→g[n+1] f⁻¹ᵉ* ~ (homotopy_group_isomorphism_of_pequiv n f)⁻¹ᵍ := -- begin -- -- refine ptrunc_functor_phomotopy 0 !apn_pinv ⬝hty _, -- -- intro x, esimp, -- end -- definition natural_square_tr_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 lemma homotopy_group_isomorphism_of_ptrunc_pequiv {A B : Type*} (n k : ℕ) (H : n+1 ≤[ℕ] k) (f : ptrunc k A ≃* ptrunc k B) : πg[n+1] A ≃g πg[n+1] B := (ghomotopy_group_ptrunc_of_le H A)⁻¹ᵍ ⬝g homotopy_group_isomorphism_of_pequiv n f ⬝g ghomotopy_group_ptrunc_of_le H B section hsquare variables {A₀₀ A₂₀ A₄₀ A₀₂ A₂₂ A₄₂ A₀₄ A₂₄ A₄₄ : Type} {f₁₀ : A₀₀ → A₂₀} {f₃₀ : A₂₀ → A₄₀} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {f₄₁ : A₄₀ → A₄₂} {f₁₂ : A₀₂ → A₂₂} {f₃₂ : A₂₂ → A₄₂} {f₀₃ : A₀₂ → A₀₄} {f₂₃ : A₂₂ → A₂₄} {f₄₃ : A₄₂ → A₄₄} {f₁₄ : A₀₄ → A₂₄} {f₃₄ : A₂₄ → A₄₄} definition trunc_functor_hsquare (n : ℕ₋₂) (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) : hsquare (trunc_functor n f₁₀) (trunc_functor n f₁₂) (trunc_functor n f₀₁) (trunc_functor n f₂₁) := λa, !trunc_functor_compose⁻¹ ⬝ trunc_functor_homotopy n h a ⬝ !trunc_functor_compose attribute hhconcat hvconcat [unfold_full] definition rfl_hhconcat (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : homotopy.rfl ⬝htyh q ~ q := homotopy.rfl definition hhconcat_rfl (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : q ⬝htyh homotopy.rfl ~ q := λx, !idp_con ⬝ ap_id (q x) definition rfl_hvconcat (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : homotopy.rfl ⬝htyv q ~ q := λx, inv_inv (q x) definition hvconcat_rfl (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : q ⬝htyv homotopy.rfl ~ q := λx, (!idp_con ⬝ !ap_id)⁻² ⬝ inv_inv (q x) end hsquare definition homotopy_group_succ_in_natural (n : ℕ) {A B : Type*} (f : A →* B) : hsquare (homotopy_group_succ_in A n) (homotopy_group_succ_in B n) (π→[n+1] f) (π→[n] (Ω→ f)) := trunc_functor_hsquare _ (loopn_succ_in_natural n f)⁻¹* definition homotopy2.refl {A} {B : A → Type} {C : Π⦃a⦄, B a → Type} (f : Πa (b : B a), C b) : f ~2 f := λa b, idp definition homotopy2.rfl [refl] {A} {B : A → Type} {C : Π⦃a⦄, B a → Type} {f : Πa (b : B a), C b} : f ~2 f := λa b, idp definition homotopy3.refl {A} {B : A → Type} {C : Πa, B a → Type} {D : Π⦃a⦄ ⦃b : B a⦄, C a b → Type} (f : Πa b (c : C a b), D c) : f ~3 f := λa b c, idp definition homotopy3.rfl {A} {B : A → Type} {C : Πa, B a → Type} {D : Π⦃a⦄ ⦃b : B a⦄, C a b → Type} {f : Πa b (c : C a b), D c} : f ~3 f := λa b c, idp definition eq_tr_of_pathover_con_tr_eq_of_pathover {A : Type} {B : A → Type} {a₁ a₂ : A} (p : a₁ = a₂) {b₁ : B a₁} {b₂ : B a₂} (q : b₁ =[p] b₂) : eq_tr_of_pathover q ⬝ tr_eq_of_pathover q⁻¹ᵒ = idp := by induction q; reflexivity end eq open eq namespace nat protected definition rec_down (P : ℕ → Type) (s : ℕ) (H0 : P s) (Hs : Πn, P (n+1) → P n) : P 0 := have Hp : Πn, P n → P (pred n), begin intro n p, cases n with n, { exact p }, { exact Hs n p } end, have H : Πn, P (s - n), begin intro n, induction n with n p, { exact H0 }, { exact Hp (s - n) p } end, transport P (nat.sub_self s) (H s) end nat namespace trunc_index open is_conn nat trunc is_trunc lemma minus_two_add_plus_two (n : ℕ₋₂) : -2+2+n = n := by induction n with n p; reflexivity; exact ap succ p protected definition of_nat_monotone {n k : ℕ} : n ≤ k → of_nat n ≤ of_nat k := begin intro H, induction H with k H K, { apply le.tr_refl }, { apply le.step K } end lemma add_plus_two_comm (n k : ℕ₋₂) : n +2+ k = k +2+ n := begin induction n with n IH, { exact minus_two_add_plus_two k }, { exact !succ_add_plus_two ⬝ ap succ IH} end end trunc_index namespace int private definition maxm2_le.lemma₁ {n k : ℕ} : n+(1:int) + -[1+ k] ≤ n := le.intro ( calc n + 1 + -[1+ k] + k = n + 1 + (-(k + 1)) + k : by reflexivity ... = n + 1 + (- 1 - k) + k : by krewrite (neg_add_rev k 1) ... = n + 1 + (- 1 - k + k) : add.assoc ... = n + 1 + (- 1 + -k + k) : by reflexivity ... = n + 1 + (- 1 + (-k + k)) : add.assoc ... = n + 1 + (- 1 + 0) : add.left_inv ... = n + (1 + (- 1 + 0)) : add.assoc ... = n : int.add_zero) private definition maxm2_le.lemma₂ {n : ℕ} {k : ℤ} : -[1+ n] + 1 + k ≤ k := le.intro ( calc -[1+ n] + 1 + k + n = - (n + 1) + 1 + k + n : by reflexivity ... = -n - 1 + 1 + k + n : by rewrite (neg_add n 1) ... = -n + (- 1 + 1) + k + n : by krewrite (int.add_assoc (-n) (- 1) 1) ... = -n + 0 + k + n : add.left_inv 1 ... = -n + k + n : int.add_zero ... = k + -n + n : int.add_comm ... = k + (-n + n) : int.add_assoc ... = k + 0 : add.left_inv n ... = k : int.add_zero) open trunc_index /- The function from integers to truncation indices which sends positive numbers to themselves, and negative numbers to negative 2. In particular -1 is sent to -2, but since we only work with pointed types, that doesn't matter for us -/ definition maxm2 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n trunc_index.of_nat (λk, -2) -- we also need the max -1 - function definition maxm1 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n trunc_index.of_nat (λk, -1) definition maxm2_le_maxm1 (n : ℤ) : maxm2 n ≤ maxm1 n := begin induction n with n n, { exact le.tr_refl n }, { exact minus_two_le -1 } end -- the is maxm1 minus 1 definition maxm1m1 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n (λ k, k.-1) (λ k, -2) definition maxm1_eq_succ (n : ℤ) : maxm1 n = (maxm1m1 n).+1 := begin induction n with n n, { reflexivity }, { reflexivity } end definition maxm2_le_maxm0 (n : ℤ) : maxm2 n ≤ max0 n := begin induction n with n n, { exact le.tr_refl n }, { exact minus_two_le 0 } end definition max0_le_of_le {n : ℤ} {m : ℕ} (H : n ≤ of_nat m) : nat.le (max0 n) m := begin induction n with n n, { exact le_of_of_nat_le_of_nat H }, { exact nat.zero_le m } end definition not_neg_succ_le_of_nat {n m : ℕ} : ¬m ≤ -[1+n] := by cases m: exact id definition maxm2_monotone {n m : ℤ} (H : n ≤ m) : maxm2 n ≤ maxm2 m := begin induction n with n n, { induction m with m m, { apply of_nat_le_of_nat, exact le_of_of_nat_le_of_nat H }, { exfalso, exact not_neg_succ_le_of_nat H }}, { apply minus_two_le } end definition sub_nat_le (n : ℤ) (m : ℕ) : n - m ≤ n := le.intro !sub_add_cancel definition sub_one_le (n : ℤ) : n - 1 ≤ n := sub_nat_le n 1 definition le_add_nat (n : ℤ) (m : ℕ) : n ≤ n + m := le.intro rfl definition le_add_one (n : ℤ) : n ≤ n + 1:= le_add_nat n 1 open trunc_index definition maxm2_le (n k : ℤ) : maxm2 (n+1+k) ≤ (maxm1m1 n).+1+2+(maxm1m1 k) := begin rewrite [-(maxm1_eq_succ n)], induction n with n n, { induction k with k k, { induction k with k IH, { apply le.tr_refl }, { exact succ_le_succ IH } }, { exact trunc_index.le_trans (maxm2_monotone maxm2_le.lemma₁) (maxm2_le_maxm1 n) } }, { krewrite (add_plus_two_comm -1 (maxm1m1 k)), rewrite [-(maxm1_eq_succ k)], exact trunc_index.le_trans (maxm2_monotone maxm2_le.lemma₂) (maxm2_le_maxm1 k) } end end int open int namespace pmap /- rename: pmap_eta in namespace pointed -/ definition eta {A B : Type*} (f : A →* B) : pmap.mk f (respect_pt f) = f := begin induction f, reflexivity end end pmap namespace lift definition is_trunc_plift [instance] [priority 1450] (A : Type*) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc n (plift A) := is_trunc_lift A n end lift namespace trunc open trunc_index definition trunc_index_equiv_nat [constructor] : ℕ₋₂ ≃ ℕ := equiv.MK add_two sub_two add_two_sub_two sub_two_add_two definition is_set_trunc_index [instance] : is_set ℕ₋₂ := is_trunc_equiv_closed_rev 0 trunc_index_equiv_nat definition is_contr_ptrunc_minus_one (A : Type*) : is_contr (ptrunc -1 A) := is_contr_of_inhabited_prop pt -- TODO: redefine loopn_ptrunc_pequiv definition apn_ptrunc_functor (n : ℕ₋₂) (k : ℕ) {A B : Type*} (f : A →* B) : Ω→[k] (ptrunc_functor (n+k) f) ∘* (loopn_ptrunc_pequiv n k A)⁻¹ᵉ* ~* (loopn_ptrunc_pequiv n k B)⁻¹ᵉ* ∘* ptrunc_functor n (Ω→[k] f) := begin revert n, induction k with k IH: intro n, { reflexivity }, { exact sorry } end definition ptrunc_pequiv_natural [constructor] (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc n A] [is_trunc n B] : f ∘* ptrunc_pequiv n A ~* ptrunc_pequiv n B ∘* ptrunc_functor n f := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { refine !idp_con ⬝ _ ⬝ !idp_con⁻¹, refine !ap_compose'⁻¹ ⬝ _, apply ap_id } end definition ptr_natural [constructor] (n : ℕ₋₂) {A B : Type*} (f : A →* B) : ptrunc_functor n f ∘* ptr n A ~* ptr n B ∘* f := begin fapply phomotopy.mk, { intro a, reflexivity }, { reflexivity } end definition ptrunc_elim_pcompose (n : ℕ₋₂) {A B C : Type*} (g : B →* C) (f : A →* B) [is_trunc n B] [is_trunc n C] : ptrunc.elim n (g ∘* f) ~* g ∘* ptrunc.elim n f := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { apply idp_con } end definition ptrunc_elim_ptr_phomotopy_pid (n : ℕ₋₂) (A : Type*): ptrunc.elim n (ptr n A) ~* pid (ptrunc n A) := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { apply idp_con } end definition is_trunc_ptrunc_of_is_trunc [instance] [priority 500] (A : Type*) (n m : ℕ₋₂) [H : is_trunc n A] : is_trunc n (ptrunc m A) := is_trunc_trunc_of_is_trunc A n m definition ptrunc_pequiv_ptrunc_of_is_trunc {n m k : ℕ₋₂} {A : Type*} (H1 : n ≤ m) (H2 : n ≤ k) (H : is_trunc n A) : ptrunc m A ≃* ptrunc k A := have is_trunc m A, from is_trunc_of_le A H1, have is_trunc k A, from is_trunc_of_le A H2, pequiv.MK (ptrunc.elim _ (ptr k A)) (ptrunc.elim _ (ptr m A)) abstract begin refine !ptrunc_elim_pcompose⁻¹* ⬝* _, exact ptrunc_elim_phomotopy _ !ptrunc_elim_ptr ⬝* !ptrunc_elim_ptr_phomotopy_pid, end end abstract begin refine !ptrunc_elim_pcompose⁻¹* ⬝* _, exact ptrunc_elim_phomotopy _ !ptrunc_elim_ptr ⬝* !ptrunc_elim_ptr_phomotopy_pid, end end definition ptrunc_change_index {k l : ℕ₋₂} (p : k = l) (X : Type*) : ptrunc k X ≃* ptrunc l X := pequiv_ap (λ n, ptrunc n X) p definition ptrunc_functor_le {k l : ℕ₋₂} (p : l ≤ k) (X : Type*) : ptrunc k X →* ptrunc l X := have is_trunc k (ptrunc l X), from is_trunc_of_le _ p, ptrunc.elim _ (ptr l X) definition trunc_index.pred [unfold 1] (n : ℕ₋₂) : ℕ₋₂ := begin cases n with n, exact -2, exact n end /- A more general version of ptrunc_elim_phomotopy, where the proofs of truncatedness might be different -/ definition ptrunc_elim_phomotopy2 [constructor] (k : ℕ₋₂) {A B : Type*} {f g : A →* B} (H₁ : is_trunc k B) (H₂ : is_trunc k B) (p : f ~* g) : @ptrunc.elim k A B H₁ f ~* @ptrunc.elim k A B H₂ g := begin fapply phomotopy.mk, { intro x, induction x with a, exact p a }, { exact to_homotopy_pt p } end end trunc namespace is_trunc open trunc_index is_conn definition is_trunc_of_eq {n m : ℕ₋₂} (p : n = m) {A : Type} (H : is_trunc n A) : is_trunc m A := transport (λk, is_trunc k A) p H definition is_trunc_succ_succ_of_is_trunc_loop (n : ℕ₋₂) (A : Type*) (H : is_trunc (n.+1) (Ω A)) (H2 : is_conn 0 A) : is_trunc (n.+2) A := begin apply is_trunc_succ_of_is_trunc_loop, apply minus_one_le_succ, refine is_conn.elim -1 _ _, exact H end lemma is_trunc_of_is_trunc_loopn (m n : ℕ) (A : Type*) (H : is_trunc n (Ω[m] A)) (H2 : is_conn m A) : is_trunc (m + n) A := begin revert A H H2; induction m with m IH: intro A H H2, { rewrite [nat.zero_add], exact H }, rewrite [succ_add], apply is_trunc_succ_succ_of_is_trunc_loop, { apply IH, { apply is_trunc_equiv_closed _ !loopn_succ_in }, apply is_conn_loop }, exact is_conn_of_le _ (zero_le_of_nat (succ m)) end lemma is_trunc_of_is_set_loopn (m : ℕ) (A : Type*) (H : is_set (Ω[m] A)) (H2 : is_conn m A) : is_trunc m A := is_trunc_of_is_trunc_loopn m 0 A H H2 end is_trunc namespace sigma open sigma.ops definition sigma_eq_equiv_of_is_prop_right [constructor] {A : Type} {B : A → Type} (u v : Σa, B a) [H : Π a, is_prop (B a)] : u = v ≃ u.1 = v.1 := !sigma_eq_equiv ⬝e !sigma_equiv_of_is_contr_right definition ap_sigma_pr1 {A B : Type} {C : B → Type} {a₁ a₂ : A} (f : A → B) (g : Πa, C (f a)) (p : a₁ = a₂) : (ap (λa, ⟨f a, g a⟩) p)..1 = ap f p := by induction p; reflexivity definition ap_sigma_pr2 {A B : Type} {C : B → Type} {a₁ a₂ : A} (f : A → B) (g : Πa, C (f a)) (p : a₁ = a₂) : (ap (λa, ⟨f a, g a⟩) p)..2 = change_path (ap_sigma_pr1 f g p)⁻¹ (pathover_ap C f (apd g p)) := by induction p; reflexivity -- open sigma.ops -- definition eq.rec_sigma {A : Type} {B : A → Type} {a₀ : A} {b₀ : B a₀} -- {P : Π(a : A) (b : B a), ⟨a₀, b₀⟩ = ⟨a, b⟩ → Type} (H : P a₀ b₀ idp) {a : A} {b : B a} -- (p : ⟨a₀, b₀⟩ = ⟨a, b⟩) : P a b p := -- sorry -- definition sigma_pathover_equiv_of_is_prop {A : Type} {B : A → Type} {C : Πa, B a → Type} -- {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} -- [Πa b, is_prop (C a b)] : ⟨b, c⟩ =[p] ⟨b', c'⟩ ≃ b =[p] b' := -- begin -- fapply equiv.MK, -- { exact pathover_pr1 }, -- { intro q, induction q, apply pathover_idp_of_eq, exact sigma_eq idp !is_prop.elimo }, -- { intro q, induction q, -- have c = c', from !is_prop.elim, induction this, -- rewrite [▸*, is_prop_elimo_self (C a) c] }, -- { esimp, generalize ⟨b, c⟩, intro x q, } -- end --rexact @(ap pathover_pr1) _ idpo _, end sigma open sigma namespace group -- definition is_equiv_isomorphism -- some extra instances for type class inference -- definition is_mul_hom_comm_homomorphism [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' (@ab_group.to_group _ (AbGroup.struct G)) -- (@ab_group.to_group _ (AbGroup.struct G')) φ := -- homomorphism.struct φ -- definition is_mul_hom_comm_homomorphism1 [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' _ -- (@ab_group.to_group _ (AbGroup.struct G')) φ := -- homomorphism.struct φ -- definition is_mul_hom_comm_homomorphism2 [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' (@ab_group.to_group _ (AbGroup.struct G)) _ φ := -- homomorphism.struct φ definition pgroup_of_Group (X : Group) : pgroup X := pgroup_of_group _ idp definition isomorphism_ap {A : Type} (F : A → Group) {a b : A} (p : a = b) : F a ≃g F b := isomorphism_of_eq (ap F p) definition interchange (G : AbGroup) (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) := calc (a * b) * (c * d) = a * (b * (c * d)) : by exact mul.assoc a b (c * d) ... = a * ((b * c) * d) : by exact ap (λ bcd, a * bcd) (mul.assoc b c d)⁻¹ ... = a * ((c * b) * d) : by exact ap (λ bc, a * (bc * d)) (mul.comm b c) ... = a * (c * (b * d)) : by exact ap (λ bcd, a * bcd) (mul.assoc c b d) ... = (a * c) * (b * d) : by exact (mul.assoc a c (b * d))⁻¹ definition homomorphism_comp_compute {G H K : Group} (g : H →g K) (f : G →g H) (x : G) : (g ∘g f) x = g (f x) := begin reflexivity end open option definition add_point_AbGroup [unfold 3] {X : Type} (G : X → AbGroup) : X₊ → AbGroup | (some x) := G x | none := trivial_ab_group_lift definition isomorphism_of_is_contr {G H : Group} (hG : is_contr G) (hH : is_contr H) : G ≃g H := trivial_group_of_is_contr G ⬝g (trivial_group_of_is_contr H)⁻¹ᵍ definition trunc_isomorphism_of_equiv {A B : Type} [inf_group A] [inf_group B] (f : A ≃ B) (h : is_mul_hom f) : Group.mk (trunc 0 A) (trunc_group A) ≃g Group.mk (trunc 0 B) (trunc_group B) := begin apply isomorphism_of_equiv (equiv.mk (trunc_functor 0 f) (is_equiv_trunc_functor 0 f)), intros x x', induction x with a, induction x' with a', apply ap tr, exact h a a' end end group open group namespace fiber definition is_contr_pfiber_pid (A : Type*) : is_contr (pfiber (pid A)) := is_contr.mk pt begin intro x, induction x with a p, esimp at p, cases p, reflexivity end end fiber namespace function variables {A B : Type} {f f' : A → B} open is_conn sigma.ops definition merely_constant {A B : Type} (f : A → B) : Type := Σb, Πa, merely (f a = b) definition merely_constant_pmap {A B : Type*} {f : A →* B} (H : merely_constant f) (a : A) : merely (f a = pt) := tconcat (tconcat (H.2 a) (tinverse (H.2 pt))) (tr (respect_pt f)) definition merely_constant_of_is_conn {A B : Type*} (f : A →* B) [is_conn 0 A] : merely_constant f := ⟨pt, is_conn.elim -1 _ (tr (respect_pt f))⟩ definition homotopy_group_isomorphism_of_is_embedding (n : ℕ) [H : is_succ n] {A B : Type*} (f : A →* B) [H2 : is_embedding f] : πg[n] A ≃g πg[n] B := begin apply isomorphism.mk (homotopy_group_homomorphism n f), induction H with n, apply is_equiv_of_equiv_of_homotopy (ptrunc_pequiv_ptrunc 0 (loopn_pequiv_loopn_of_is_embedding (n+1) f)), exact sorry end end function open function namespace is_conn open unit trunc_index nat is_trunc pointed.ops definition is_conn_zero {A : Type} (a₀ : trunc 0 A) (p : Πa a' : A, ∥ a = a' ∥) : is_conn 0 A := is_conn_succ_intro a₀ (λa a', is_conn_minus_one _ (p a a')) definition is_conn_zero_pointed {A : Type*} (p : Πa a' : A, ∥ a = a' ∥) : is_conn 0 A := is_conn_zero (tr pt) p definition is_conn_fiber (n : ℕ₋₂) {A B : Type} (f : A → B) (b : B) [is_conn n A] [is_conn (n.+1) B] : is_conn n (fiber f b) := is_conn_equiv_closed_rev _ !fiber.sigma_char _ definition is_conn_fun_compose {n : ℕ₋₂} {A B C : Type} (g : B → C) (f : A → B) (H : is_conn_fun n g) (K : is_conn_fun n f) : is_conn_fun n (g ∘ f) := sorry end is_conn namespace misc open is_conn open sigma.ops pointed trunc_index definition component [constructor] (A : Type*) : Type* := pType.mk (Σ(a : A), merely (pt = a)) ⟨pt, tr idp⟩ lemma is_conn_component [instance] (A : Type*) : is_conn 0 (component A) := is_contr.mk (tr pt) begin intro x, induction x with x, induction x with a p, induction p with p, induction p, reflexivity end definition component_incl [constructor] (A : Type*) : component A →* A := pmap.mk pr1 idp definition is_embedding_component_incl [instance] (A : Type*) : is_embedding (component_incl A) := is_embedding_pr1 _ definition component_intro [constructor] {A B : Type*} (f : A →* B) (H : merely_constant f) : A →* component B := begin fapply pmap.mk, { intro a, refine ⟨f a, _⟩, exact tinverse (merely_constant_pmap H a) }, exact subtype_eq !respect_pt end definition component_functor [constructor] {A B : Type*} (f : A →* B) : component A →* component B := component_intro (f ∘* component_incl A) !merely_constant_of_is_conn -- definition component_elim [constructor] {A B : Type*} (f : A →* B) (H : merely_constant f) : -- A →* component B := -- begin -- fapply pmap.mk, -- { intro a, refine ⟨f a, _⟩, exact tinverse (merely_constant_pmap H a) }, -- exact subtype_eq !respect_pt -- end definition loop_component (A : Type*) : Ω (component A) ≃* Ω A := loop_pequiv_loop_of_is_embedding (component_incl A) lemma loopn_component (n : ℕ) (A : Type*) : Ω[n+1] (component A) ≃* Ω[n+1] A := !loopn_succ_in ⬝e* loopn_pequiv_loopn n (loop_component A) ⬝e* !loopn_succ_in⁻¹ᵉ* -- lemma fundamental_group_component (A : Type*) : π₁ (component A) ≃g π₁ A := -- isomorphism_of_equiv (trunc_equiv_trunc 0 (loop_component A)) _ lemma homotopy_group_component (n : ℕ) (A : Type*) : πg[n+1] (component A) ≃g πg[n+1] A := homotopy_group_isomorphism_of_is_embedding (n+1) (component_incl A) definition is_trunc_component [instance] (n : ℕ₋₂) (A : Type*) [is_trunc n A] : is_trunc n (component A) := begin apply @is_trunc_sigma, intro a, cases n with n, { apply is_contr_of_inhabited_prop, exact tr !is_prop.elim }, { apply is_trunc_succ_of_is_prop }, end definition ptrunc_component' (n : ℕ₋₂) (A : Type*) : ptrunc (n.+2) (component A) ≃* component (ptrunc (n.+2) A) := begin fapply pequiv.MK', { exact ptrunc.elim (n.+2) (component_functor !ptr) }, { intro x, cases x with x p, induction x with a, refine tr ⟨a, _⟩, note q := trunc_functor -1 !tr_eq_tr_equiv p, exact trunc_trunc_equiv_left _ !minus_one_le_succ q }, { exact sorry }, { exact sorry } end definition ptrunc_component (n : ℕ₋₂) (A : Type*) : ptrunc n (component A) ≃* component (ptrunc n A) := begin cases n with n, exact sorry, cases n with n, exact sorry, exact ptrunc_component' n A end definition break_into_components (A : Type) : A ≃ Σ(x : trunc 0 A), Σ(a : A), ∥ tr a = x ∥ := calc A ≃ Σ(a : A) (x : trunc 0 A), tr a = x : by exact (@sigma_equiv_of_is_contr_right _ _ (λa, !is_contr_sigma_eq))⁻¹ᵉ ... ≃ Σ(x : trunc 0 A) (a : A), tr a = x : by apply sigma_comm_equiv ... ≃ Σ(x : trunc 0 A), Σ(a : A), ∥ tr a = x ∥ : by exact sigma_equiv_sigma_right (λx, sigma_equiv_sigma_right (λa, !trunc_equiv⁻¹ᵉ)) definition pfiber_pequiv_component_of_is_contr [constructor] {A B : Type*} (f : A →* B) [is_contr B] /- extra condition, something like trunc_functor 0 f is an embedding -/ : pfiber f ≃* component A := sorry end misc namespace category definition precategory_Group.{u} [instance] [constructor] : precategory.{u+1 u} Group := begin fapply precategory.mk, { exact λG H, G →g H }, { exact _ }, { exact λG H K ψ φ, ψ ∘g φ }, { exact λG, gid G }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp } end definition precategory_AbGroup.{u} [instance] [constructor] : precategory.{u+1 u} AbGroup := begin fapply precategory.mk, { exact λG H, G →g H }, { exact _ }, { exact λG H K ψ φ, ψ ∘g φ }, { exact λG, gid G }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp } end open iso definition Group_is_iso_of_is_equiv {G H : Group} (φ : G →g H) (H : is_equiv (group_fun φ)) : is_iso φ := begin fconstructor, { exact (isomorphism.mk φ H)⁻¹ᵍ }, { apply homomorphism_eq, rexact left_inv φ }, { apply homomorphism_eq, rexact right_inv φ } end definition Group_is_equiv_of_is_iso {G H : Group} (φ : G ⟶ H) (Hφ : is_iso φ) : is_equiv (group_fun φ) := begin fapply adjointify, { exact group_fun φ⁻¹ʰ }, { note p := right_inverse φ, exact ap010 group_fun p }, { note p := left_inverse φ, exact ap010 group_fun p } end definition Group_iso_equiv (G H : Group) : (G ≅ H) ≃ (G ≃g H) := begin fapply equiv.MK, { intro φ, induction φ with φ φi, constructor, exact Group_is_equiv_of_is_iso φ _ }, { intro v, induction v with φ φe, constructor, exact Group_is_iso_of_is_equiv φ _ }, { intro v, induction v with φ φe, apply isomorphism_eq, reflexivity }, { intro φ, induction φ with φ φi, apply iso_eq, reflexivity } end definition Group_props.{u} {A : Type.{u}} (v : (A → A → A) × (A → A) × A) : Prop.{u} := begin induction v with m v, induction v with i o, fapply trunctype.mk, { exact is_set A × (Πa, m a o = a) × (Πa, m o a = a) × (Πa b c, m (m a b) c = m a (m b c)) × (Πa, m (i a) a = o) }, { apply is_trunc_of_imp_is_trunc, intro v, induction v with H v, have is_prop (Πa, m a o = a), from _, have is_prop (Πa, m o a = a), from _, have is_prop (Πa b c, m (m a b) c = m a (m b c)), from _, have is_prop (Πa, m (i a) a = o), from _, apply is_trunc_prod } end definition Group.sigma_char2.{u} : Group.{u} ≃ Σ(A : Type.{u}) (v : (A → A → A) × (A → A) × A), Group_props v := begin fapply equiv.MK, { intro G, refine ⟨G, _⟩, induction G with G g, induction g with m s ma o om mo i mi, repeat (fconstructor; do 2 try assumption), }, { intro v, induction v with x v, induction v with y v, repeat induction y with x y, repeat induction v with x v, constructor, fconstructor, repeat assumption }, { intro v, induction v with x v, induction v with y v, repeat induction y with x y, repeat induction v with x v, reflexivity }, { intro v, repeat induction v with x v, reflexivity }, end open is_trunc section local attribute group.to_has_mul group.to_has_inv [coercion] theorem inv_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A G ~2 @mul A H) : @inv A G ~ @inv A H := begin have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g, from λg, !mul_inv_cancel_right⁻¹, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4, change Gi ~ Hi, intro g, have p' : Gm ~2 Hm, from p, calc Gi g = Hm (Hm (Gi g) g) (Hi g) : foo ... = Hm (Gm (Gi g) g) (Hi g) : by rewrite p' ... = Hm G1 (Hi g) : by rewrite Gh4 ... = Gm G1 (Hi g) : by rewrite p' ... = Hi g : Gh2 end theorem one_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A (group.to_has_mul G) ~2 @mul A (group.to_has_mul H)) : @one A (group.to_has_one G) = @one A (group.to_has_one H) := begin cases G with Gm Gs Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hm Hs Hh1 H1 Hh2 Hh3 Hi Hh4, exact (Hh2 G1)⁻¹ ⬝ (p H1 G1)⁻¹ ⬝ Gh3 H1, end end open prod.ops definition group_of_Group_props.{u} {A : Type.{u}} {m : A → A → A} {i : A → A} {o : A} (H : Group_props (m, (i, o))) : group A := ⦃group, mul := m, inv := i, one := o, is_set_carrier := H.1, mul_one := H.2.1, one_mul := H.2.2.1, mul_assoc := H.2.2.2.1, mul_left_inv := H.2.2.2.2⦄ theorem Group_eq_equiv_lemma2 {A : Type} {m m' : A → A → A} {i i' : A → A} {o o' : A} (H : Group_props (m, (i, o))) (H' : Group_props (m', (i', o'))) : (m, (i, o)) = (m', (i', o')) ≃ (m ~2 m') := begin have is_set A, from pr1 H, apply equiv_of_is_prop, { intro p, exact apd100 (eq_pr1 p)}, { intro p, apply prod_eq (eq_of_homotopy2 p), apply prod_eq: esimp [Group_props] at *; esimp, { apply eq_of_homotopy, exact inv_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }, { exact one_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }} end open sigma.ops theorem Group_eq_equiv_lemma {G H : Group} (p : (Group.sigma_char2 G).1 = (Group.sigma_char2 H).1) : ((Group.sigma_char2 G).2 =[p] (Group.sigma_char2 H).2) ≃ (is_mul_hom (equiv_of_eq (proof p qed : Group.carrier G = Group.carrier H))) := begin refine !sigma_pathover_equiv_of_is_prop ⬝e _, induction G with G g, induction H with H h, esimp [Group.sigma_char2] at p, induction p, refine !pathover_idp ⬝e _, induction g with s m ma o om mo i mi, induction h with σ μ μa ε εμ με ι μι, exact Group_eq_equiv_lemma2 (Group.sigma_char2 (Group.mk G (group.mk s m ma o om mo i mi))).2.2 (Group.sigma_char2 (Group.mk G (group.mk σ μ μa ε εμ με ι μι))).2.2 end definition isomorphism.sigma_char (G H : Group) : (G ≃g H) ≃ Σ(e : G ≃ H), is_mul_hom e := begin fapply equiv.MK, { intro φ, exact ⟨equiv_of_isomorphism φ, to_respect_mul φ⟩ }, { intro v, induction v with e p, exact isomorphism_of_equiv e p }, { intro v, induction v with e p, induction e, reflexivity }, { intro φ, induction φ with φ H, induction φ, reflexivity }, end definition Group_eq_equiv (G H : Group) : G = H ≃ (G ≃g H) := begin refine (eq_equiv_fn_eq_of_equiv Group.sigma_char2 G H) ⬝e _, refine !sigma_eq_equiv ⬝e _, refine sigma_equiv_sigma_right Group_eq_equiv_lemma ⬝e _, transitivity (Σ(e : (Group.sigma_char2 G).1 ≃ (Group.sigma_char2 H).1), @is_mul_hom _ _ _ _ (to_fun e)), apply sigma_ua, exact !isomorphism.sigma_char⁻¹ᵉ end definition to_fun_Group_eq_equiv {G H : Group} (p : G = H) : Group_eq_equiv G H p ~ isomorphism_of_eq p := begin induction p, reflexivity end definition Group_eq2 {G H : Group} {p q : G = H} (r : isomorphism_of_eq p ~ isomorphism_of_eq q) : p = q := begin apply eq_of_fn_eq_fn (Group_eq_equiv G H), apply isomorphism_eq, intro g, refine to_fun_Group_eq_equiv p g ⬝ r g ⬝ (to_fun_Group_eq_equiv q g)⁻¹, end definition Group_eq_equiv_Group_iso (G₁ G₂ : Group) : G₁ = G₂ ≃ G₁ ≅ G₂ := Group_eq_equiv G₁ G₂ ⬝e (Group_iso_equiv G₁ G₂)⁻¹ᵉ definition category_Group.{u} : category Group.{u} := category.mk precategory_Group begin intro G H, apply is_equiv_of_equiv_of_homotopy (Group_eq_equiv_Group_iso G H), intro p, induction p, fapply iso_eq, apply homomorphism_eq, reflexivity end definition category_AbGroup : category AbGroup := category.mk precategory_AbGroup sorry definition Grp.{u} [constructor] : Category := category.Mk Group.{u} category_Group definition AbGrp [constructor] : Category := category.Mk AbGroup category_AbGroup end category namespace sphere -- definition constant_sphere_map_sphere {n m : ℕ} (H : n < m) (f : S n →* S m) : -- f ~* pconst (S n) (S m) := -- begin -- assert H : is_contr (Ω[n] (S m)), -- { apply homotopy_group_sphere_le, }, -- apply phomotopy_of_eq, -- apply eq_of_fn_eq_fn !sphere_pmap_pequiv, -- apply @is_prop.elim -- end end sphere section injective_surjective open trunc fiber image /- do we want to prove this without funext before we move it? -/ variables {A B C : Type} (f : A → B) definition is_embedding_factor [is_set A] [is_set B] (g : B → C) (h : A → C) (H : g ∘ f ~ h) : is_embedding h → is_embedding f := begin induction H using homotopy.rec_on_idp, intro E, fapply is_embedding_of_is_injective, intro x y p, fapply @is_injective_of_is_embedding _ _ _ E _ _ (ap g p) end definition is_surjective_factor (g : B → C) (h : A → C) (H : g ∘ f ~ h) : is_surjective h → is_surjective g := begin induction H using homotopy.rec_on_idp, intro S, intro c, note p := S c, induction p, apply tr, fapply fiber.mk, exact f a, exact p end end injective_surjective -- Yuri Sulyma's code from HoTT MRC notation `⅀→`:(max+5) := susp_functor notation `⅀⇒`:(max+5) := susp_functor_phomotopy notation `Ω⇒`:(max+5) := ap1_phomotopy definition ap1_phomotopy_symm {A B : Type*} {f g : A →* B} (p : f ~* g) : (Ω⇒ p)⁻¹* = Ω⇒ (p⁻¹*) := begin induction p using phomotopy_rec_idp, rewrite ap1_phomotopy_refl, xrewrite [+refl_symm], rewrite ap1_phomotopy_refl end definition ap1_phomotopy_trans {A B : Type*} {f g h : A →* B} (q : g ~* h) (p : f ~* g) : Ω⇒ (p ⬝* q) = Ω⇒ p ⬝* Ω⇒ q := begin induction p using phomotopy_rec_idp, induction q using phomotopy_rec_idp, rewrite trans_refl, rewrite [+ap1_phomotopy_refl], rewrite trans_refl end namespace pointed definition to_homotopy_pt_mk {A B : Type*} {f g : A →* B} (h : f ~ g) (p : h pt ⬝ respect_pt g = respect_pt f) : to_homotopy_pt (phomotopy.mk h p) = p := to_right_inv !eq_con_inv_equiv_con_eq p variables {A₀₀ A₂₀ A₀₂ A₂₂ : Type*} {f₁₀ : A₀₀ →* A₂₀} {f₁₂ : A₀₂ →* A₂₂} {f₀₁ : A₀₀ →* A₀₂} {f₂₁ : A₂₀ →* A₂₂} definition psquare_transpose (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : psquare f₀₁ f₂₁ f₁₀ f₁₂ := p⁻¹* end pointed namespace pi definition pi_bool_left_nat {A B : bool → Type} (g : Πx, A x -> B x) : hsquare (pi_bool_left A) (pi_bool_left B) (pi_functor_right g) (prod_functor (g ff) (g tt)) := begin intro h, esimp end definition pi_bool_left_inv_nat {A B : bool → Type} (g : Πx, A x -> B x) : hsquare (pi_bool_left A)⁻¹ᵉ (pi_bool_left B)⁻¹ᵉ (prod_functor (g ff) (g tt)) (pi_functor_right g) := hhinverse (pi_bool_left_nat g) end pi namespace sum infix ` +→ `:62 := sum_functor variables {A₀₀ A₂₀ A₀₂ A₂₂ B₀₀ B₂₀ B₀₂ B₂₂ A A' B B' C C' : Type} {f₁₀ : A₀₀ → A₂₀} {f₁₂ : A₀₂ → A₂₂} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {g₁₀ : B₀₀ → B₂₀} {g₁₂ : B₀₂ → B₂₂} {g₀₁ : B₀₀ → B₀₂} {g₂₁ : B₂₀ → B₂₂} {h₀₁ : B₀₀ → A₀₂} {h₂₁ : B₂₀ → A₂₂} definition sum_rec_hsquare [unfold 16] (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) (k : hsquare g₁₀ f₁₂ h₀₁ h₂₁) : hsquare (f₁₀ +→ g₁₀) f₁₂ (sum.rec f₀₁ h₀₁) (sum.rec f₂₁ h₂₁) := begin intro x, induction x with a b, exact h a, exact k b end definition sum_functor_hsquare [unfold 19] (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) (k : hsquare g₁₀ g₁₂ g₀₁ g₂₁) : hsquare (f₁₀ +→ g₁₀) (f₁₂ +→ g₁₂) (f₀₁ +→ g₀₁) (f₂₁ +→ g₂₁) := sum_rec_hsquare (λa, ap inl (h a)) (λb, ap inr (k b)) definition sum_functor_compose (g : B → C) (f : A → B) (g' : B' → C') (f' : A' → B') : (g ∘ f) +→ (g' ∘ f') ~ g +→ g' ∘ f +→ f' := begin intro x, induction x with a a': reflexivity end definition sum_rec_sum_functor (g : B → C) (g' : B' → C) (f : A → B) (f' : A' → B') : sum.rec g g' ∘ sum_functor f f' ~ sum.rec (g ∘ f) (g' ∘ f') := begin intro x, induction x with a a': reflexivity end definition sum_rec_same_compose (g : B → C) (f : A → B) : sum.rec (g ∘ f) (g ∘ f) ~ g ∘ sum.rec f f := begin intro x, induction x with a a': reflexivity end definition sum_rec_same (f : A → B) : sum.rec f f ~ f ∘ sum.rec id id := sum_rec_same_compose f id end sum namespace prod infix ` ×→ `:63 := prod_functor end prod namespace equiv definition rec_eq_of_equiv {A : Type} {P : A → A → Type} (e : Πa a', a = a' ≃ P a a') {a a' : A} (Q : P a a' → Type) (H : Π(q : a = a'), Q (e a a' q)) : Π(p : P a a'), Q p := equiv_rect (e a a') Q H definition rec_idp_of_equiv {A : Type} {P : A → A → Type} (e : Πa a', a = a' ≃ P a a') {a : A} (r : P a a) (s : e a a idp = r) (Q : Πa', P a a' → Type) (H : Q a r) ⦃a' : A⦄ (p : P a a') : Q a' p := rec_eq_of_equiv e _ begin intro q, induction q, induction s, exact H end p definition rec_idp_of_equiv_idp {A : Type} {P : A → A → Type} (e : Πa a', a = a' ≃ P a a') {a : A} (r : P a a) (s : e a a idp = r) (Q : Πa', P a a' → Type) (H : Q a r) : rec_idp_of_equiv e r s Q H r = H := begin induction s, refine !is_equiv_rect_comp ⬝ _, reflexivity end end equiv
e02cd0acef52b22410b4c4733bd59ca1634896af
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/tactic/basic.lean
1dfddba76b78d74ac4fc78384c9d2990237291af
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
792
lean
import tactic.alias import tactic.clear import tactic.converter.apply_congr import tactic.delta_instance import tactic.elide import tactic.explode import tactic.find import tactic.finish import tactic.generalizes import tactic.generalize_proofs import tactic.lift import tactic.lint import tactic.localized import tactic.mk_iff_of_inductive_prop import tactic.norm_cast import tactic.obviously import tactic.protected import tactic.push_neg import tactic.replacer import tactic.rename_var import tactic.restate_axiom import tactic.rewrite import tactic.show_term import tactic.simp_rw import tactic.simp_command import tactic.simp_result import tactic.simps import tactic.split_ifs import tactic.squeeze import tactic.suggest import tactic.tauto import tactic.trunc_cases import tactic.where
cac7ae135ccc7f6d00364fab4fde1f1d0c93e11e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/theories/analysis/metric_space.lean
e5c2911f4c44abc2ae0cf5561dce65c08cdfba9c
[ "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
27,572
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Metric spaces. -/ import data.real.complete data.pnat data.list.sort ..topology.basic data.set open nat real eq.ops classical structure metric_space [class] (M : Type) : Type := (dist : M → M → ℝ) (dist_self : ∀ x : M, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : M}, dist x y = 0 → x = y) (dist_comm : ∀ x y : M, dist x y = dist y x) (dist_triangle : ∀ x y z : M, dist x z ≤ dist x y + dist y z) namespace analysis section metric_space_M variables {M : Type} [metric_space M] definition dist (x y : M) : ℝ := metric_space.dist x y proposition dist_self (x : M) : dist x x = 0 := metric_space.dist_self x proposition eq_of_dist_eq_zero {x y : M} (H : dist x y = 0) : x = y := metric_space.eq_of_dist_eq_zero H proposition dist_comm (x y : M) : dist x y = dist y x := metric_space.dist_comm x y proposition dist_eq_zero_iff (x y : M) : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (suppose x = y, this ▸ !dist_self) proposition dist_triangle (x y z : M) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z proposition dist_nonneg (x y : M) : 0 ≤ dist x y := have dist x y + dist y x ≥ 0, by rewrite -(dist_self x); apply dist_triangle, have 2 * dist x y ≥ 0, by krewrite [-real.one_add_one, right_distrib, +one_mul, dist_comm at {2}]; apply this, nonneg_of_mul_nonneg_left this two_pos proposition dist_pos_of_ne {x y : M} (H : x ≠ y) : dist x y > 0 := lt_of_le_of_ne !dist_nonneg (suppose 0 = dist x y, H (iff.mp !dist_eq_zero_iff this⁻¹)) proposition ne_of_dist_pos {x y : M} (H : dist x y > 0) : x ≠ y := suppose x = y, have H1 : dist x x > 0, by rewrite this at {2}; exact H, by rewrite dist_self at H1; apply not_lt_self _ H1 proposition eq_of_forall_dist_le {x y : M} (H : ∀ ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_zero_of_nonneg_of_forall_le !dist_nonneg H) /- convergence of a sequence -/ definition converges_to_seq (X : ℕ → M) (y : M) : Prop := ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ ⦃n⦄, n ≥ N → dist (X n) y < ε -- the same, with ≤ in place of <; easier to prove, harder to use definition converges_to_seq.intro {X : ℕ → M} {y : M} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → dist (X n) y ≤ ε) : converges_to_seq X y := take ε, assume epos : ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain N HN, from H e2pos, exists.intro N (take n, suppose n ≥ N, calc dist (X n) y ≤ ε / 2 : HN _ `n ≥ N` ... < ε : div_two_lt_of_pos epos) notation X `⟶` y `in` `ℕ` := converges_to_seq X y attribute [class] definition converges_seq (X : ℕ → M) : Prop := ∃ y, X ⟶ y in ℕ noncomputable definition limit_seq (X : ℕ → M) [H : converges_seq X] : M := some H proposition converges_to_limit_seq (X : ℕ → M) [H : converges_seq X] : (X ⟶ limit_seq X in ℕ) := some_spec H proposition converges_to_seq_unique {X : ℕ → M} {y₁ y₂ : M} (H₁ : X ⟶ y₁ in ℕ) (H₂ : X ⟶ y₂ in ℕ) : y₁ = y₂ := eq_of_forall_dist_le (take ε, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y₁ < ε / 2), from H₁ e2pos, obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y₂ < ε / 2), from H₂ e2pos, let N := max N₁ N₂ in have dN₁ : dist (X N) y₁ < ε / 2, from HN₁ !le_max_left, have dN₂ : dist (X N) y₂ < ε / 2, from HN₂ !le_max_right, have dist y₁ y₂ < ε, from calc dist y₁ y₂ ≤ dist y₁ (X N) + dist (X N) y₂ : dist_triangle ... = dist (X N) y₁ + dist (X N) y₂ : dist_comm ... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂ ... = ε : add_halves, show dist y₁ y₂ ≤ ε, from le_of_lt this) proposition eq_limit_of_converges_to_seq {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) : y = @limit_seq M _ X (exists.intro y H) := converges_to_seq_unique H (@converges_to_limit_seq M _ X (exists.intro y H)) proposition converges_to_seq_constant (y : M) : (λn, y) ⟶ y in ℕ := take ε, assume egt0 : ε > 0, exists.intro 0 (take n, suppose n ≥ 0, calc dist y y = 0 : !dist_self ... < ε : egt0) proposition converges_to_seq_offset {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) : (λ n, X (n + k)) ⟶ y in ℕ := take ε, suppose ε > 0, obtain N HN, from H `ε > 0`, exists.intro N (take n : ℕ, assume ngtN : n ≥ N, show dist (X (n + k)) y < ε, from HN (n + k) (le.trans ngtN !le_add_right)) proposition converges_to_seq_offset_left {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) : (λ n, X (k + n)) ⟶ y in ℕ := have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm), by rewrite aux; exact converges_to_seq_offset k H proposition converges_to_seq_offset_succ {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) : (λ n, X (succ n)) ⟶ y in ℕ := converges_to_seq_offset 1 H proposition converges_to_seq_of_converges_to_seq_offset {X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (n + k)) ⟶ y in ℕ) : X ⟶ y in ℕ := take ε, suppose ε > 0, obtain N HN, from H `ε > 0`, exists.intro (N + k) (take n : ℕ, assume nge : n ≥ N + k, have n - k ≥ N, from nat.le_sub_of_add_le nge, have dist (X (n - k + k)) y < ε, from HN (n - k) this, show dist (X n) y < ε, by rewrite [(nat.sub_add_cancel (le.trans !le_add_left nge)) at this]; exact this) proposition converges_to_seq_of_converges_to_seq_offset_left {X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (k + n)) ⟶ y in ℕ) : X ⟶ y in ℕ := have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm), by rewrite aux at H; exact converges_to_seq_of_converges_to_seq_offset H proposition converges_to_seq_of_converges_to_seq_offset_succ {X : ℕ → M} {y : M} (H : (λ n, X (succ n)) ⟶ y in ℕ) : X ⟶ y in ℕ := @converges_to_seq_of_converges_to_seq_offset M _ X y 1 H proposition converges_to_seq_offset_iff (X : ℕ → M) (y : M) (k : ℕ) : ((λ n, X (n + k)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) := iff.intro converges_to_seq_of_converges_to_seq_offset !converges_to_seq_offset proposition converges_to_seq_offset_left_iff (X : ℕ → M) (y : M) (k : ℕ) : ((λ n, X (k + n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) := iff.intro converges_to_seq_of_converges_to_seq_offset_left !converges_to_seq_offset_left proposition converges_to_seq_offset_succ_iff (X : ℕ → M) (y : M) : ((λ n, X (succ n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) := iff.intro converges_to_seq_of_converges_to_seq_offset_succ !converges_to_seq_offset_succ section open list definition r_trans : transitive (@le ℝ _) := λ a b c, !le.trans definition r_refl : reflexive (@le ℝ _) := λ a, !le.refl theorem dec_prf_eq (P : Prop) (H1 H2 : decidable P) : H1 = H2 := begin induction H1, induction H2, reflexivity, apply absurd a a_1, induction H2, apply absurd a_1 a, reflexivity end -- there's a very ugly part of this proof. proposition bounded_of_converges_seq {X : ℕ → M} {x : M} (H : X ⟶ x in ℕ) : ∃ K : ℝ, ∀ n : ℕ, dist (X n) x ≤ K := begin cases H zero_lt_one with N HN, cases em (N = 0), existsi 1, intro n, apply le_of_lt, apply HN, rewrite a, apply zero_le, let l := map (λ n : ℕ, -dist (X n) x) (upto N), have Hnenil : l ≠ nil, from (map_ne_nil_of_ne_nil _ (upto_ne_nil_of_ne_zero a)), existsi max (-list.min (λ a b : ℝ, le a b) l Hnenil) 1, intro n, have Hsmn : ∀ m : ℕ, m < N → dist (X m) x ≤ max (-list.min (λ a b : ℝ, le a b) l Hnenil) 1, begin intro m Hm, apply le.trans, rotate 1, apply le_max_left, note Hall := min_lemma real.le_total r_trans r_refl Hnenil, have Hmem : -dist (X m) x ∈ (map (λ (n : ℕ), -dist (X n) x) (upto N)), from mem_map _ (mem_upto_of_lt Hm), note Hallm' := of_mem_of_all Hmem Hall, apply le_neg_of_le_neg, esimp, esimp at Hallm', /- have Heqs : (λ (a b : real), classical.prop_decidable (@le.{1} real real.real_has_le a b)) = (@decidable_le.{1} real (@decidable_linear_ordered_comm_group.to_decidable_linear_order.{1} real (@decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_comm_group.{1} real (@discrete_linear_ordered_field.to_decidable_linear_ordered_comm_ring.{1} real real.discrete_linear_ordered_field)))), begin apply funext, intro, apply funext, intro, apply dec_prf_eq end, rewrite -Heqs, -/ exact Hallm' end, cases em (n < N) with Elt Ege, apply Hsmn, exact Elt, apply le_of_lt, apply lt_of_lt_of_le, apply HN, apply le_of_not_gt Ege, apply le_max_right end end /- cauchy sequences -/ definition cauchy (X : ℕ → M) : Prop := ∀ ε : ℝ, ε > 0 → ∃ N, ∀ m n, m ≥ N → n ≥ N → dist (X m) (X n) < ε proposition cauchy_of_converges_seq (X : ℕ → M) [H : converges_seq X] : cauchy X := take ε, suppose ε > 0, obtain y (Hy : converges_to_seq X y), from H, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y < ε / 2), from Hy e2pos, obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y < ε / 2), from Hy e2pos, let N := max N₁ N₂ in exists.intro N (take m n, suppose m ≥ N, suppose n ≥ N, have m ≥ N₁, from le.trans !le_max_left `m ≥ N`, have n ≥ N₂, from le.trans !le_max_right `n ≥ N`, have dN₁ : dist (X m) y < ε / 2, from HN₁ `m ≥ N₁`, have dN₂ : dist (X n) y < ε / 2, from HN₂ `n ≥ N₂`, show dist (X m) (X n) < ε, from calc dist (X m) (X n) ≤ dist (X m) y + dist y (X n) : dist_triangle ... = dist (X m) y + dist (X n) y : dist_comm ... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂ ... = ε : add_halves) end metric_space_M /- convergence of a function at a point -/ section metric_space_M_N variables {M N : Type} [strucM : metric_space M] [strucN : metric_space N] include strucM strucN definition converges_to_at (f : M → N) (y : N) (x : M) := ∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ ⦃x'⦄, x' ≠ x ∧ dist x' x < δ → dist (f x') y < ε notation f `⟶` y `at` x := converges_to_at f y x attribute [class] definition converges_at (f : M → N) (x : M) := ∃ y, converges_to_at f y x noncomputable definition limit_at (f : M → N) (x : M) [H : converges_at f x] : N := some H proposition converges_to_limit_at (f : M → N) (x : M) [H : converges_at f x] : (f ⟶ limit_at f x at x) := some_spec H section omit strucN -- set_option pp.coercions true --set_option pp.all true open pnat rat section omit strucM private lemma of_rat_rat_of_pnat_eq_of_nat_nat_of_pnat (p : pnat) : of_rat (rat_of_pnat p) = of_nat (nat_of_pnat p) := rfl end theorem cnv_real_of_cnv_nat {X : ℕ → M} {c : M} (H : ∀ n : ℕ, dist (X n) c < 1 / (real.of_nat n + 1)) : ∀ ε : ℝ, ε > 0 → ∃ N : ℕ, ∀ n : ℕ, n ≥ N → dist (X n) c < ε := begin intros ε Hε, cases ex_rat_pos_lower_bound_of_pos Hε with q Hq, cases Hq with Hq1 Hq2, cases pnat_bound Hq1 with p Hp, existsi nat_of_pnat p, intros n Hn, apply lt_of_lt_of_le, apply H, apply le.trans, rotate 1, apply Hq2, have Hrat : of_rat (inv p) ≤ of_rat q, from of_rat_le_of_rat_of_le Hp, apply le.trans, rotate 1, exact Hrat, change 1 / (of_nat n + 1) ≤ of_rat ((1 : ℚ) / (rat_of_pnat p)), rewrite [of_rat_divide, of_rat_one], eapply one_div_le_one_div_of_le, krewrite -of_rat_zero, apply of_rat_lt_of_rat_of_lt, apply rat_of_pnat_is_pos, krewrite [of_rat_rat_of_pnat_eq_of_nat_nat_of_pnat, -real.of_nat_add], apply real.of_nat_le_of_nat_of_le, apply le_add_of_le_right, assumption end end theorem all_conv_seqs_of_converges_to_at {f : M → N} {c : M} {l : N} (Hconv : f ⟶ l at c) : ∀ X : ℕ → M, ((∀ n : ℕ, ((X n) ≠ c) ∧ (X ⟶ c in ℕ)) → ((λ n : ℕ, f (X n)) ⟶ l in ℕ)) := begin intros X HX, rewrite [↑converges_to_at at Hconv, ↑converges_to_seq], intros ε Hε, cases Hconv Hε with δ Hδ, cases Hδ with Hδ1 Hδ2, cases HX 0 with _ HXlim, cases HXlim Hδ1 with N1 HN1, existsi N1, intro n Hn, apply Hδ2, split, apply and.left (HX _), exact HN1 Hn end theorem converges_to_at_of_all_conv_seqs {f : M → N} (c : M) (l : N) (Hseq : ∀ X : ℕ → M, ((∀ n : ℕ, ((X n) ≠ c) ∧ (X ⟶ c in ℕ)) → ((λ n : ℕ, f (X n)) ⟶ l in ℕ))) : f ⟶ l at c := by_contradiction (assume Hnot : ¬ (f ⟶ l at c), obtain ε Hε, from exists_not_of_not_forall Hnot, let Hε' := and_not_of_not_implies Hε in obtain (H1 : ε > 0) H2, from Hε', have H3 : ∀ δ : ℝ, (δ > 0 → ∃ x' : M, x' ≠ c ∧ dist x' c < δ ∧ dist (f x') l ≥ ε), begin -- tedious!! intros δ Hδ, note Hε'' := forall_not_of_not_exists H2, note H4 := forall_not_of_not_exists H2 δ, have ¬ (∀ x' : M, x' ≠ c ∧ dist x' c < δ → dist (f x') l < ε), from λ H', H4 (and.intro Hδ H'), note H5 := exists_not_of_not_forall this, cases H5 with x' Hx', existsi x', note H6 := and_not_of_not_implies Hx', rewrite and.assoc at H6, cases H6, split, assumption, cases a_1, split, assumption, apply le_of_not_gt, assumption end, let S : ℕ → M → Prop := λ n x, 0 < dist x c ∧ dist x c < 1 / (of_nat n + 1) ∧ dist (f x) l ≥ ε in have HS : ∀ n : ℕ, ∃ m : M, S n m, begin intro k, have Hpos : 0 < of_nat k + 1, from of_nat_succ_pos k, cases H3 (1 / (k + 1)) (one_div_pos_of_pos Hpos) with x' Hx', cases Hx' with Hne Hx', cases Hx' with Hdistl Hdistg, existsi x', esimp, split, apply dist_pos_of_ne, assumption, split, repeat assumption end, let X : ℕ → M := λ n, some (HS n) in have H4 : ∀ n : ℕ, ((X n) ≠ c) ∧ (X ⟶ c in ℕ), from (take n, and.intro (begin note Hspec := some_spec (HS n), esimp, esimp at Hspec, cases Hspec, apply ne_of_dist_pos, assumption end) (begin apply cnv_real_of_cnv_nat, intro m, note Hspec := some_spec (HS m), esimp, esimp at Hspec, cases Hspec with Hspec1 Hspec2, cases Hspec2, assumption end)), have H5 : (λ n : ℕ, f (X n)) ⟶ l in ℕ, from Hseq X H4, begin note H6 := H5 H1, cases H6 with Q HQ, note HQ' := HQ !le.refl, esimp at HQ', apply absurd HQ', apply not_lt_of_ge, note H7 := some_spec (HS Q), esimp at H7, cases H7 with H71 H72, cases H72, assumption end) end metric_space_M_N section topology /- A metric space is a topological space. -/ open set prod topology variables {V : Type} [Vmet : metric_space V] include Vmet definition open_ball (x : V) (ε : ℝ) := {y ∈ univ | dist x y < ε} theorem open_ball_empty_of_nonpos (x : V) {ε : ℝ} (Hε : ε ≤ 0) : open_ball x ε = ∅ := begin apply eq_empty_of_forall_not_mem, intro y Hy, note Hlt := and.right Hy, apply not_lt_of_ge (dist_nonneg x y), apply lt_of_lt_of_le Hlt Hε end theorem radius_pos_of_nonempty {x : V} {ε : ℝ} {u : V} (Hu : u ∈ open_ball x ε) : ε > 0 := begin apply lt_of_not_ge, intro Hge, note Hop := open_ball_empty_of_nonpos x Hge, rewrite Hop at Hu, apply not_mem_empty _ Hu end theorem mem_open_ball (x : V) {ε : ℝ} (H : ε > 0) : x ∈ open_ball x ε := suffices x ∈ univ ∧ dist x x < ε, from this, and.intro !mem_univ (by rewrite dist_self; assumption) definition closed_ball (x : V) (ε : ℝ) := {y ∈ univ | dist x y ≤ ε} theorem closed_ball_eq_compl (x : V) (ε : ℝ) : closed_ball x ε = -{y ∈ univ | dist x y > ε} := begin apply ext, intro y, apply iff.intro, intro Hx, apply mem_compl, intro Hxmem, cases Hxmem with _ Hgt, cases Hx with _ Hle, apply not_le_of_gt Hgt Hle, intro Hx, note Hx' := not_mem_of_mem_compl Hx, split, apply mem_univ, apply le_of_not_gt, intro Hgt, apply Hx', split, apply mem_univ, assumption end omit Vmet definition open_sets_basis (V : Type) [metric_space V] := image (λ pair : V × ℝ, open_ball (pr1 pair) (pr2 pair)) univ attribute [instance] definition metric_topology (V : Type) [metric_space V] : topology V := topology.generated_by (open_sets_basis V) include Vmet theorem open_ball_mem_open_sets_basis (x : V) (ε : ℝ) : (open_ball x ε) ∈ (open_sets_basis V) := mem_image !mem_univ rfl theorem open_ball_open (x : V) (ε : ℝ) : Open (open_ball x ε) := by apply generators_mem_topology_generated_by; apply open_ball_mem_open_sets_basis theorem closed_ball_closed (x : V) {ε : ℝ} (H : ε > 0) : closed (closed_ball x ε) := begin apply iff.mpr !closed_iff_Open_compl, rewrite closed_ball_eq_compl, rewrite compl_compl, apply Open_of_forall_exists_Open_nbhd, intro y Hy, cases Hy with _ Hxy, existsi open_ball y (dist x y - ε), split, apply open_ball_open, split, apply mem_open_ball, apply sub_pos_of_lt Hxy, intros y' Hy', cases Hy' with _ Hxy'd, rewrite dist_comm at Hxy'd, split, apply mem_univ, apply lt_of_not_ge, intro Hxy', apply not_lt_self (dist x y), exact calc dist x y ≤ dist x y' + dist y' y : dist_triangle ... ≤ ε + dist y' y : add_le_add_right Hxy' ... < ε + (dist x y - ε) : add_lt_add_left Hxy'd ... = dist x y : by rewrite [add.comm, sub_add_cancel] end private theorem not_mem_open_basis_of_boundary_pt {s : set V} (a : s ∈ open_sets_basis V) {x : V} (Hbd : ∀ ε : ℝ, ε > 0 → ∃ v : V, v ∉ s ∧ dist x v < ε) : ¬ x ∈ s := begin intro HxU, cases a with pr Hpr, cases pr with y r, cases Hpr with _ Hs, rewrite -Hs at HxU, have H : dist y x < r, from and.right HxU, cases Hbd _ (sub_pos_of_lt H) with v Hv, cases Hv with Hv Hvdist, apply Hv, rewrite -Hs, apply and.intro, apply mem_univ, apply lt_of_le_of_lt, apply dist_triangle, exact x, esimp, exact calc dist y x + dist x v < dist y x + (r - dist y x) : add_lt_add_left Hvdist ... = r : by rewrite [add.comm, sub_add_cancel] end private theorem not_mem_intersect_of_boundary_pt {s t : set V} (a : Open s) (a_1 : Open t) {x : V} (v_0 : (x ∈ s → ¬ (∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ s ∧ dist x v < ε)))) (v_1 : (x ∈ t → ¬ (∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ t ∧ dist x v < ε)))) (Hbd : ∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ s ∩ t ∧ dist x v < ε)) : ¬ (x ∈ s ∩ t) := begin intro HxU, have Hxs : x ∈ s, from mem_of_mem_inter_left HxU, have Hxt : x ∈ t, from mem_of_mem_inter_right HxU, note Hsih := exists_not_of_not_forall (v_0 Hxs), note Htih := exists_not_of_not_forall (v_1 Hxt), cases Hsih with ε1 Hε1, cases Htih with ε2 Hε2, note Hε1' := and_not_of_not_implies Hε1, note Hε2' := and_not_of_not_implies Hε2, cases Hε1' with Hε1p Hε1', cases Hε2' with Hε2p Hε2', note Hε1'' := forall_not_of_not_exists Hε1', note Hε2'' := forall_not_of_not_exists Hε2', have Hmin : min ε1 ε2 > 0, from lt_min Hε1p Hε2p, cases Hbd _ Hmin with v Hv, cases Hv with Hvint Hvdist, note Hε1v := Hε1'' v, note Hε2v := Hε2'' v, cases em (v ∉ s) with Hnm Hmem, apply Hε1v, split, exact Hnm, apply lt_of_lt_of_le Hvdist, apply min_le_left, apply Hε2v, have Hmem' : v ∈ s, from not_not_elim Hmem, note Hnm := not_mem_of_mem_of_not_mem_inter_left Hmem' Hvint, split, exact Hnm, apply lt_of_lt_of_le Hvdist, apply min_le_right end private theorem not_mem_sUnion_of_boundary_pt {S : set (set V)} (a : ∀₀ s ∈ S, Open s) {x : V} (v_0 : ∀ ⦃x_1 : set V⦄, x_1 ∈ S → x ∈ x_1 → ¬ (∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ x_1 ∧ dist x v < ε))) (Hbd : ∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ ⋃₀ S ∧ dist x v < ε)) : ¬ x ∈ ⋃₀ S := begin intro HxU, have Hex : ∃₀ s ∈ S, x ∈ s, from HxU, cases Hex with s Hs, cases Hs with Hs Hxs, cases exists_not_of_not_forall (v_0 Hs Hxs) with ε Hε, cases and_not_of_not_implies Hε with Hεp Hv, cases Hbd _ Hεp with v Hv', cases Hv' with Hvnm Hdist, apply Hv, existsi v, split, apply not_mem_of_not_mem_sUnion Hvnm Hs, exact Hdist end /- this should be doable by showing that the open-ball boundary definition is equivalent to topology.on_boundary, and applying topology.not_open_of_on_boundary. But the induction hypotheses don't work out nicely. -/ theorem not_open_of_ex_boundary_pt {U : set V} {x : V} (HxU : x ∈ U) (Hbd : ∀ ε : ℝ, ε > 0 → ∃ v : V, v ∉ U ∧ dist x v < ε) : ¬ Open U := begin intro HUopen, induction HUopen, {apply not_mem_open_basis_of_boundary_pt a Hbd HxU}, {cases Hbd 1 zero_lt_one with v Hv, cases Hv with Hv _, exact Hv !mem_univ}, {apply not_mem_intersect_of_boundary_pt a a_1 v_0 v_1 Hbd HxU}, {apply not_mem_sUnion_of_boundary_pt a v_0 Hbd HxU} end theorem ex_Open_ball_subset_of_Open_of_nonempty {U : set V} (HU : Open U) {x : V} (Hx : x ∈ U) : ∃ (r : ℝ), r > 0 ∧ open_ball x r ⊆ U := begin let balloon := {r ∈ univ | r > 0 ∧ open_ball x r ⊆ U}, cases em (balloon = ∅), have H : ∀ r : ℝ, r > 0 → ∃ v : V, v ∉ U ∧ dist x v < r, begin intro r Hr, note Hor := not_or_not_of_not_and (forall_not_of_sep_empty a (mem_univ r)), note Hor' := or.neg_resolve_left Hor Hr, apply exists_of_not_forall_not, intro Hall, apply Hor', intro y Hy, cases not_or_not_of_not_and (Hall y) with Hmem Hge, apply not_not_elim Hmem, apply absurd (and.right Hy) Hge end, apply absurd HU, apply not_open_of_ex_boundary_pt Hx H, cases exists_mem_of_ne_empty a with r Hr, cases Hr with _ Hr, cases Hr with Hrpos HxrU, existsi r, split, repeat assumption end end topology section continuity variables {M N : Type} [Hm : metric_space M] [Hn : metric_space N] include Hm Hn open topology set /- continuity at a point -/ -- the ε - δ definition of continuity is equivalent to the topological definition theorem continuous_at_intro {f : M → N} {x : M} (H : ∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ ⦃x'⦄, dist x' x < δ → dist (f x') (f x) < ε) : continuous_at f x := begin rewrite ↑continuous_at, intros U HfU Uopen, cases ex_Open_ball_subset_of_Open_of_nonempty Uopen HfU with r Hr, cases Hr with Hr HUr, cases H Hr with δ Hδ, cases Hδ with Hδ Hx'δ, existsi open_ball x δ, split, apply mem_open_ball, exact Hδ, split, apply open_ball_open, intro y Hy, apply HUr, cases Hy with y' Hy', cases Hy' with Hy' Hfy', cases Hy' with _ Hy', rewrite dist_comm at Hy', note Hy'' := Hx'δ Hy', apply and.intro !mem_univ, rewrite [-Hfy', dist_comm], exact Hy'' end theorem continuous_at_elim {f : M → N} {x : M} (Hfx : continuous_at f x) : ∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ ⦃x'⦄, dist x' x < δ → dist (f x') (f x) < ε := begin intros ε Hε, rewrite [↑continuous_at at Hfx], cases Hfx (open_ball (f x) ε) (mem_open_ball _ Hε) !open_ball_open with V HV, cases HV with HVx HV, cases HV with HV HVf, cases ex_Open_ball_subset_of_Open_of_nonempty HV HVx with δ Hδ, cases Hδ with Hδ Hδx, existsi δ, split, exact Hδ, intro x' Hx', rewrite dist_comm, apply and.right, apply HVf, existsi x', split, apply Hδx, apply and.intro !mem_univ, rewrite dist_comm, apply Hx', apply rfl end theorem continuous_at_of_converges_to_at {f : M → N} {x : M} (Hf : f ⟶ f x at x) : continuous_at f x := continuous_at_intro (take ε, suppose ε > 0, obtain δ Hδ, from Hf this, exists.intro δ (and.intro (and.left Hδ) (take x', suppose dist x' x < δ, if Heq : x' = x then by rewrite [-Heq, dist_self]; assumption else (suffices dist x' x < δ, from and.right Hδ x' (and.intro Heq this), this)))) theorem converges_to_at_of_continuous_at {f : M → N} {x : M} (Hf : continuous_at f x) : f ⟶ f x at x := take ε, suppose ε > 0, obtain δ Hδ, from continuous_at_elim Hf this, exists.intro δ (and.intro (and.left Hδ) (take x', assume H : x' ≠ x ∧ dist x' x < δ, show dist (f x') (f x) < ε, from and.right Hδ x' (and.right H))) definition continuous (f : M → N) : Prop := ∀ x, continuous_at f x attribute [instance] theorem converges_seq_comp_of_converges_seq_of_cts (X : ℕ → M) [HX : converges_seq X] {f : M → N} (Hf : continuous f) : converges_seq (λ n, f (X n)) := begin cases HX with xlim Hxlim, existsi f xlim, rewrite ↑converges_to_seq at *, intros ε Hε, let Hcont := (continuous_at_elim (Hf xlim)) Hε, cases Hcont with δ Hδ, cases Hxlim (and.left Hδ) with B HB, existsi B, intro n Hn, apply and.right Hδ, apply HB Hn end omit Hn theorem id_continuous : continuous (λ x : M, x) := begin intros x, apply continuous_at_intro, intro ε Hε, existsi ε, split, assumption, intros, assumption end end continuity end analysis /- complete metric spaces -/ structure complete_metric_space [class] (M : Type) extends metricM : metric_space M : Type := (complete : ∀ X, @analysis.cauchy M metricM X → @analysis.converges_seq M metricM X) namespace analysis proposition complete (M : Type) [cmM : complete_metric_space M] {X : ℕ → M} (H : cauchy X) : converges_seq X := complete_metric_space.complete X H end analysis /- the reals form a metric space -/ attribute [instance] noncomputable definition metric_space_real : metric_space ℝ := ⦃ metric_space, dist := λ x y, abs (x - y), dist_self := λ x, abstract by rewrite [sub_self, abs_zero] end, eq_of_dist_eq_zero := λ x y, eq_of_abs_sub_eq_zero, dist_comm := abs_sub, dist_triangle := abs_sub_le ⦄
ab13cb26e657007c98a77d3015467ae7de139495
5b273b8c05e2f73fb74340ce100ce261900a98cd
/binomial.lean
9ca96d81df4b53652d6c6cf4760213e578e68f56
[]
no_license
ChrisHughes24/leanstuff1
2eba44bc48da6e544e07495b41e1703f81dc1c24
cbcd788b8b1d07b20b2fff4482c870077a13d1c0
refs/heads/master
1,631,670,333,297
1,527,093,981,000
1,527,093,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,315
lean
import algebra.big_operators data.real.cau_seq tactic.ring algebra.archimedean data.nat.choose analysis.limits open nat is_absolute_value variables {α : Type*} {β : Type*} (f g : ℕ → α) (n m : ℕ) local infix `^` := monoid.pow local notation f ` ∑ ` : 90 n : 90 := finset.sum (finset.range n) f section sum_range variable [add_comm_monoid α] lemma sum_range_succ : f ∑ succ n = f n + f ∑ n := have h : n ∉ finset.range n := by rw finset.mem_range; exact lt_irrefl _, by rw [finset.range_succ, finset.sum_insert h] lemma sum_range_succ' : ∀ n : ℕ, f ∑ succ n = (λ m, f (succ m)) ∑ n + f 0 := | 0 := by simp | (succ n) := by rw [sum_range_succ (λ m, f (succ m)), add_assoc, ← sum_range_succ']; exact sum_range_succ _ _ lemma sum_range_comm : f ∑ n = (λ m, f (n - (succ m))) ∑ n := begin induction n with n hi, { simp }, { rw [sum_range_succ, sum_range_succ', hi, succ_sub_one, add_comm], simp [succ_sub_succ] } end end sum_range theorem binomial [comm_semiring α] (x y : α) : ∀ n : ℕ, (x + y)^n = (λ m, x^m * y^(n - m) * choose n m) ∑ succ n | 0 := by simp | (succ n) := begin rw [_root_.pow_succ, binomial, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ', sum_range_succ, sum_range_succ', add_assoc, ← add_assoc (_ ∑ n), ← finset.sum_add_distrib], have h₁ : x * (x^n * y^(n - n) * choose n n) = x^succ n * y^(succ n - succ n) * choose (succ n) (succ n) := by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0 := by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₃ : (λ m, x * (x^m * y^(n - m) * choose n m) + y * (x^succ m * y^(n - succ m) * choose n (succ m))) ∑ n = (λ m, x^succ m * y^(succ n - succ m) * ↑(choose (succ n) (succ m))) ∑ n := finset.sum_congr rfl begin assume m hm, rw finset.mem_range at hm, rw [← mul_assoc y, ← mul_assoc y, mul_right_comm y, ← _root_.pow_succ, add_one, ← succ_sub hm], simp [succ_sub_succ, _root_.pow_succ, choose_succ_succ, mul_add, mul_comm, mul_assoc, mul_left_comm] end, rw [h₁, h₂, h₃] end
f3642faa0a50f8ed60396851f7552ea8895e346a
9a2260f3b7b64ae9c50bf326fdb0387f5ac64683
/src/NITRO/Elements.lean
2ec6067acbae7eb04346633c76caf1d496a3a7b1
[ "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
o89/nitro
e8e1c7f3e7baeb7a659f899c605d37b1d3e553a6
c62a67398a89d6e6a2e9da62350adaf5f17cfda9
refs/heads/master
1,670,068,174,264
1,669,086,407,000
1,669,086,407,000
204,147,098
3
5
null
null
null
null
UTF-8
Lean
false
false
245
lean
import NITRO.Tags variable {α : Type} def div := @Elem.tag α "div" def title := @Elem.tag α "title" [] def idAttr := Attr.str "id" def classAttr := Attr.list "class" def br := @Elem.unpaired α "br" [] def hr := @Elem.unpaired α "hr" []
fcfe8ae7bd0af97076f4ff6ec2487f6e6864a6bf
63abd62053d479eae5abf4951554e1064a4c45b4
/src/linear_algebra/direct_sum/tensor_product.lean
361936a9ca50cf3040d52f3ba963798f637a1fc7
[ "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
2,277
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import linear_algebra.tensor_product import linear_algebra.direct_sum_module section ring namespace tensor_product open_locale tensor_product open_locale direct_sum open linear_map variables (R : Type*) [comm_ring R] variables (ι₁ : Type*) (ι₂ : Type*) variables [decidable_eq ι₁] [decidable_eq ι₂] variables (M₁ : ι₁ → Type*) (M₂ : ι₂ → Type*) variables [Π i₁, add_comm_group (M₁ i₁)] [Π i₂, add_comm_group (M₂ i₂)] variables [Π i₁, module R (M₁ i₁)] [Π i₂, module R (M₂ i₂)] /-- The linear equivalence `(⨁ i₁, M₁ i₁) ⊗ (⨁ i₂, M₂ i₂) ≃ (⨁ i₁, ⨁ i₂, M₁ i₁ ⊗ M₂ i₂)`, i.e. "tensor product distributes over direct sum". -/ def direct_sum : (⨁ i₁, M₁ i₁) ⊗[R] (⨁ i₂, M₂ i₂) ≃ₗ[R] (⨁ (i : ι₁ × ι₂), M₁ i.1 ⊗[R] M₂ i.2) := begin refine linear_equiv.of_linear (lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂, flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂)) (direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _)) (linear_map.ext $ direct_sum.to_module.ext _ $ λ i, mk_compr₂_inj $ linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _) (mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext _ $ λ i₁, linear_map.ext $ λ x₁, linear_map.ext $ direct_sum.to_module.ext _ $ λ i₂, linear_map.ext $ λ x₂, _), repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|> rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|> rw curry_apply }, cases i; refl end @[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) : direct_sum R ι₁ ι₂ M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) = direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) := by simp [direct_sum] end tensor_product end ring
e0e3cc58e0d75905fdc89fe45135dfa898931aa1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/cc_value.lean
e053c0bd65763554ea80b3414f1223a53fd29e71
[ "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
412
lean
open tactic example (a b : nat) : a = 1 → b = 2 → a = b → false := by cc example (a b c : int) : a = 1 → c = -2 → a = b → c = b → false := by cc example (a b : char) : a = 'h' → b = 'w' → a = b → false := by cc example (a b : string) : a = "hello" → b = "world" → a = b → false := by cc example (a b c : string) : a = c → a = "hello" → c = "world" → c = b → false := by cc
512ff287fab40317d9eed9b1a3a6fcb1e1591d04
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/rbmap/default.lean
c4bfe039c17e4aac7a0ea98c38787254b59968dd
[ "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
15,049
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree import data.rbmap.basic universes u v namespace rbmap variables {α : Type u} {β : Type v} {lt : α → α → Prop} /- Auxiliary instances -/ private def rbmap_lt_is_swo {α : Type u} {β : Type v} {lt : α → α → Prop} [is_strict_weak_order α lt] : is_strict_weak_order (α × β) (rbmap_lt lt) := { irrefl := λ _, irrefl_of lt _, trans := λ _ _ _ h₁ h₂, trans_of lt h₁ h₂, incomp_trans := λ _ _ _ h₁ h₂, incomp_trans_of lt h₁ h₂ } private def rbmap_lt_dec {α : Type u} {β : Type v} {lt : α → α → Prop} [h : decidable_rel lt] : decidable_rel (@rbmap_lt α β lt) := λ a b, h a.1 b.1 local attribute [instance] rbmap_lt_is_swo rbmap_lt_dec /- Helper lemmas for reusing rbtree results. -/ private lemma to_rbtree_mem {k : α} {m : rbmap α β lt} : k ∈ m → ∃ v : β, rbtree.mem (k, v) m := begin cases m with n p; cases n; intros h, { exact false.elim h }, all_goals { existsi n_val.2, exact h } end private lemma eqv_entries_of_eqv_keys {k₁ k₂ : α} (v₁ v₂ : β) : k₁ ≈[lt] k₂ → (k₁, v₁) ≈[rbmap_lt lt] (k₂, v₂) := id private lemma eqv_keys_of_eqv_entries {k₁ k₂ : α} {v₁ v₂ : β} : (k₁, v₁) ≈[rbmap_lt lt] (k₂, v₂) → k₁ ≈[lt] k₂ := id private lemma eqv_entries [is_irrefl α lt] (k : α) (v₁ v₂ : β) : (k, v₁) ≈[rbmap_lt lt] (k, v₂) := and.intro (irrefl_of lt k) (irrefl_of lt k) private lemma to_rbmap_mem [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : rbtree.mem (k, v) m → k ∈ m := begin cases m with n p; cases n; intros h, { exact false.elim h }, { simp [has_mem.mem, rbmap.mem], exact @rbtree.mem_of_mem_of_eqv _ _ _ ⟨rbnode.red_node n_lchild n_val n_rchild, p⟩ _ _ h (eqv_entries _ _ _) }, { simp [has_mem.mem, rbmap.mem], exact @rbtree.mem_of_mem_of_eqv _ _ _ ⟨rbnode.black_node n_lchild n_val n_rchild, p⟩ _ _ h (eqv_entries _ _ _) } end private lemma to_rbtree_mem' [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} (v : β) : k ∈ m → rbtree.mem (k, v) m := begin intro h, cases to_rbtree_mem h with v' hm, apply rbtree.mem_of_mem_of_eqv hm, apply eqv_entries end lemma eq_some_of_to_value_eq_some {e : option (α × β)} {v : β} : to_value e = some v → ∃ k, e = some (k, v) := begin cases e with val; simp [to_value, false_implies_iff], { cases val, simp } end lemma eq_none_of_to_value_eq_none {e : option (α × β)} : to_value e = none → e = none := by cases e; simp [to_value, false_implies_iff] /- Lemmas -/ lemma not_mem_mk_rbmap : ∀ (k : α), k ∉ mk_rbmap α β lt := by simp [has_mem.mem, mk_rbmap, mk_rbtree, rbmap.mem] lemma not_mem_of_empty {m : rbmap α β lt} (k : α) : m.empty = tt → k ∉ m := by cases m with n p; cases n; simp [has_mem.mem, mk_rbmap, mk_rbtree, rbmap.mem, rbmap.empty, rbtree.empty, false_implies_iff] lemma mem_of_mem_of_eqv [is_strict_weak_order α lt] {m : rbmap α β lt} {k₁ k₂ : α} : k₁ ∈ m → k₁ ≈[lt] k₂ → k₂ ∈ m := begin intros h₁ h₂, have h₁ := to_rbtree_mem h₁, cases h₁ with v h₁, exact to_rbmap_mem (rbtree.mem_of_mem_of_eqv h₁ (eqv_entries_of_eqv_keys v v h₂)) end section decidable variables [decidable_rel lt] lemma not_mem_of_find_entry_none [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} : m.find_entry k = none → k ∉ m := begin cases m with t p, cases t; simp [find_entry], { intros, simp [has_mem.mem, rbmap.mem] }, all_goals { intro h, exact rbtree.not_mem_of_find_none h, } end lemma not_mem_of_find_none [is_strict_weak_order α lt] {k : α} {m : rbmap α β lt} : m.find k = none → k ∉ m := begin simp [find], intro h, have := eq_none_of_to_value_eq_none h, exact not_mem_of_find_entry_none this end lemma mem_of_find_entry_some [is_strict_weak_order α lt] {k₁ : α} {e : α × β} {m : rbmap α β lt} : m.find_entry k₁ = some e → k₁ ∈ m := begin cases m with t p, cases t; simp [find_entry, false_implies_iff], all_goals { intro h, exact rbtree.mem_of_find_some h } end lemma mem_of_find_some [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.find k = some v → k ∈ m := begin simp [find], intro h, have := eq_some_of_to_value_eq_some h, cases this with _ he, exact mem_of_find_entry_some he end lemma find_entry_eq_find_entry_of_eqv [is_strict_weak_order α lt] {m : rbmap α β lt} {k₁ k₂ : α} : k₁ ≈[lt] k₂ → m.find_entry k₁ = m.find_entry k₂ := begin intro h, cases m with t p, cases t; simp [find_entry], all_goals { apply rbtree.find_eq_find_of_eqv, apply eqv_entries_of_eqv_keys, assumption } end lemma find_eq_find_of_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) : k₁ ≈[lt] k₂ → m.find k₁ = m.find k₂ := begin intro h, simp [find], apply congr_arg, apply find_entry_eq_find_entry_of_eqv, assumption end lemma find_entry_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ (∃ e, m.find_entry k = some e ∧ k ≈[lt] e.1) := begin apply iff.intro; cases m with t p, { intro h, have h := to_rbtree_mem h, cases h with v h₁, have hex := iff.mp (rbtree.find_correct _ _) h₁, cases hex with e h₂, existsi e, cases t; simp [find_entry] at ⊢ h₂, { simp [rbtree.find, rbnode.find] at h₂, cases h₂ }, { cases h₂ with h₂₁ h₂₂, split, { have := rbtree.find_eq_find_of_eqv ⟨rbnode.red_node t_lchild t_val t_rchild, p⟩ (eqv_entries k v t_val.2), rw [←this], exact h₂₁ }, { cases e, apply eqv_keys_of_eqv_entries h₂₂ } }, { cases h₂ with h₂₁ h₂₂, split, { have := rbtree.find_eq_find_of_eqv ⟨rbnode.black_node t_lchild t_val t_rchild, p⟩ (eqv_entries k v t_val.2), rw [←this], exact h₂₁ }, { cases e, apply eqv_keys_of_eqv_entries h₂₂ } } }, { intro h, cases h with e h, cases h with h₁ h₂, cases t; simp [find_entry] at h₁, { contradiction }, all_goals { exact to_rbmap_mem (rbtree.mem_of_find_some h₁) } } end lemma eqv_of_find_entry_some [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : m.find_entry k₁ = some (k₂, v) → k₁ ≈[lt] k₂ := begin cases m with t p, cases t; simp [find_entry, false_implies_iff], all_goals { intro h, exact eqv_keys_of_eqv_entries (rbtree.eqv_of_find_some h) } end lemma eq_of_find_entry_some [is_strict_total_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : m.find_entry k₁ = some (k₂, v) → k₁ = k₂ := λ h, suffices k₁ ≈[lt] k₂, from eq_of_eqv_lt this, eqv_of_find_entry_some h lemma find_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ ∃ v, m.find k = some v := begin apply iff.intro, { intro h, have := iff.mp (find_entry_correct k m) h, cases this with e h, cases h with h₁ h₂, existsi e.2, simp [find, h₁, to_value] }, { intro h, cases h with v h, simp [find] at h, have h := eq_some_of_to_value_eq_some h, cases h with k' h, have heqv := eqv_of_find_entry_some h, exact iff.mpr (find_entry_correct k m) ⟨(k', v), ⟨h, heqv⟩⟩ } end lemma constains_correct [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) : k ∈ m ↔ m.contains k = tt := begin apply iff.intro, { intro h, have h := iff.mp (find_entry_correct k m) h, cases h with e h, cases h with h₁ h₂, simp [contains, h₁, option.is_some] }, { simp [contains], intro h, generalize he : find_entry m k = e, cases e, { simp [he, option.is_some] at h, contradiction }, { exact mem_of_find_entry_some he } } end lemma mem_insert_of_incomp [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : (¬ lt k₁ k₂ ∧ ¬ lt k₂ k₁) → k₁ ∈ m.insert k₂ v := λ h, to_rbmap_mem (rbtree.mem_insert_of_incomp m (eqv_entries_of_eqv_keys v v h)) lemma mem_insert [is_strict_weak_order α lt] (k : α) (m : rbmap α β lt) (v : β) : k ∈ m.insert k v := to_rbmap_mem (rbtree.mem_insert (k, v) m) lemma mem_insert_of_equiv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≈[lt] k₂ → k₁ ∈ m.insert k₂ v := mem_insert_of_incomp m v lemma mem_insert_of_mem [is_strict_weak_order α lt] {k₁ : α} {m : rbmap α β lt} (k₂ : α) (v : β) : k₁ ∈ m → k₁ ∈ m.insert k₂ v := λ h, to_rbmap_mem (rbtree.mem_insert_of_mem (k₂, v) (to_rbtree_mem' v h)) lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → k₁ ≈[lt] k₂ ∨ k₁ ∈ m := λ h, or.elim (rbtree.equiv_or_mem_of_mem_insert (to_rbtree_mem' v h)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr (to_rbmap_mem h)) lemma incomp_or_mem_of_mem_ins [is_strict_weak_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → (¬ lt k₁ k₂ ∧ ¬ lt k₂ k₁) ∨ k₁ ∈ m := equiv_or_mem_of_mem_insert lemma eq_or_mem_of_mem_ins [is_strict_total_order α lt] {k₁ k₂ : α} {v : β} {m : rbmap α β lt} : k₁ ∈ m.insert k₂ v → k₁ = k₂ ∨ k₁ ∈ m := λ h, suffices k₁ ≈[lt] k₂ ∨ k₁ ∈ m, by simp [eqv_lt_iff_eq] at this; assumption, incomp_or_mem_of_mem_ins h lemma find_entry_insert_of_eqv [is_strict_weak_order α lt] (m : rbmap α β lt) {k₁ k₂ : α} (v : β) : k₁ ≈[lt] k₂ → (m.insert k₁ v).find_entry k₂ = some (k₁, v) := begin intro h, generalize h₁ : m.insert k₁ v = m', cases m' with t p, cases t, { have := mem_insert k₁ m v, rw [h₁] at this, apply absurd this, apply not_mem_mk_rbmap }, all_goals { simp [find_entry], rw [←h₁, insert], apply rbtree.find_insert_of_eqv, apply eqv_entries_of_eqv_keys _ _ h } end lemma find_entry_insert [is_strict_weak_order α lt] (m : rbmap α β lt) (k : α) (v : β) : (m.insert k v).find_entry k = some (k, v) := find_entry_insert_of_eqv m v (refl k) lemma find_insert_of_eqv [is_strict_weak_order α lt] (m : rbmap α β lt) {k₁ k₂ : α} (v : β) : k₁ ≈[lt] k₂ → (m.insert k₁ v).find k₂ = some v := begin intro h, have := find_entry_insert_of_eqv m v h, simp [find, this, to_value] end lemma find_insert [is_strict_weak_order α lt] (m : rbmap α β lt) (k : α) (v : β) : (m.insert k v).find k = some v := find_insert_of_eqv m v (refl k) lemma find_entry_insert_of_disj [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro h, have h' : ∀ {v₁ v₂ : β}, (rbmap_lt lt) (k₁, v₁) (k₂, v₂) ∨ (rbmap_lt lt) (k₂, v₂) (k₁, v₁) := λ _ _, h, generalize h₁ : m = m₁, generalize h₂ : insert m₁ k₁ v = m₂, rw [←h₁] at h₂ ⊢, rw [←h₂], cases m₁ with t₁ p₁; cases t₁; cases m₂ with t₂ p₂; cases t₂, { rw [h₂, h₁] }, iterate 2 { rw [h₂], conv { to_lhs, simp [find_entry] }, rw [←h₂, insert, rbtree.find_insert_of_disj _ h', h₁], refl }, any_goals { simp [insert] at h₂, exact absurd h₂ (rbtree.insert_ne_mk_rbtree m (k₁, v)) }, any_goals { rw [h₂, h₁], simp [find_entry], rw [←h₂, ←h₁, insert, rbtree.find_insert_of_disj _ h'], apply rbtree.find_eq_find_of_eqv, apply eqv_entries } end lemma find_entry_insert_of_not_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : ¬ k₁ ≈[lt] k₂ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro hn, have he : lt k₁ k₂ ∨ lt k₂ k₁, { simp [strict_weak_order.equiv, decidable.not_and_iff_or_not, decidable.not_not_iff] at hn, assumption }, apply find_entry_insert_of_disj _ _ he end lemma find_entry_insert_of_ne [is_strict_total_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≠ k₂ → (m.insert k₁ v).find_entry k₂ = m.find_entry k₂ := begin intro h, have : ¬ k₁ ≈[lt] k₂ := λ h', h (eq_of_eqv_lt h'), apply find_entry_insert_of_not_eqv _ _ this end lemma find_insert_of_disj [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_disj m v h, simp [find, this] end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : ¬ k₁ ≈[lt] k₂ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_not_eqv m v h, simp [find, this] end lemma find_insert_of_ne [is_strict_total_order α lt] {k₁ k₂ : α} (m : rbmap α β lt) (v : β) : k₁ ≠ k₂ → (m.insert k₁ v).find k₂ = m.find k₂ := begin intro h, have := find_entry_insert_of_ne m v h, simp [find, this] end end decidable lemma mem_of_min_eq [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → k ∈ m := λ h, to_rbmap_mem (rbtree.mem_of_min_eq h) lemma mem_of_max_eq [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → k ∈ m := λ h, to_rbmap_mem (rbtree.mem_of_max_eq h) lemma eq_leaf_of_min_eq_none {m : rbmap α β lt} : m.min = none → m = mk_rbmap α β lt := rbtree.eq_leaf_of_min_eq_none lemma eq_leaf_of_max_eq_none {m : rbmap α β lt} : m.max = none → m = mk_rbmap α β lt := rbtree.eq_leaf_of_max_eq_none lemma min_is_minimal [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → ∀ {k'}, k' ∈ m → k ≈[lt] k' ∨ lt k k' := λ h k' hm, or.elim (rbtree.min_is_minimal h (to_rbtree_mem' v hm)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr h) lemma max_is_maximal [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → ∀ {k'}, k' ∈ m → k ≈[lt] k' ∨ lt k' k := λ h k' hm, or.elim (rbtree.max_is_maximal h (to_rbtree_mem' v hm)) (λ h, or.inl (eqv_keys_of_eqv_entries h)) (λ h, or.inr h) lemma min_is_minimal_of_total [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.min = some (k, v) → ∀ {k'}, k' ∈ m → k = k' ∨ lt k k' := λ h k' hm, match min_is_minimal h hm with | or.inl h := or.inl (eq_of_eqv_lt h) | or.inr h := or.inr h end lemma max_is_maximal_of_total [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β lt} : m.max = some (k, v) → ∀ {k'}, k' ∈ m → k = k' ∨ lt k' k := λ h k' hm, match max_is_maximal h hm with | or.inl h := or.inl (eq_of_eqv_lt h) | or.inr h := or.inr h end end rbmap
804705a59fcf03fd7a60b79492c9c93a9f4eac11
b561a44b48979a98df50ade0789a21c79ee31288
/src/Init/Data/Array/Basic.lean
86765aa384f5599ff495b805c904b9a0536d4289
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,536
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 -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Util universe u v w namespace Array variable {α : Type u} @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { data := List.replicate n v } @[simp] theorem size_mkArray (n : Nat) (v : α) : (mkArray n v).size = n := List.length_replicate .. instance : EmptyCollection (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) where default := Array.empty def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def back? (a : Array α) : Option α := a.get? (a.size - 1) -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ @[simp] theorem size_set (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := List.length_set .. @[simp] theorem size_push (a : Array α) (v : α) : (push a v).size = a.size + 1 := List.length_concat .. /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i let v₂ := a.get j let a' := a.set i v₂ a'.set (size_set a i v₂ ▸ j) v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i let a := a.set i v (e, a) @[inline] def swapAt! (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else have : Inhabited α := ⟨v⟩ panic! ("index " ++ toString i ++ " out of bounds") @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { data := a.data.dropLast } def shrink (a : Array α) (n : Nat) : Array α := let rec loop | 0, a => a | n+1, a => loop n a.pop loop (a.size - n) a @[inline] def modifyM [Monad m] [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := do if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩ let v := a.get idx let a' := a.set idx arbitrary let v ← f v pure <| a'.set (size_set a .. ▸ idx) v else pure a @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run <| a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/ @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b /- Reference implementation for `forIn` -/ @[implementedBy Array.forInUnsafe] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self i) h have : as.size - 1 < as.size := Nat.sub_lt (Nat.zero_lt_of_lt h') (by decide) have : as.size - 1 - i < as.size := Nat.lt_of_le_of_lt (Nat.sub_le (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.le_of_lt h') b loop as.size (Nat.le_refl _) b instance : ForIn m (Array α) α where forIn := Array.forIn /- See comment at forInUnsafe -/ @[inline] unsafe def foldlMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.lt_of_lt_of_le hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.le_refl _) /- See comment at forInUnsafe -/ @[inline] unsafe def foldrMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i-1) stop (← f (as.uget (i-1) lcProof) b) if start ≤ as.size then if stop < start then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else if stop < as.size then fold (USize.ofNat as.size) (USize.ofNat stop) init else pure init /- Reference implementation for `foldrM` -/ @[implementedBy foldrMUnsafe] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec fold (i : Nat) (h : i ≤ as.size) (b : β) : m β := do if i == stop then pure b else match i, h with | 0, _ => pure b | i+1, h => have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h fold i (Nat.le_of_lt this) (← f (as.get ⟨i, this⟩) b) if h : start ≤ as.size then if stop < start then fold start h init else pure init else if stop < as.size then fold as.size (Nat.le_refl _) init else pure init /- See comment at forInUnsafe -/ @[inline] unsafe def mapMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := let sz := USize.ofNat as.size let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do if i < sz then let v := r.uget i lcProof let r := r.uset i arbitrary lcProof let vNew ← f (unsafeCast v) map (i+1) (r.uset i (unsafeCast vNew) lcProof) else pure (unsafeCast r) unsafeCast <| map 0 (unsafeCast as) /- Reference implementation for `mapM` -/ @[implementedBy mapMUnsafe] def mapM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do let b ← f a; pure (bs.push b)) (mkEmpty as.size) @[inline] def mapIdxM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : Fin as.size → α → m β) : m (Array β) := let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array β) : m (Array β) := do match i, inv with | 0, _ => pure bs | i+1, inv => have : j < as.size := by rw [← inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_comm] apply Nat.le_add_right let idx : Fin as.size := ⟨j, this⟩ have : i + (j + 1) = as.size := by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] map i (j+1) this (bs.push (← f idx (as.get idx))) map as.size 0 rfl (mkEmpty as.size) @[inline] def findSomeM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := do for a in as do match (← f a) with | some b => return b | _ => pure ⟨⟩ return none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := do for a in as do if (← p a) then return a return none @[inline] def findIdxM? [Monad m] (as : Array α) (p : α → m Bool) : m (Option Nat) := do let mut i := 0 for a in as do if (← p a) then return some i i := i + 1 return none @[inline] unsafe def anyMUnsafe {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do if i == stop then pure false else if (← p (as.uget i lcProof)) then pure true else any (i+1) stop if start < stop then if stop ≤ as.size then any (USize.ofNat start) (USize.ofNat stop) else pure false else pure false @[implementedBy anyMUnsafe] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let any (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) : m Bool := do if hlt : j < stop then match i with | 0 => pure false | i'+1 => if (← p (as.get ⟨j, Nat.lt_of_lt_of_le hlt h⟩)) then pure true else loop i' (j+1) else pure false loop (stop - start) start if h : stop ≤ as.size then any stop h else any as.size (Nat.le_refl _) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := return !(← as.anyM fun v => return !(← p v)) @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, h => pure none | i+1, h => do have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h let r ← f (as.get ⟨i, this⟩) match r with | some v => pure r | none => have : i ≤ as.size := Nat.le_of_lt this find i this find as.size (Nat.le_refl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := 0) (stop := as.size) : m PUnit := as.foldlM (fun _ => f) ⟨⟩ start stop @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := as.size) (stop := 0) : m PUnit := as.foldrM (fun a _ => f a) ⟨⟩ start stop @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Array α) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Array α) (start := as.size) (stop := 0) : β := Id.run <| as.foldrM f init start stop @[inline] def map {α : Type u} {β : Type v} (f : α → β) (as : Array α) : Array β := Id.run <| as.mapM f @[inline] def mapIdx {α : Type u} {β : Type v} (as : Array α) (f : Fin as.size → α → β) : Array β := Id.run <| as.mapIdxM f @[inline] def find? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findM? p @[inline] def findSome? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeM? f @[inline] def findSome! {α : Type u} {β : Type v} [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeRevM? f @[inline] def findRev? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p @[inline] def findIdx? {α : Type u} (as : Array α) (p : α → Bool) : Option Nat := let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat := if hlt : j < as.size then match i, inv with | 0, inv => by apply False.elim rw [Nat.zero_add] at inv rw [inv] at hlt exact absurd hlt (Nat.lt_irrefl _) | i+1, inv => if p (as.get ⟨j, hlt⟩) then some j else have : i + (j+1) = as.size := by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] loop i (j+1) this else none loop as.size 0 rfl def getIdx? [BEq α] (a : Array α) (v : α) : Option Nat := a.findIdx? fun a => a == v @[inline] def any (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.anyM p start stop @[inline] def all (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.allM p start stop def contains [BEq α] (as : Array α) (a : α) : Bool := as.any fun b => a == b def elem [BEq α] (a : α) (as : Array α) : Bool := as.contains a -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverse (as : Array α) : Array α := let n := as.size let mid := n / 2 let rec rev (as : Array α) (i : Nat) := if i < mid then rev (as.swap! i (n - i - 1)) (i+1) else as rev as 0 @[inline] def getEvenElems (as : Array α) : Array α := (·.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a => if even then (false, r.push a) else (true, r) @[export lean_array_to_list] def toList (as : Array α) : List α := as.foldr List.cons [] instance {α : Type u} [Repr α] : Repr (Array α) where reprPrec a n := let _ : Std.ToFormat α := ⟨repr⟩ if a.size == 0 then "#[]" else Std.Format.bracketFill "#[" (Std.Format.joinSep (toList a) ("," ++ Std.Format.line)) "]" instance [ToString α] : ToString (Array α) where toString a := "#" ++ toString a.toList protected def append (as : Array α) (bs : Array α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : Append (Array α) := ⟨Array.append⟩ protected def appendList (as : Array α) (bs : List α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : HAppend (Array α) (List α) (Array α) := ⟨Array.appendList⟩ @[inline] def concatMapM [Monad m] (f : α → m (Array β)) (as : Array α) : m (Array β) := as.foldlM (init := empty) fun bs a => do return bs ++ (← f a) @[inline] def concatMap (f : α → Array β) (as : Array α) : Array β := as.foldl (init := empty) fun bs a => bs ++ f a end Array export Array (mkArray) syntax "#[" sepBy(term, ", ") "]" : term macro_rules | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ]) namespace Array -- TODO(Leo): cleanup @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [BEq α] : BEq (Array α) := ⟨fun a b => isEqv a b BEq.beq⟩ @[inline] def filter (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Array α := as.foldl (init := #[]) (start := start) (stop := stop) fun r a => if p a then r.push a else r @[inline] def filterM [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m (Array α) := as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do if (← p a) then r.push a else r @[specialize] def filterMapM [Monad m] (f : α → m (Option β)) (as : Array α) (start := 0) (stop := as.size) : m (Array β) := as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do match (← f a) with | some b => pure (bs.push b) | none => pure bs @[inline] def filterMap (f : α → Option β) (as : Array α) (start := 0) (stop := as.size) : Array β := Id.run <| as.filterMapM f (start := start) (stop := stop) @[specialize] def getMax? (as : Array α) (lt : α → α → Bool) : Option α := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩ some <| as.foldl (init := a0) (start := 1) fun best a => if lt best a then a else best else none @[inline] def partition (p : α → Bool) (as : Array α) : Array α × Array α := do let mut bs := #[] let mut cs := #[] for a in as do if p a then bs := bs.push a else cs := cs.push a return (bs, cs) theorem ext (a b : Array α) (h₁ : a.size = b.size) (h₂ : (i : Nat) → (hi₁ : i < a.size) → (hi₂ : i < b.size) → a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) : a = b := by let rec extAux (a b : List α) (h₁ : a.length = b.length) (h₂ : (i : Nat) → (hi₁ : i < a.length) → (hi₂ : i < b.length) → a.get i hi₁ = b.get i hi₂) : a = b := by induction a generalizing b with | nil => cases b with | nil => rfl | cons b bs => rw [List.length_cons] at h₁; injection h₁ | cons a as ih => cases b with | nil => rw [List.length_cons] at h₁; injection h₁ | cons b bs => have hz₁ : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zero_lt_succ have hz₂ : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zero_lt_succ have headEq : a = b := h₂ 0 hz₁ hz₂ have h₁' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h₁; injection h₁; assumption have h₂' : (i : Nat) → (hi₁ : i < as.length) → (hi₂ : i < bs.length) → as.get i hi₁ = bs.get i hi₂ := by intro i hi₁ hi₂ have hi₁' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have hi₂' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have : (a::as).get (i+1) hi₁' = (b::bs).get (i+1) hi₂' := h₂ (i+1) hi₁' hi₂' apply this have tailEq : as = bs := ih bs h₁' h₂' rw [headEq, tailEq] cases a; cases b apply congrArg apply extAux assumption assumption theorem extLit {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : (i : Nat) → (hi : i < n) → a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array -- CLEANUP the following code namespace Array partial def indexOfAux [BEq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux a v (i+1) else none def indexOf? [BEq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a @[simp] theorem size_swap (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := by show ((a.set i (a.get j)).set (size_set a i _ ▸ j) (a.get i)).size = a.size rw [size_set, size_set] @[simp] theorem size_pop (a : Array α) : a.pop.size = a.size - 1 := List.length_dropLast .. section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } where default := ⟨a.pop, size_pop a⟩ partial def eraseIdxSzAux (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h⟩; eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq) else ⟨r.pop, (size_pop r).trans (heq ▸ rfl)⟩ end def eraseIdx' (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def erase [BEq α] (as : Array α) (a : α) : Array α := match as.indexOf? a with | none => as | some i => as.feraseIdx i partial def insertAtAux (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux i as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size def toListLitAux (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux a n hsz i (Nat.le_of_succ_le hi) (a.getLit i hsz (Nat.lt_of_lt_of_eq (Nat.lt_of_lt_of_le (Nat.lt_succ_self i) hi) hsz) :: acc) def toArrayLit (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray <| toListLitAux a n hsz n (hsz ▸ Nat.le_refl _) [] theorem toArrayLit_eq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove ∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List α) (hi : 0 ≤ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List α) (hi : i+1 ≤ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have ∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ [] -/ partial def isPrefixOfAux [BEq α] (as bs : Array α) (hle : as.size ≤ bs.size) : Nat → Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.lt_of_lt_of_le h hle⟩; if a == b then isPrefixOfAux as bs hle (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf [BEq α] (as bs : Array α) : Bool := if h : as.size ≤ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux [BEq α] (as : Array α) (a : α) : forall (i : Nat), i < as.size → Bool | 0, h => true | i+1, h => have : i < as.size := Nat.lt_trans (Nat.lt_succ_self _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux as a i this private partial def allDiffAux [BEq α] (as : Array α) : Nat → Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux as (i+1) else true def allDiff [BEq α] (as : Array α) : Bool := allDiffAux as 0 @[specialize] partial def zipWithAux (f : α → β → γ) (as : Array α) (bs : Array β) : Nat → Array γ → Array γ | i, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; if h : i < bs.size then let b := bs.get ⟨i, h⟩; zipWithAux f as bs (i+1) <| cs.push <| f a b else cs else cs @[inline] def zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : Array γ := zipWithAux f as bs 0 #[] def zip (as : Array α) (bs : Array β) : Array (α × β) := zipWith as bs Prod.mk def unzip (as : Array (α × β)) : Array α × Array β := as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b) def split (as : Array α) (p : α → Bool) : Array α × Array α := as.foldl (init := (#[], #[])) fun (as, bs) a => if p a then (as.push a, bs) else (as, bs.push a) end Array
a46b58b80c57c747218796df623d9e5d54438ef7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/bounded_continuous_function_auto.lean
16eba22a58acab58e4f01476c45192222cc2aa74
[]
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
27,767
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.basic import Mathlib.PostPort universes u v w u_1 namespace Mathlib /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] := Subtype fun (f : α → β) => continuous f ∧ ∃ (C : ℝ), ∀ (x y : α), dist (f x) (f y) ≤ C namespace bounded_continuous_function protected instance has_coe_to_fun {α : Type u} {β : Type v} [topological_space α] [metric_space β] : has_coe_to_fun (bounded_continuous_function α β) := has_coe_to_fun.mk (fun (x : bounded_continuous_function α β) => α → β) subtype.val theorem bounded_range {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} : metric.bounded (set.range ⇑f) := iff.mpr metric.bounded_range_iff (and.right (subtype.property f)) /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact {α : Type u} {β : Type v} [topological_space α] [metric_space β] [compact_space α] (f : α → β) (hf : continuous f) : bounded_continuous_function α β := { val := f, property := sorry } /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete {α : Type u} {β : Type v} [topological_space α] [metric_space β] [discrete_topology α] (f : α → β) (hf : ∃ (C : ℝ), ∀ (x y : α), dist (f x) (f y) ≤ C) : bounded_continuous_function α β := { val := f, property := sorry } /-- The uniform distance between two bounded continuous functions -/ protected instance has_dist {α : Type u} {β : Type v} [topological_space α] [metric_space β] : has_dist (bounded_continuous_function α β) := has_dist.mk fun (f g : bounded_continuous_function α β) => Inf (set_of fun (C : ℝ) => 0 ≤ C ∧ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C) theorem dist_eq {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} : dist f g = Inf (set_of fun (C : ℝ) => 0 ≤ C ∧ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C) := rfl theorem dist_set_exists {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} : ∃ (C : ℝ), 0 ≤ C ∧ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C := sorry /-- The pointwise distance is controlled by the distance between functions, by definition. -/ theorem dist_coe_le_dist {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} (x : α) : dist (coe_fn f x) (coe_fn g x) ≤ dist f g := le_cInf dist_set_exists fun (b : ℝ) (hb : b ∈ set_of fun (C : ℝ) => 0 ≤ C ∧ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C) => and.right hb x theorem ext {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} (H : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g := subtype.eq (funext H) theorem ext_iff {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} : f = g ↔ ∀ (x : α), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : α) => h ▸ rfl, mpr := ext } /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ theorem dist_le {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} {C : ℝ} (C0 : 0 ≤ C) : dist f g ≤ C ↔ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C := sorry /-- On an empty space, bounded continuous functions are at distance 0 -/ theorem dist_zero_of_empty {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} {g : bounded_continuous_function α β} (e : ¬Nonempty α) : dist f g = 0 := le_antisymm (iff.mpr (dist_le (le_refl 0)) fun (x : α) => not.elim e (Nonempty.intro x)) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ protected instance metric_space {α : Type u} {β : Type v} [topological_space α] [metric_space β] : metric_space (bounded_continuous_function α β) := metric_space.mk sorry sorry sorry sorry (fun (x y : bounded_continuous_function α β) => ennreal.of_real ((fun (f g : bounded_continuous_function α β) => Inf (set_of fun (C : ℝ) => 0 ≤ C ∧ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C)) x y)) (uniform_space_of_dist (fun (f g : bounded_continuous_function α β) => Inf (set_of fun (C : ℝ) => 0 ≤ C ∧ ∀ (x : α), dist (coe_fn f x) (coe_fn g x) ≤ C)) sorry sorry sorry) /-- Constant as a continuous bounded function. -/ def const (α : Type u) {β : Type v} [topological_space α] [metric_space β] (b : β) : bounded_continuous_function α β := { val := fun (x : α) => b, property := sorry } @[simp] theorem coe_const {α : Type u} {β : Type v} [topological_space α] [metric_space β] (b : β) : ⇑(const α b) = function.const α b := rfl theorem const_apply {α : Type u} {β : Type v} [topological_space α] [metric_space β] (a : α) (b : β) : coe_fn (const α b) a = b := rfl /-- If the target space is inhabited, so is the space of bounded continuous functions -/ protected instance inhabited {α : Type u} {β : Type v} [topological_space α] [metric_space β] [Inhabited β] : Inhabited (bounded_continuous_function α β) := { default := const α Inhabited.default } /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval {α : Type u} {β : Type v} [topological_space α] [metric_space β] : continuous fun (p : bounded_continuous_function α β × α) => coe_fn (prod.fst p) (prod.snd p) := sorry /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/ /-- In particular, when `x` is fixed, `f → f x` is continuous -/ theorem continuous_evalx {α : Type u} {β : Type v} [topological_space α] [metric_space β] {x : α} : continuous fun (f : bounded_continuous_function α β) => coe_fn f x := continuous.comp continuous_eval (continuous.prod_mk continuous_id continuous_const) /-- When `f` is fixed, `x → f x` is also continuous, by definition -/ theorem continuous_evalf {α : Type u} {β : Type v} [topological_space α] [metric_space β] {f : bounded_continuous_function α β} : continuous ⇑f := and.left (subtype.property f) /-- Bounded continuous functions taking values in a complete space form a complete space. -/ protected instance complete_space {α : Type u} {β : Type v} [topological_space α] [metric_space β] [complete_space β] : complete_space (bounded_continuous_function α β) := sorry /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [metric_space β] [metric_space γ] (G : β → γ) {C : nnreal} (H : lipschitz_with C G) (f : bounded_continuous_function α β) : bounded_continuous_function α γ := { val := fun (x : α) => G (coe_fn f x), property := sorry } /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ theorem lipschitz_comp {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [metric_space β] [metric_space γ] {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : lipschitz_with C (comp G H) := sorry /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ theorem uniform_continuous_comp {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [metric_space β] [metric_space γ] {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : uniform_continuous (comp G H) := lipschitz_with.uniform_continuous (lipschitz_comp H) /-- The composition operator (in the target) with a Lipschitz map is continuous -/ theorem continuous_comp {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [metric_space β] [metric_space γ] {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : continuous (comp G H) := lipschitz_with.continuous (lipschitz_comp H) /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict {α : Type u} {β : Type v} [topological_space α] [metric_space β] (s : set β) (f : bounded_continuous_function α β) (H : ∀ (x : α), coe_fn f x ∈ s) : bounded_continuous_function α ↥s := { val := set.cod_restrict (⇑f) s H, property := sorry } /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ {α : Type u} {β : Type v} [topological_space α] [compact_space α] [metric_space β] [compact_space β] (A : set (bounded_continuous_function α β)) (closed : is_closed A) (H : ∀ (x : α) (ε : ℝ) (H : ε > 0), ∃ (U : set α), ∃ (H : U ∈ nhds x), ∀ (y z : α), y ∈ U → z ∈ U → ∀ (f : bounded_continuous_function α β), f ∈ A → dist (coe_fn f y) (coe_fn f z) < ε) : is_compact A := sorry /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ {α : Type u} {β : Type v} [topological_space α] [compact_space α] [metric_space β] (s : set β) (hs : is_compact s) (A : set (bounded_continuous_function α β)) (closed : is_closed A) (in_s : ∀ (f : bounded_continuous_function α β) (x : α), f ∈ A → coe_fn f x ∈ s) (H : ∀ (x : α) (ε : ℝ) (H : ε > 0), ∃ (U : set α), ∃ (H : U ∈ nhds x), ∀ (y z : α), y ∈ U → z ∈ U → ∀ (f : bounded_continuous_function α β), f ∈ A → dist (coe_fn f y) (coe_fn f z) < ε) : is_compact A := sorry /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli {α : Type u} {β : Type v} [topological_space α] [compact_space α] [metric_space β] (s : set β) (hs : is_compact s) (A : set (bounded_continuous_function α β)) (in_s : ∀ (f : bounded_continuous_function α β) (x : α), f ∈ A → coe_fn f x ∈ s) (H : ∀ (x : α) (ε : ℝ) (H : ε > 0), ∃ (U : set α), ∃ (H : U ∈ nhds x), ∀ (y z : α), y ∈ U → z ∈ U → ∀ (f : bounded_continuous_function α β), f ∈ A → dist (coe_fn f y) (coe_fn f z) < ε) : is_compact (closure A) := sorry /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ theorem equicontinuous_of_continuity_modulus {β : Type v} [metric_space β] {α : Type u} [metric_space α] (b : ℝ → ℝ) (b_lim : filter.tendsto b (nhds 0) (nhds 0)) (A : set (bounded_continuous_function α β)) (H : ∀ (x y : α) (f : bounded_continuous_function α β), f ∈ A → dist (coe_fn f x) (coe_fn f y) ≤ b (dist x y)) (x : α) (ε : ℝ) (ε0 : 0 < ε) : ∃ (U : set α), ∃ (H : U ∈ nhds x), ∀ (y z : α), y ∈ U → z ∈ U → ∀ (f : bounded_continuous_function α β), f ∈ A → dist (coe_fn f y) (coe_fn f z) < ε := sorry /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ protected instance has_zero {α : Type u} {β : Type v} [topological_space α] [normed_group β] : HasZero (bounded_continuous_function α β) := { zero := const α 0 } @[simp] theorem coe_zero {α : Type u} {β : Type v} [topological_space α] [normed_group β] {x : α} : coe_fn 0 x = 0 := rfl protected instance has_norm {α : Type u} {β : Type v} [topological_space α] [normed_group β] : has_norm (bounded_continuous_function α β) := has_norm.mk fun (u : bounded_continuous_function α β) => dist u 0 theorem norm_def {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) : norm f = dist f 0 := rfl /-- The norm of a bounded continuous function is the supremum of `∥f x∥`. We use `Inf` to ensure that the definition works if `α` has no elements. -/ theorem norm_eq {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) : norm f = Inf (set_of fun (C : ℝ) => 0 ≤ C ∧ ∀ (x : α), norm (coe_fn f x) ≤ C) := sorry theorem norm_coe_le_norm {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (x : α) : norm (coe_fn f x) ≤ norm f := sorry theorem dist_le_two_norm' {β : Type v} {γ : Type w} [normed_group β] {f : γ → β} {C : ℝ} (hC : ∀ (x : γ), norm (f x) ≤ C) (x : γ) (y : γ) : dist (f x) (f y) ≤ bit0 1 * C := trans_rel_left LessEq (le_trans (dist_le_norm_add_norm (f x) (f y)) (add_le_add (hC x) (hC y))) (Eq.symm (two_mul C)) /-- Distance between the images of any two points is at most twice the norm of the function. -/ theorem dist_le_two_norm {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (x : α) (y : α) : dist (coe_fn f x) (coe_fn f y) ≤ bit0 1 * norm f := dist_le_two_norm' (norm_coe_le_norm f) x y /-- The norm of a function is controlled by the supremum of the pointwise norms -/ theorem norm_le {α : Type u} {β : Type v} [topological_space α] [normed_group β] {f : bounded_continuous_function α β} {C : ℝ} (C0 : 0 ≤ C) : norm f ≤ C ↔ ∀ (x : α), norm (coe_fn f x) ≤ C := sorry /-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty, then it is equal to `∥b∥`. -/ theorem norm_const_le {α : Type u} {β : Type v} [topological_space α] [normed_group β] (b : β) : norm (const α b) ≤ norm b := iff.mpr (norm_le (norm_nonneg b)) fun (x : α) => le_refl (norm (coe_fn (const α b) x)) @[simp] theorem norm_const_eq {α : Type u} {β : Type v} [topological_space α] [normed_group β] [h : Nonempty α] (b : β) : norm (const α b) = norm b := le_antisymm (norm_const_le b) (nonempty.elim h fun (x : α) => norm_coe_le_norm (const α b) x) /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀ (x : α), norm (f x) ≤ C) : bounded_continuous_function α β := { val := fun (n : α) => f n, property := sorry } theorem norm_of_normed_group_le {α : Type u} {β : Type v} [topological_space α] [normed_group β] {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ (x : α), norm (f x) ≤ C) : norm (of_normed_group f hfc C hfC) ≤ C := iff.mpr (norm_le hC) hfC /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β] (f : α → β) (C : ℝ) (H : ∀ (x : α), norm (f x) ≤ C) : bounded_continuous_function α β := of_normed_group f sorry C H /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ protected instance has_add {α : Type u} {β : Type v} [topological_space α] [normed_group β] : Add (bounded_continuous_function α β) := { add := fun (f g : bounded_continuous_function α β) => of_normed_group (⇑f + ⇑g) sorry (norm f + norm g) sorry } /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ protected instance has_neg {α : Type u} {β : Type v} [topological_space α] [normed_group β] : Neg (bounded_continuous_function α β) := { neg := fun (f : bounded_continuous_function α β) => of_normed_group (-⇑f) sorry (norm f) sorry } /-- The pointwise difference of two bounded continuous functions is again bounded continuous. -/ protected instance has_sub {α : Type u} {β : Type v} [topological_space α] [normed_group β] : Sub (bounded_continuous_function α β) := { sub := fun (f g : bounded_continuous_function α β) => of_normed_group (⇑f - ⇑g) sorry (norm f + norm g) sorry } @[simp] theorem coe_add {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (g : bounded_continuous_function α β) : ⇑(f + g) = fun (x : α) => coe_fn f x + coe_fn g x := rfl theorem add_apply {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (g : bounded_continuous_function α β) {x : α} : coe_fn (f + g) x = coe_fn f x + coe_fn g x := rfl @[simp] theorem coe_neg {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) : ⇑(-f) = fun (x : α) => -coe_fn f x := rfl theorem neg_apply {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) {x : α} : coe_fn (-f) x = -coe_fn f x := rfl theorem forall_coe_zero_iff_zero {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) : (∀ (x : α), coe_fn f x = 0) ↔ f = 0 := iff.symm ext_iff protected instance add_comm_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] : add_comm_group (bounded_continuous_function α β) := add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry @[simp] theorem coe_sub {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (g : bounded_continuous_function α β) : ⇑(f - g) = fun (x : α) => coe_fn f x - coe_fn g x := rfl theorem sub_apply {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (g : bounded_continuous_function α β) {x : α} : coe_fn (f - g) x = coe_fn f x - coe_fn g x := rfl protected instance normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] : normed_group (bounded_continuous_function α β) := normed_group.mk sorry theorem abs_diff_coe_le_dist {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : bounded_continuous_function α β) (g : bounded_continuous_function α β) {x : α} : norm (coe_fn f x - coe_fn g x) ≤ dist f g := eq.mpr (id (Eq._oldrec (Eq.refl (norm (coe_fn f x - coe_fn g x) ≤ dist f g)) (dist_eq_norm f g))) (norm_coe_le_norm (f - g) x) theorem coe_le_coe_add_dist {α : Type u} [topological_space α] {x : α} {f : bounded_continuous_function α ℝ} {g : bounded_continuous_function α ℝ} : coe_fn f x ≤ coe_fn g x + dist f g := iff.mp sub_le_iff_le_add' (and.right (iff.mp abs_le (dist_coe_le_dist x))) /-! ### Normed space structure In this section, if `β` is a normed space, then we show that the space of bounded continuous functions from `α` to `β` inherits a normed space structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ protected instance has_scalar {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] : has_scalar 𝕜 (bounded_continuous_function α β) := has_scalar.mk fun (c : 𝕜) (f : bounded_continuous_function α β) => of_normed_group (c • ⇑f) sorry (norm c * norm f) sorry @[simp] theorem coe_smul {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] (c : 𝕜) (f : bounded_continuous_function α β) : ⇑(c • f) = fun (x : α) => c • coe_fn f x := rfl theorem smul_apply {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] (c : 𝕜) (f : bounded_continuous_function α β) (x : α) : coe_fn (c • f) x = c • coe_fn f x := rfl protected instance semimodule {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] : semimodule 𝕜 (bounded_continuous_function α β) := semimodule.of_core (semimodule.core.mk (has_scalar.mk has_scalar.smul) sorry sorry sorry sorry) protected instance normed_space {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] : normed_space 𝕜 (bounded_continuous_function α β) := normed_space.mk sorry /-! ### Normed ring structure In this section, if `R` is a normed ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ protected instance ring {α : Type u} [topological_space α] {R : Type u_1} [normed_ring R] : ring (bounded_continuous_function α R) := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry (fun (f g : bounded_continuous_function α R) => of_normed_group (⇑f * ⇑g) sorry (norm f * norm g) sorry) sorry (const α 1) sorry sorry sorry sorry protected instance normed_ring {α : Type u} [topological_space α] {R : Type u_1} [normed_ring R] : normed_ring (bounded_continuous_function α R) := normed_ring.mk sorry sorry /-! ### Normed commutative ring structure In this section, if `R` is a normed commutative ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed commutative ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ protected instance comm_ring {α : Type u} [topological_space α] {R : Type u_1} [normed_comm_ring R] : comm_ring (bounded_continuous_function α R) := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry protected instance normed_comm_ring {α : Type u} [topological_space α] {R : Type u_1} [normed_comm_ring R] : normed_comm_ring (bounded_continuous_function α R) := normed_comm_ring.mk sorry /-! ### Normed algebra structure In this section, if `γ` is a normed algebra, then we show that the space of bounded continuous functions from `α` to `γ` inherits a normed algebra structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ /-- `bounded_continuous_function.const` as a `ring_hom`. -/ def C {α : Type u} {γ : Type w} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_ring γ] [normed_algebra 𝕜 γ] : 𝕜 →+* bounded_continuous_function α γ := ring_hom.mk (fun (c : 𝕜) => const α (coe_fn (algebra_map 𝕜 γ) c)) sorry sorry sorry sorry protected instance algebra {α : Type u} {γ : Type w} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_ring γ] [normed_algebra 𝕜 γ] : algebra 𝕜 (bounded_continuous_function α γ) := algebra.mk C sorry sorry protected instance normed_algebra {α : Type u} {γ : Type w} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_ring γ] [normed_algebra 𝕜 γ] [Nonempty α] : normed_algebra 𝕜 (bounded_continuous_function α γ) := normed_algebra.mk sorry /-! ### Structure as normed module over scalar functions If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous functions from `α` to `β` is naturally a module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ protected instance has_scalar' {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] : has_scalar (bounded_continuous_function α 𝕜) (bounded_continuous_function α β) := has_scalar.mk fun (f : bounded_continuous_function α 𝕜) (g : bounded_continuous_function α β) => of_normed_group (fun (x : α) => coe_fn f x • coe_fn g x) sorry (norm f * norm g) sorry protected instance module' {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] : module (bounded_continuous_function α 𝕜) (bounded_continuous_function α β) := semimodule.of_core (semimodule.core.mk (has_scalar.mk has_scalar.smul) sorry sorry sorry sorry) theorem norm_smul_le {α : Type u} {β : Type v} {𝕜 : Type u_1} [normed_field 𝕜] [topological_space α] [normed_group β] [normed_space 𝕜 β] (f : bounded_continuous_function α 𝕜) (g : bounded_continuous_function α β) : norm (f • g) ≤ norm f * norm g := norm_of_normed_group_le (has_scalar'._proof_1 f g) (mul_nonneg (norm_nonneg f) (norm_nonneg g)) (has_scalar'._proof_2 f g) end Mathlib
411379a7d6af1307ca009bd230f0074c3a912288
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/power/6.lean
78c263a0d479a853534d764c0eb8dff9d90305a3
[ "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
166
lean
lemma mul_pow (a b n : mynat) : (a * b) ^ n = a ^ n * b ^ n := induction n with d hd, repeat {rw pow_zero}, simp, repeat {rw pow_succ}, rw hd, simp, end
1562112825ad356f4236095ac708cef8d24ae331
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/zmod/quadratic_reciprocity.lean
c4a8bc90746eb4af7d07c0f11d2bdd29ed7b50cb
[ "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
23,223
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.finite data.zmod.basic data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_pow_two_eq_prime_iff_of_mod_four_eq_one`, and `exists_pow_two_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and `exists_pow_two_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmodp namespace zmodp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : ℕ} (hp : nat.prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (λ h, by resetI; subst h; exact iff_of_true ⟨1, subsingleton.elim _ _⟩ (subsingleton.elim _ _)) (λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], λ hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.two_le dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) : (∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmodp p hp, y ^ 2 = -1) ↔ p % 4 ≠ 3 := have (-1 : zmodp p hp) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, hp.eq_two_or_odd.elim (λ hp, by resetI; subst hp; exact dec_trivial) (λ hp1, (mod_two_eq_zero_or_one (p / 2)).elim (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_zero, eq_self_iff_true, true_iff], assume h, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, h] at hp2, exact absurd hp2 dec_trivial, end) (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_one, iff_false_intro (zmodp.ne_neg_self hp hp1 one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at hp2, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp1, have hp4 : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp1 hp2, revert hp4, generalize : p % 4 = k, revert k, exact dec_trivial end)) lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (λ h, by revert a ha; resetI; subst h; exact dec_trivial) (λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : ℕ} (hp : nat.prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_Ico_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom _ (coe : units (zmodp p hp) → zmodp p hp), ← prod_hom _ (coe : ℕ → zmodp p hp)], exact eq.symm (prod_bij (λ a _, (a : zmodp p hp).1) (λ a ha, Ico.mem.2 ⟨nat.pos_of_ne_zero (λ h, units.coe_ne_zero a (fin.eq_of_veq h)), by rw [← succ_sub hp.pos, succ_sub_one]; exact (a : zmodp p hp).2⟩) (λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (λ b hb, have b ≠ 0 ∧ b < p, by rwa [Ico.mem, nat.succ_le_iff, ← succ_sub hp.pos, succ_sub_one, nat.pos_iff_ne_zero] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_Ico_one_prime {p : ℕ} (hp : nat.prime p) : (Ico 1 p).prod (λ x, (x : zmodp p hp)) = -1 := by conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom _ (coe : ℕ → zmodp p hp), finset.prod_Ico_id_eq_fact, wilsons_lemma] end zmodp /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id {p : ℕ} (hp : p.prime) (a : zmodp p hp) (hpa : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hsurj : ∀ b : ℕ , b ∈ Ico 1 (p / 2).succ → ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmodp p hp).val_min_abs.nat_abs, from λ b hb, ⟨(b / a : zmodp p hp).val_min_abs.nat_abs, Ico.mem.2 ⟨nat.pos_of_ne_zero $ by simp [div_eq_mul_inv, hpa, zmodp.eq_zero_iff_dvd_nat hp b, hpe hb], nat.lt_succ_of_le $ zmodp.nat_abs_val_min_abs_le _⟩, begin rw [zmodp.cast_nat_abs_val_min_abs], split_ifs, { erw [mul_div_cancel' _ hpa, zmodp.val_min_abs, zmod.val_min_abs, zmodp.val_cast_of_lt hp (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hpa, zmod.nat_abs_val_min_abs_neg, zmod.val_min_abs, zmodp.val_cast_of_lt hp (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat] }, end⟩, have hmem : ∀ x : ℕ, x ∈ Ico 1 (p / 2).succ → (a * x : zmodp p hp).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, from λ x hx, by simp [hpa, zmodp.eq_zero_iff_dvd_nat hp x, hpe hx, lt_succ_iff, succ_le_iff, nat.pos_iff_ne_zero, zmodp.nat_abs_val_min_abs_le _], multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmodp p hp).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj private lemma gauss_lemma_aux₁ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hpa : (a : zmodp p hp) ≠ 0) : (a^(p / 2) * (p / 2).fact : zmodp p hp) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (p / 2).fact := calc (a ^ (p / 2) * (p / 2).fact : zmodp p hp) = (Ico 1 (p / 2).succ).prod (λ x, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_fact, prod_const, Ico.card, succ_sub_one]; simp ... = (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmodp p hp).val) : by simp ... = (Ico 1 (p / 2).succ).prod (λ x, (if (a * x : zmodp p hp).val ≤ p / 2 then 1 else -1) * (a * x : zmodp p hp).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [zmodp.cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmodp p hp).val_min_abs.nat_abs) : have (Ico 1 (p / 2).succ).prod (λ x, if (a * x : zmodp p hp).val ≤ p / 2 then (1 : zmodp p hp) else -1) = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).prod (λ _, -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (p / 2).fact : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id hp a hpa, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_fact] private lemma gauss_lemma_aux₂ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hpa : (a : zmodp p hp) ≠ 0) : (a^(p / 2) : zmodp p hp) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card := (domain.mul_right_inj (show ((p / 2).fact : zmodp p hp) ≠ 0, by rw [ne.def, zmodp.eq_zero_iff_dvd_nat, hp.dvd_fact, not_le]; exact nat.div_lt_self hp.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ _ hp2 hpa private lemma eisenstein_lemma_aux₁ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hap : (a : zmodp p hp) ≠ 0) : (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmodp p hp).val))).card + (Ico 1 (p / 2).succ).sum (λ x, x) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from zmod.eq_iff_modeq_nat.2 hp2, calc (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = (((Ico 1 (p / 2).succ).sum (λ x, (a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = ((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmodp p hp).val) : ℕ) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) : by simp only [zmodp.val_cast_nat]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2] ... = _ : congr_arg2 (+) (calc (((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmodp p hp).val) : ℕ) : zmod 2) = (Ico 1 (p / 2).succ).sum (λ x, ((((a * x : zmodp p hp).val_min_abs + (if (a * x : zmodp p hp).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2)) : by simp only [(zmodp.val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card + (((Ico 1 (p / 2).succ).sum (λ x, (a * x : zmodp p hp).val_min_abs.nat_abs)) : ℕ) : by simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast] ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id hp _ hap, ← finset.sum_eq_multiset_sum]; simp [sum_nat_cast]) rfl private lemma eisenstein_lemma_aux₂ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmodp p hp) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmodp p hp).val))).card ≡ (Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from zmod.eq_iff_modeq_nat.2 ha2, (@zmod.eq_iff_modeq_nat 2 _ _).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast, add_neg_eq_iff_eq_add.symm, zmod.neg_eq_self_mod_two] using eq.symm (eisenstein_lemma_aux₁ hp hp2 hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _$ finset.ext.2 $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integers point in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext] else calc (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (Ico 1 (p / 2).succ).sum (λ a, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card) : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul {p q : ℕ} (hp : p.prime) (hq0 : (q : zmodp p hp) ≠ 0) : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) + (Ico 1 (q / 2).succ).sum (λ a, (a * p) / q) = (p / 2) * (q / 2) := have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), from disjoint_filter.2 $ λ x hx hpq hqp, have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp [*, nat.lt_succ_iff] at *; tauto) (nat.div_lt_self hp.pos dec_trivial), begin have : (x.1 : zmodp p hp) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmodp p hp) (le_antisymm hpq hqp) }, rw [fin.eq_iff_veq, zmodp.val_cast_of_lt hp hxp, zmodp.zero_val] at this, simp * at * end, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext.2 $ λ x, by have := le_total (x.2 * p) (x.1 * q); simp; tauto, by rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product]; simp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) namespace zmodp def legendre_sym (a p : ℕ) (hp : nat.prime p) : ℤ := if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) (hp : nat.prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.two_le (succ_pos 1))] else (nat.prime.eq_two_or_odd hp).elim (λ hp2, begin resetI; subst hp2, suffices : ∀ a : zmodp 2 nat.prime_two, (((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 nat.prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (λ hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : nat.prime p) (ha : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} (hp1 : p % 2 = 1) (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card := have (legendre_sym a p hp : zmodp p hp) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card : ℤ) : zmodp p hp), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ hp hp1 ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a hp ha0; cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card; simp [*, zmodp.ne_neg_self hp hp1 one_ne_zero, (zmodp.ne_neg_self hp hp1 one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = 1 ↔ (∃ b : zmodp p hp, b ^ 2 = a) := by rw [legendre_sym]; split_ifs; finish lemma eisenstein_lemma (hp1 : p % 2 = 1) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = (-1)^(Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma hp hp1 ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ hp hp1 ha1 ha0] theorem quadratic_reciprocity (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmodp q hq) ≠ 0, from zmodp.prime_ne_zero _ hp hpq.symm, have hqp0 : (q : zmodp p hp) ≠ 0, from zmodp.prime_ne_zero _ hq hpq, by rw [eisenstein_lemma _ hq1 hp1 hpq0, eisenstein_lemma _ hp1 hq1 hqp0, ← _root_.pow_add, sum_mul_div_add_sum_mul_div_eq_mul _ hpq0, mul_comm] lemma legendre_sym_two (hp1 : p % 2 = 1) : legendre_sym 2 p hp = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simp [hp1]), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmodp p hp).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← mod_add_div p 2, add_comm, hp1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, zmodp.val_cast_of_lt _ h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmodp p hp).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmodp p hp).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma _ hp1 (prime_ne_zero hp prime_two hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((@zmod.eq_iff_modeq_nat 2 _ _).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, zmod.neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_pow_two_eq_two_iff (hp1 : p % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmodp p hp) ≠ 0, from zmodp.prime_ne_zero hp prime_two (λ h, by simp * at *), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmodp p hp) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff hp hp2, legendre_sym_two hp hp1, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, clear hm, revert m, exact dec_trivial end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by resetI; subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
30d99d39051f87601c6406cc58e3cc21eb952137
9dc8cecdf3c4634764a18254e94d43da07142918
/src/combinatorics/simple_graph/connectivity.lean
4b5e0aec79048f9d4713d20e5a54bb87b88e9cd4
[ "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
52,427
lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.basic import combinatorics.simple_graph.subgraph import data.list /-! # Graph connectivity In a simple graph, * A *walk* is a finite sequence of adjacent vertices, and can be thought of equally well as a sequence of directed edges. * A *trail* is a walk whose edges each appear no more than once. * A *path* is a trail whose vertices appear no more than once. * A *cycle* is a nonempty trail whose first and last vertices are the same and whose vertices except for the first appear no more than once. **Warning:** graph theorists mean something different by "path" than do homotopy theorists. A "walk" in graph theory is a "path" in homotopy theory. Another warning: some graph theorists use "path" and "simple path" for "walk" and "path." Some definitions and theorems have inspiration from multigraph counterparts in [Chou1994]. ## Main definitions * `simple_graph.walk` (with accompanying pattern definitions `simple_graph.walk.nil'` and `simple_graph.walk.cons'`) * `simple_graph.walk.is_trail`, `simple_graph.walk.is_path`, and `simple_graph.walk.is_cycle`. * `simple_graph.path` * `simple_graph.walk.map` and `simple_graph.path.map` for the induced map on walks, given an (injective) graph homomorphism. * `simple_graph.reachable` for the relation of whether there exists a walk between a given pair of vertices * `simple_graph.preconnected` and `simple_graph.connected` are predicates on simple graphs for whether every vertex can be reached from every other, and in the latter case, whether the vertex type is nonempty. * `simple_graph.subgraph.connected` gives subgraphs the connectivity predicate via `simple_graph.subgraph.coe`. * `simple_graph.connected_component` is the type of connected components of a given graph. ## Tags walks, trails, paths, circuits, cycles -/ open function universes u v w namespace simple_graph variables {V : Type u} {V' : Type v} {V'' : Type w} variables (G : simple_graph V) (G' : simple_graph V') (G'' : simple_graph V'') /-- A walk is a sequence of adjacent vertices. For vertices `u v : V`, the type `walk u v` consists of all walks starting at `u` and ending at `v`. We say that a walk *visits* the vertices it contains. The set of vertices a walk visits is `simple_graph.walk.support`. See `simple_graph.walk.nil'` and `simple_graph.walk.cons'` for patterns that can be useful in definitions since they make the vertices explicit. -/ @[derive decidable_eq] inductive walk : V → V → Type u | nil {u : V} : walk u u | cons {u v w: V} (h : G.adj u v) (p : walk v w) : walk u w attribute [refl] walk.nil @[simps] instance walk.inhabited (v : V) : inhabited (G.walk v v) := ⟨walk.nil⟩ namespace walk variables {G} /-- Pattern to get `walk.nil` with the vertex as an explicit argument. -/ @[pattern] abbreviation nil' (u : V) : G.walk u u := walk.nil /-- Pattern to get `walk.cons` with the vertices as explicit arguments. -/ @[pattern] abbreviation cons' (u v w : V) (h : G.adj u v) (p : G.walk v w) : G.walk u w := walk.cons h p /-- Change the endpoints of a walk using equalities. This is helpful for relaxing definitional equality constraints and to be able to state otherwise difficult-to-state lemmas. While this is a simple wrapper around `eq.rec`, it gives a canonical way to write it. The simp-normal form is for the `copy` to be pushed outward. That way calculations can occur within the "copy context." -/ protected def copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : G.walk u' v' := eq.rec (eq.rec p hv) hu @[simp] lemma copy_rfl_rfl {u v} (p : G.walk u v) : p.copy rfl rfl = p := rfl @[simp] lemma copy_copy {u v u' v' u'' v''} (p : G.walk u v) (hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') : (p.copy hu hv).copy hu' hv' = p.copy (hu.trans hu') (hv.trans hv') := by { subst_vars, refl } @[simp] lemma copy_nil {u u'} (hu : u = u') : (walk.nil : G.walk u u).copy hu hu = walk.nil := by { subst_vars, refl } lemma copy_cons {u v w u' w'} (h : G.adj u v) (p : G.walk v w) (hu : u = u') (hw : w = w') : (walk.cons h p).copy hu hw = walk.cons (by rwa ← hu) (p.copy rfl hw) := by { subst_vars, refl } @[simp] lemma cons_copy {u v w v' w'} (h : G.adj u v) (p : G.walk v' w') (hv : v' = v) (hw : w' = w) : walk.cons h (p.copy hv hw) = (walk.cons (by rwa hv) p).copy rfl hw := by { subst_vars, refl } lemma exists_eq_cons_of_ne : Π {u v : V} (hne : u ≠ v) (p : G.walk u v), ∃ (w : V) (h : G.adj u w) (p' : G.walk w v), p = cons h p' | _ _ hne nil := (hne rfl).elim | _ _ _ (cons h p') := ⟨_, h, p', rfl⟩ /-- The length of a walk is the number of edges/darts along it. -/ def length : Π {u v : V}, G.walk u v → ℕ | _ _ nil := 0 | _ _ (cons _ q) := q.length.succ /-- The concatenation of two compatible walks. -/ @[trans] def append : Π {u v w : V}, G.walk u v → G.walk v w → G.walk u w | _ _ _ nil q := q | _ _ _ (cons h p) q := cons h (p.append q) /-- The concatenation of the reverse of the first walk with the second walk. -/ protected def reverse_aux : Π {u v w : V}, G.walk u v → G.walk u w → G.walk v w | _ _ _ nil q := q | _ _ _ (cons h p) q := reverse_aux p (cons (G.symm h) q) /-- The walk in reverse. -/ @[symm] def reverse {u v : V} (w : G.walk u v) : G.walk v u := w.reverse_aux nil /-- Get the `n`th vertex from a walk, where `n` is generally expected to be between `0` and `p.length`, inclusive. If `n` is greater than or equal to `p.length`, the result is the path's endpoint. -/ def get_vert : Π {u v : V} (p : G.walk u v) (n : ℕ), V | u v nil _ := u | u v (cons _ _) 0 := u | u v (cons _ q) (n+1) := q.get_vert n @[simp] lemma get_vert_zero {u v} (w : G.walk u v) : w.get_vert 0 = u := by { cases w; refl } lemma get_vert_of_length_le {u v} (w : G.walk u v) {i : ℕ} (hi : w.length ≤ i) : w.get_vert i = v := begin induction w with _ x y z hxy wyz IH generalizing i, { refl }, { cases i, { cases hi, }, { exact IH (nat.succ_le_succ_iff.1 hi) } } end @[simp] lemma get_vert_length {u v} (w : G.walk u v) : w.get_vert w.length = v := w.get_vert_of_length_le rfl.le lemma adj_get_vert_succ {u v} (w : G.walk u v) {i : ℕ} (hi : i < w.length) : G.adj (w.get_vert i) (w.get_vert (i+1)) := begin induction w with _ x y z hxy wyz IH generalizing i, { cases hi, }, { cases i, { simp [get_vert, hxy] }, { exact IH (nat.succ_lt_succ_iff.1 hi) } }, end @[simp] lemma cons_append {u v w x : V} (h : G.adj u v) (p : G.walk v w) (q : G.walk w x) : (cons h p).append q = cons h (p.append q) := rfl @[simp] lemma cons_nil_append {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h nil).append p = cons h p := rfl @[simp] lemma append_nil : Π {u v : V} (p : G.walk u v), p.append nil = p | _ _ nil := rfl | _ _ (cons h p) := by rw [cons_append, append_nil] @[simp] lemma nil_append {u v : V} (p : G.walk u v) : nil.append p = p := rfl lemma append_assoc : Π {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk w x), p.append (q.append r) = (p.append q).append r | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by { dunfold append, rw append_assoc, } @[simp] lemma append_copy_copy {u v w u' v' w'} (p : G.walk u v) (q : G.walk v w) (hu : u = u') (hv : v = v') (hw : w = w') : (p.copy hu hv).append (q.copy hv hw) = (p.append q).copy hu hw := by { subst_vars, refl } @[simp] lemma reverse_nil {u : V} : (nil : G.walk u u).reverse = nil := rfl lemma reverse_singleton {u v : V} (h : G.adj u v) : (cons h nil).reverse = cons (G.symm h) nil := rfl @[simp] lemma cons_reverse_aux {u v w x : V} (p : G.walk u v) (q : G.walk w x) (h : G.adj w u) : (cons h p).reverse_aux q = p.reverse_aux (cons (G.symm h) q) := rfl @[simp] protected lemma append_reverse_aux : Π {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk u x), (p.append q).reverse_aux r = q.reverse_aux (p.reverse_aux r) | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := append_reverse_aux p' q (cons (G.symm h) r) @[simp] protected lemma reverse_aux_append : Π {u v w x : V} (p : G.walk u v) (q : G.walk u w) (r : G.walk w x), (p.reverse_aux q).append r = p.reverse_aux (q.append r) | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by simp [reverse_aux_append p' (cons (G.symm h) q) r] protected lemma reverse_aux_eq_reverse_append {u v w : V} (p : G.walk u v) (q : G.walk u w) : p.reverse_aux q = p.reverse.append q := by simp [reverse] @[simp] lemma reverse_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).reverse = p.reverse.append (cons (G.symm h) nil) := by simp [reverse] @[simp] lemma reverse_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).reverse = p.reverse.copy hv hu := by { subst_vars, refl } @[simp] lemma reverse_append {u v w : V} (p : G.walk u v) (q : G.walk v w) : (p.append q).reverse = q.reverse.append p.reverse := by simp [reverse] @[simp] lemma reverse_reverse : Π {u v : V} (p : G.walk u v), p.reverse.reverse = p | _ _ nil := rfl | _ _ (cons h p) := by simp [reverse_reverse] @[simp] lemma length_nil {u : V} : (nil : G.walk u u).length = 0 := rfl @[simp] lemma length_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).length = p.length + 1 := rfl @[simp] lemma length_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).length = p.length := by { subst_vars, refl } @[simp] lemma length_append : Π {u v w : V} (p : G.walk u v) (q : G.walk v w), (p.append q).length = p.length + q.length | _ _ _ nil _ := by simp | _ _ _ (cons _ _) _ := by simp [length_append, add_left_comm, add_comm] @[simp] protected lemma length_reverse_aux : Π {u v w : V} (p : G.walk u v) (q : G.walk u w), (p.reverse_aux q).length = p.length + q.length | _ _ _ nil _ := by simp! | _ _ _ (cons _ _) _ := by simp [length_reverse_aux, nat.add_succ, nat.succ_add] @[simp] lemma length_reverse {u v : V} (p : G.walk u v) : p.reverse.length = p.length := by simp [reverse] lemma eq_of_length_eq_zero : Π {u v : V} {p : G.walk u v}, p.length = 0 → u = v | _ _ nil _ := rfl @[simp] lemma exists_length_eq_zero_iff {u v : V} : (∃ (p : G.walk u v), p.length = 0) ↔ u = v := begin split, { rintro ⟨p, hp⟩, exact eq_of_length_eq_zero hp, }, { rintro rfl, exact ⟨nil, rfl⟩, }, end @[simp] lemma length_eq_zero_iff {u : V} {p : G.walk u u} : p.length = 0 ↔ p = nil := by cases p; simp /-- The `support` of a walk is the list of vertices it visits in order. -/ def support : Π {u v : V}, G.walk u v → list V | u v nil := [u] | u v (cons h p) := u :: p.support /-- The `darts` of a walk is the list of darts it visits in order. -/ def darts : Π {u v : V}, G.walk u v → list G.dart | u v nil := [] | u v (cons h p) := ⟨(u, _), h⟩ :: p.darts /-- The `edges` of a walk is the list of edges it visits in order. This is defined to be the list of edges underlying `simple_graph.walk.darts`. -/ def edges {u v : V} (p : G.walk u v) : list (sym2 V) := p.darts.map dart.edge @[simp] lemma support_nil {u : V} : (nil : G.walk u u).support = [u] := rfl @[simp] lemma support_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).support = u :: p.support := rfl @[simp] lemma support_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).support = p.support := by { subst_vars, refl } lemma support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').support = p.support ++ p'.support.tail := by induction p; cases p'; simp [*] @[simp] lemma support_reverse {u v : V} (p : G.walk u v) : p.reverse.support = p.support.reverse := by induction p; simp [support_append, *] lemma support_ne_nil {u v : V} (p : G.walk u v) : p.support ≠ [] := by cases p; simp lemma tail_support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').support.tail = p.support.tail ++ p'.support.tail := by rw [support_append, list.tail_append_of_ne_nil _ _ (support_ne_nil _)] lemma support_eq_cons {u v : V} (p : G.walk u v) : p.support = u :: p.support.tail := by cases p; simp @[simp] lemma start_mem_support {u v : V} (p : G.walk u v) : u ∈ p.support := by cases p; simp @[simp] lemma end_mem_support {u v : V} (p : G.walk u v) : v ∈ p.support := by induction p; simp [*] lemma mem_support_iff {u v w : V} (p : G.walk u v) : w ∈ p.support ↔ w = u ∨ w ∈ p.support.tail := by cases p; simp lemma mem_support_nil_iff {u v : V} : u ∈ (nil : G.walk v v).support ↔ u = v := by simp @[simp] lemma mem_tail_support_append_iff {t u v w : V} (p : G.walk u v) (p' : G.walk v w) : t ∈ (p.append p').support.tail ↔ t ∈ p.support.tail ∨ t ∈ p'.support.tail := by rw [tail_support_append, list.mem_append] @[simp] lemma end_mem_tail_support_of_ne {u v : V} (h : u ≠ v) (p : G.walk u v) : v ∈ p.support.tail := by { obtain ⟨_, _, _, rfl⟩ := exists_eq_cons_of_ne h p, simp } @[simp] lemma mem_support_append_iff {t u v w : V} (p : G.walk u v) (p' : G.walk v w) : t ∈ (p.append p').support ↔ t ∈ p.support ∨ t ∈ p'.support := begin simp only [mem_support_iff, mem_tail_support_append_iff], by_cases h : t = v; by_cases h' : t = u; subst_vars; try { have := ne.symm h' }; simp [*], end @[simp] lemma subset_support_append_left {V : Type u} {G : simple_graph V} {u v w : V} (p : G.walk u v) (q : G.walk v w) : p.support ⊆ (p.append q).support := by simp only [walk.support_append, list.subset_append_left] @[simp] lemma subset_support_append_right {V : Type u} {G : simple_graph V} {u v w : V} (p : G.walk u v) (q : G.walk v w) : q.support ⊆ (p.append q).support := by { intro h, simp only [mem_support_append_iff, or_true, implies_true_iff] { contextual := tt }} lemma coe_support {u v : V} (p : G.walk u v) : (p.support : multiset V) = {u} + p.support.tail := by cases p; refl lemma coe_support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : ((p.append p').support : multiset V) = {u} + p.support.tail + p'.support.tail := by rw [support_append, ←multiset.coe_add, coe_support] lemma coe_support_append' [decidable_eq V] {u v w : V} (p : G.walk u v) (p' : G.walk v w) : ((p.append p').support : multiset V) = p.support + p'.support - {v} := begin rw [support_append, ←multiset.coe_add], simp only [coe_support], rw add_comm {v}, simp only [← add_assoc, add_tsub_cancel_right], end lemma chain_adj_support : Π {u v w : V} (h : G.adj u v) (p : G.walk v w), list.chain G.adj u p.support | _ _ _ h nil := list.chain.cons h list.chain.nil | _ _ _ h (cons h' p) := list.chain.cons h (chain_adj_support h' p) lemma chain'_adj_support : Π {u v : V} (p : G.walk u v), list.chain' G.adj p.support | _ _ nil := list.chain.nil | _ _ (cons h p) := chain_adj_support h p lemma chain_dart_adj_darts : Π {d : G.dart} {v w : V} (h : d.snd = v) (p : G.walk v w), list.chain G.dart_adj d p.darts | _ _ _ h nil := list.chain.nil | _ _ _ h (cons h' p) := list.chain.cons h (chain_dart_adj_darts (by exact rfl) p) lemma chain'_dart_adj_darts : Π {u v : V} (p : G.walk u v), list.chain' G.dart_adj p.darts | _ _ nil := trivial | _ _ (cons h p) := chain_dart_adj_darts rfl p /-- Every edge in a walk's edge list is an edge of the graph. It is written in this form (rather than using `⊆`) to avoid unsightly coercions. -/ lemma edges_subset_edge_set : Π {u v : V} (p : G.walk u v) ⦃e : sym2 V⦄ (h : e ∈ p.edges), e ∈ G.edge_set | _ _ (cons h' p') e h := by rcases h with ⟨rfl, h⟩; solve_by_elim @[simp] lemma darts_nil {u : V} : (nil : G.walk u u).darts = [] := rfl @[simp] lemma darts_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).darts = ⟨(u, v), h⟩ :: p.darts := rfl @[simp] lemma darts_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).darts = p.darts := by { subst_vars, refl } @[simp] lemma darts_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').darts = p.darts ++ p'.darts := by induction p; simp [*] @[simp] lemma darts_reverse {u v : V} (p : G.walk u v) : p.reverse.darts = (p.darts.map dart.symm).reverse := by induction p; simp [*, sym2.eq_swap] lemma mem_darts_reverse {u v : V} {d : G.dart} {p : G.walk u v} : d ∈ p.reverse.darts ↔ d.symm ∈ p.darts := by simp lemma cons_map_snd_darts {u v : V} (p : G.walk u v) : u :: p.darts.map dart.snd = p.support := by induction p; simp! [*] lemma map_snd_darts {u v : V} (p : G.walk u v) : p.darts.map dart.snd = p.support.tail := by simpa using congr_arg list.tail (cons_map_snd_darts p) lemma map_fst_darts_append {u v : V} (p : G.walk u v) : p.darts.map dart.fst ++ [v] = p.support := by induction p; simp! [*] lemma map_fst_darts {u v : V} (p : G.walk u v) : p.darts.map dart.fst = p.support.init := by simpa! using congr_arg list.init (map_fst_darts_append p) @[simp] lemma edges_nil {u : V} : (nil : G.walk u u).edges = [] := rfl @[simp] lemma edges_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).edges = ⟦(u, v)⟧ :: p.edges := rfl @[simp] lemma edges_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).edges = p.edges := by { subst_vars, refl } @[simp] lemma edges_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').edges = p.edges ++ p'.edges := by simp [edges] @[simp] lemma edges_reverse {u v : V} (p : G.walk u v) : p.reverse.edges = p.edges.reverse := by simp [edges] @[simp] lemma length_support {u v : V} (p : G.walk u v) : p.support.length = p.length + 1 := by induction p; simp * @[simp] lemma length_darts {u v : V} (p : G.walk u v) : p.darts.length = p.length := by induction p; simp * @[simp] lemma length_edges {u v : V} (p : G.walk u v) : p.edges.length = p.length := by simp [edges] lemma dart_fst_mem_support_of_mem_darts : Π {u v : V} (p : G.walk u v) {d : G.dart}, d ∈ p.darts → d.fst ∈ p.support | u v (cons h p') d hd := begin simp only [support_cons, darts_cons, list.mem_cons_iff] at hd ⊢, rcases hd with (rfl|hd), { exact or.inl rfl, }, { exact or.inr (dart_fst_mem_support_of_mem_darts _ hd), }, end lemma dart_snd_mem_support_of_mem_darts {u v : V} (p : G.walk u v) {d : G.dart} (h : d ∈ p.darts) : d.snd ∈ p.support := by simpa using p.reverse.dart_fst_mem_support_of_mem_darts (by simp [h] : d.symm ∈ p.reverse.darts) lemma fst_mem_support_of_mem_edges {t u v w : V} (p : G.walk v w) (he : ⟦(t, u)⟧ ∈ p.edges) : t ∈ p.support := begin obtain ⟨d, hd, he⟩ := list.mem_map.mp he, rw dart_edge_eq_mk_iff' at he, rcases he with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { exact dart_fst_mem_support_of_mem_darts _ hd, }, { exact dart_snd_mem_support_of_mem_darts _ hd, }, end lemma snd_mem_support_of_mem_edges {t u v w : V} (p : G.walk v w) (he : ⟦(t, u)⟧ ∈ p.edges) : u ∈ p.support := by { rw sym2.eq_swap at he, exact p.fst_mem_support_of_mem_edges he } lemma darts_nodup_of_support_nodup {u v : V} {p : G.walk u v} (h : p.support.nodup) : p.darts.nodup := begin induction p, { simp, }, { simp only [darts_cons, support_cons, list.nodup_cons] at h ⊢, refine ⟨λ h', h.1 (dart_fst_mem_support_of_mem_darts p_p h'), p_ih h.2⟩, } end lemma edges_nodup_of_support_nodup {u v : V} {p : G.walk u v} (h : p.support.nodup) : p.edges.nodup := begin induction p, { simp, }, { simp only [edges_cons, support_cons, list.nodup_cons] at h ⊢, exact ⟨λ h', h.1 (fst_mem_support_of_mem_edges p_p h'), p_ih h.2⟩, } end /-! ### Trails, paths, circuits, cycles -/ /-- A *trail* is a walk with no repeating edges. -/ structure is_trail {u v : V} (p : G.walk u v) : Prop := (edges_nodup : p.edges.nodup) /-- A *path* is a walk with no repeating vertices. Use `simple_graph.walk.is_path.mk'` for a simpler constructor. -/ structure is_path {u v : V} (p : G.walk u v) extends to_trail : is_trail p : Prop := (support_nodup : p.support.nodup) /-- A *circuit* at `u : V` is a nonempty trail beginning and ending at `u`. -/ structure is_circuit {u : V} (p : G.walk u u) extends to_trail : is_trail p : Prop := (ne_nil : p ≠ nil) /-- A *cycle* at `u : V` is a circuit at `u` whose only repeating vertex is `u` (which appears exactly twice). -/ structure is_cycle {u : V} (p : G.walk u u) extends to_circuit : is_circuit p : Prop := (support_nodup : p.support.tail.nodup) lemma is_trail_def {u v : V} (p : G.walk u v) : p.is_trail ↔ p.edges.nodup := ⟨is_trail.edges_nodup, λ h, ⟨h⟩⟩ @[simp] lemma is_trail_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).is_trail ↔ p.is_trail := by { subst_vars, refl } lemma is_path.mk' {u v : V} {p : G.walk u v} (h : p.support.nodup) : is_path p := ⟨⟨edges_nodup_of_support_nodup h⟩, h⟩ lemma is_path_def {u v : V} (p : G.walk u v) : p.is_path ↔ p.support.nodup := ⟨is_path.support_nodup, is_path.mk'⟩ @[simp] lemma is_path_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).is_path ↔ p.is_path := by { subst_vars, refl } lemma is_circuit_def {u : V} (p : G.walk u u) : p.is_circuit ↔ is_trail p ∧ p ≠ nil := iff.intro (λ h, ⟨h.1, h.2⟩) (λ h, ⟨h.1, h.2⟩) @[simp] lemma is_circuit_copy {u u'} (p : G.walk u u) (hu : u = u') : (p.copy hu hu).is_circuit ↔ p.is_circuit := by { subst_vars, refl } lemma is_cycle_def {u : V} (p : G.walk u u) : p.is_cycle ↔ is_trail p ∧ p ≠ nil ∧ p.support.tail.nodup := iff.intro (λ h, ⟨h.1.1, h.1.2, h.2⟩) (λ h, ⟨⟨h.1, h.2.1⟩, h.2.2⟩) @[simp] lemma is_cycle_copy {u u'} (p : G.walk u u) (hu : u = u') : (p.copy hu hu).is_cycle ↔ p.is_cycle := by { subst_vars, refl } @[simp] lemma is_trail.nil {u : V} : (nil : G.walk u u).is_trail := ⟨by simp [edges]⟩ lemma is_trail.of_cons {u v w : V} {h : G.adj u v} {p : G.walk v w} : (cons h p).is_trail → p.is_trail := by simp [is_trail_def] @[simp] lemma cons_is_trail_iff {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).is_trail ↔ p.is_trail ∧ ⟦(u, v)⟧ ∉ p.edges := by simp [is_trail_def, and_comm] lemma is_trail.reverse {u v : V} (p : G.walk u v) (h : p.is_trail) : p.reverse.is_trail := by simpa [is_trail_def] using h @[simp] lemma reverse_is_trail_iff {u v : V} (p : G.walk u v) : p.reverse.is_trail ↔ p.is_trail := by split; { intro h, convert h.reverse _, try { rw reverse_reverse } } lemma is_trail.of_append_left {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_trail) : p.is_trail := by { rw [is_trail_def, edges_append, list.nodup_append] at h, exact ⟨h.1⟩ } lemma is_trail.of_append_right {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_trail) : q.is_trail := by { rw [is_trail_def, edges_append, list.nodup_append] at h, exact ⟨h.2.1⟩ } lemma is_trail.count_edges_le_one [decidable_eq V] {u v : V} {p : G.walk u v} (h : p.is_trail) (e : sym2 V) : p.edges.count e ≤ 1 := list.nodup_iff_count_le_one.mp h.edges_nodup e lemma is_trail.count_edges_eq_one [decidable_eq V] {u v : V} {p : G.walk u v} (h : p.is_trail) {e : sym2 V} (he : e ∈ p.edges) : p.edges.count e = 1 := list.count_eq_one_of_mem h.edges_nodup he @[simp] lemma is_path.nil {u : V} : (nil : G.walk u u).is_path := by { fsplit; simp } lemma is_path.of_cons {u v w : V} {h : G.adj u v} {p : G.walk v w} : (cons h p).is_path → p.is_path := by simp [is_path_def] @[simp] lemma cons_is_path_iff {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).is_path ↔ p.is_path ∧ u ∉ p.support := by split; simp [is_path_def] { contextual := tt } lemma is_path.reverse {u v : V} {p : G.walk u v} (h : p.is_path) : p.reverse.is_path := by simpa [is_path_def] using h @[simp] lemma is_path_reverse_iff {u v : V} (p : G.walk u v) : p.reverse.is_path ↔ p.is_path := by split; intro h; convert h.reverse; simp lemma is_path.of_append_left {u v w : V} {p : G.walk u v} {q : G.walk v w} : (p.append q).is_path → p.is_path := by { simp only [is_path_def, support_append], exact list.nodup.of_append_left } lemma is_path.of_append_right {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_path) : q.is_path := begin rw ←is_path_reverse_iff at h ⊢, rw reverse_append at h, apply h.of_append_left, end @[simp] lemma is_cycle.not_of_nil {u : V} : ¬ (nil : G.walk u u).is_cycle := λ h, h.ne_nil rfl /-! ### Walk decompositions -/ section walk_decomp variables [decidable_eq V] /-- Given a vertex in the support of a path, give the path up until (and including) that vertex. -/ def take_until : Π {v w : V} (p : G.walk v w) (u : V) (h : u ∈ p.support), G.walk v u | v w nil u h := by rw mem_support_nil_iff.mp h | v w (cons r p) u h := if hx : v = u then by subst u else cons r (take_until p _ $ h.cases_on (λ h', (hx h'.symm).elim) id) /-- Given a vertex in the support of a path, give the path from (and including) that vertex to the end. In other words, drop vertices from the front of a path until (and not including) that vertex. -/ def drop_until : Π {v w : V} (p : G.walk v w) (u : V) (h : u ∈ p.support), G.walk u w | v w nil u h := by rw mem_support_nil_iff.mp h | v w (cons r p) u h := if hx : v = u then by { subst u, exact cons r p } else drop_until p _ $ h.cases_on (λ h', (hx h'.symm).elim) id /-- The `take_until` and `drop_until` functions split a walk into two pieces. The lemma `count_support_take_until_eq_one` specifies where this split occurs. -/ @[simp] lemma take_spec {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).append (p.drop_until u h) = p := begin induction p, { rw mem_support_nil_iff at h, subst u, refl, }, { obtain (rfl|h) := h, { simp! }, { simp! only, split_ifs with h'; subst_vars; simp [*], } }, end lemma mem_support_iff_exists_append {V : Type u} {G : simple_graph V} {u v w : V} {p : G.walk u v} : w ∈ p.support ↔ ∃ (q : G.walk u w) (r : G.walk w v), p = q.append r := begin classical, split, { exact λ h, ⟨_, _, (p.take_spec h).symm⟩ }, { rintro ⟨q, r, rfl⟩, simp only [mem_support_append_iff, end_mem_support, start_mem_support, or_self], }, end @[simp] lemma count_support_take_until_eq_one {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).support.count u = 1 := begin induction p, { rw mem_support_nil_iff at h, subst u, simp!, }, { obtain (rfl|h) := h, { simp! }, { simp! only, split_ifs with h'; rw eq_comm at h'; subst_vars; simp! [*, list.count_cons], } }, end lemma count_edges_take_until_le_one {u v w : V} (p : G.walk v w) (h : u ∈ p.support) (x : V) : (p.take_until u h).edges.count ⟦(u, x)⟧ ≤ 1 := begin induction p with u' u' v' w' ha p' ih, { rw mem_support_nil_iff at h, subst u, simp!, }, { obtain (rfl|h) := h, { simp!, }, { simp! only, split_ifs with h', { subst h', simp, }, { rw [edges_cons, list.count_cons], split_ifs with h'', { rw sym2.eq_iff at h'', obtain (⟨rfl,rfl⟩|⟨rfl,rfl⟩) := h'', { exact (h' rfl).elim }, { cases p'; simp! } }, { apply ih, } } } }, end @[simp] lemma take_until_copy {u v w v' w'} (p : G.walk v w) (hv : v = v') (hw : w = w') (h : u ∈ (p.copy hv hw).support) : (p.copy hv hw).take_until u h = (p.take_until u (by { subst_vars, exact h })).copy hv rfl := by { subst_vars, refl } @[simp] lemma drop_until_copy {u v w v' w'} (p : G.walk v w) (hv : v = v') (hw : w = w') (h : u ∈ (p.copy hv hw).support) : (p.copy hv hw).drop_until u h = (p.drop_until u (by { subst_vars, exact h })).copy rfl hw := by { subst_vars, refl } lemma support_take_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).support ⊆ p.support := λ x hx, by { rw [← take_spec p h, mem_support_append_iff], exact or.inl hx } lemma support_drop_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).support ⊆ p.support := λ x hx, by { rw [← take_spec p h, mem_support_append_iff], exact or.inr hx } lemma darts_take_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).darts ⊆ p.darts := λ x hx, by { rw [← take_spec p h, darts_append, list.mem_append], exact or.inl hx } lemma darts_drop_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).darts ⊆ p.darts := λ x hx, by { rw [← take_spec p h, darts_append, list.mem_append], exact or.inr hx } lemma edges_take_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).edges ⊆ p.edges := list.map_subset _ (p.darts_take_until_subset h) lemma edges_drop_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).edges ⊆ p.edges := list.map_subset _ (p.darts_drop_until_subset h) lemma length_take_until_le {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).length ≤ p.length := begin have := congr_arg walk.length (p.take_spec h), rw [length_append] at this, exact nat.le.intro this, end lemma length_drop_until_le {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).length ≤ p.length := begin have := congr_arg walk.length (p.take_spec h), rw [length_append, add_comm] at this, exact nat.le.intro this, end protected lemma is_trail.take_until {u v w : V} {p : G.walk v w} (hc : p.is_trail) (h : u ∈ p.support) : (p.take_until u h).is_trail := is_trail.of_append_left (by rwa ← take_spec _ h at hc) protected lemma is_trail.drop_until {u v w : V} {p : G.walk v w} (hc : p.is_trail) (h : u ∈ p.support) : (p.drop_until u h).is_trail := is_trail.of_append_right (by rwa ← take_spec _ h at hc) protected lemma is_path.take_until {u v w : V} {p : G.walk v w} (hc : p.is_path) (h : u ∈ p.support) : (p.take_until u h).is_path := is_path.of_append_left (by rwa ← take_spec _ h at hc) protected lemma is_path.drop_until {u v w : V} (p : G.walk v w) (hc : p.is_path) (h : u ∈ p.support) : (p.drop_until u h).is_path := is_path.of_append_right (by rwa ← take_spec _ h at hc) /-- Rotate a loop walk such that it is centered at the given vertex. -/ def rotate {u v : V} (c : G.walk v v) (h : u ∈ c.support) : G.walk u u := (c.drop_until u h).append (c.take_until u h) @[simp] lemma support_rotate {u v : V} (c : G.walk v v) (h : u ∈ c.support) : (c.rotate h).support.tail ~r c.support.tail := begin simp only [rotate, tail_support_append], apply list.is_rotated.trans list.is_rotated_append, rw [←tail_support_append, take_spec], end lemma rotate_darts {u v : V} (c : G.walk v v) (h : u ∈ c.support) : (c.rotate h).darts ~r c.darts := begin simp only [rotate, darts_append], apply list.is_rotated.trans list.is_rotated_append, rw [←darts_append, take_spec], end lemma rotate_edges {u v : V} (c : G.walk v v) (h : u ∈ c.support) : (c.rotate h).edges ~r c.edges := (rotate_darts c h).map _ protected lemma is_trail.rotate {u v : V} {c : G.walk v v} (hc : c.is_trail) (h : u ∈ c.support) : (c.rotate h).is_trail := begin rw [is_trail_def, (c.rotate_edges h).perm.nodup_iff], exact hc.edges_nodup, end protected lemma is_circuit.rotate {u v : V} {c : G.walk v v} (hc : c.is_circuit) (h : u ∈ c.support) : (c.rotate h).is_circuit := begin refine ⟨hc.to_trail.rotate _, _⟩, cases c, { exact (hc.ne_nil rfl).elim, }, { intro hn, have hn' := congr_arg length hn, rw [rotate, length_append, add_comm, ← length_append, take_spec] at hn', simpa using hn', }, end protected lemma is_cycle.rotate {u v : V} {c : G.walk v v} (hc : c.is_cycle) (h : u ∈ c.support) : (c.rotate h).is_cycle := begin refine ⟨hc.to_circuit.rotate _, _⟩, rw list.is_rotated.nodup_iff (support_rotate _ _), exact hc.support_nodup, end end walk_decomp end walk /-! ### Type of paths -/ /-- The type for paths between two vertices. -/ abbreviation path (u v : V) := {p : G.walk u v // p.is_path} namespace path variables {G G'} @[simp] protected lemma is_path {u v : V} (p : G.path u v) : (p : G.walk u v).is_path := p.property @[simp] protected lemma is_trail {u v : V} (p : G.path u v) : (p : G.walk u v).is_trail := p.property.to_trail /-- The length-0 path at a vertex. -/ @[refl, simps] protected def nil {u : V} : G.path u u := ⟨walk.nil, walk.is_path.nil⟩ /-- The length-1 path between a pair of adjacent vertices. -/ @[simps] def singleton {u v : V} (h : G.adj u v) : G.path u v := ⟨walk.cons h walk.nil, by simp [h.ne]⟩ lemma mk_mem_edges_singleton {u v : V} (h : G.adj u v) : ⟦(u, v)⟧ ∈ (singleton h : G.walk u v).edges := by simp [singleton] /-- The reverse of a path is another path. See also `simple_graph.walk.reverse`. -/ @[symm, simps] def reverse {u v : V} (p : G.path u v) : G.path v u := ⟨walk.reverse p, p.property.reverse⟩ lemma count_support_eq_one [decidable_eq V] {u v w : V} {p : G.path u v} (hw : w ∈ (p : G.walk u v).support) : (p : G.walk u v).support.count w = 1 := list.count_eq_one_of_mem p.property.support_nodup hw lemma count_edges_eq_one [decidable_eq V] {u v : V} {p : G.path u v} (e : sym2 V) (hw : e ∈ (p : G.walk u v).edges) : (p : G.walk u v).edges.count e = 1 := list.count_eq_one_of_mem p.property.to_trail.edges_nodup hw @[simp] lemma nodup_support {u v : V} (p : G.path u v) : (p : G.walk u v).support.nodup := (walk.is_path_def _).mp p.property lemma loop_eq {v : V} (p : G.path v v) : p = path.nil := begin obtain (p|p) := p, { refl }, { simpa using p_property }, end lemma not_mem_edges_of_loop {v : V} {e : sym2 V} {p : G.path v v} : ¬ e ∈ (p : G.walk v v).edges := by simp [p.loop_eq] lemma cons_is_cycle {u v : V} (p : G.path v u) (h : G.adj u v) (he : ¬ ⟦(u, v)⟧ ∈ (p : G.walk v u).edges) : (walk.cons h ↑p).is_cycle := by simp [walk.is_cycle_def, walk.cons_is_trail_iff, he] end path /-! ### Walks to paths -/ namespace walk variables {G} [decidable_eq V] /-- Given a walk, produces a walk from it by bypassing subwalks between repeated vertices. The result is a path, as shown in `simple_graph.walk.bypass_is_path`. This is packaged up in `simple_graph.walk.to_path`. -/ def bypass : Π {u v : V}, G.walk u v → G.walk u v | u v nil := nil | u v (cons ha p) := let p' := p.bypass in if hs : u ∈ p'.support then p'.drop_until u hs else cons ha p' @[simp] lemma bypass_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).bypass = p.bypass.copy hu hv := by { subst_vars, refl } lemma bypass_is_path {u v : V} (p : G.walk u v) : p.bypass.is_path := begin induction p, { simp!, }, { simp only [bypass], split_ifs, { apply is_path.drop_until, assumption, }, { simp [*, cons_is_path_iff], } }, end lemma length_bypass_le {u v : V} (p : G.walk u v) : p.bypass.length ≤ p.length := begin induction p, { refl }, { simp only [bypass], split_ifs, { transitivity, apply length_drop_until_le, rw [length_cons], exact le_add_right p_ih, }, { rw [length_cons, length_cons], exact add_le_add_right p_ih 1, } }, end /-- Given a walk, produces a path with the same endpoints using `simple_graph.walk.bypass`. -/ def to_path {u v : V} (p : G.walk u v) : G.path u v := ⟨p.bypass, p.bypass_is_path⟩ lemma support_bypass_subset {u v : V} (p : G.walk u v) : p.bypass.support ⊆ p.support := begin induction p, { simp!, }, { simp! only, split_ifs, { apply list.subset.trans (support_drop_until_subset _ _), apply list.subset_cons_of_subset, assumption, }, { rw support_cons, apply list.cons_subset_cons, assumption, }, }, end lemma support_to_path_subset {u v : V} (p : G.walk u v) : (p.to_path : G.walk u v).support ⊆ p.support := support_bypass_subset _ lemma darts_bypass_subset {u v : V} (p : G.walk u v) : p.bypass.darts ⊆ p.darts := begin induction p, { simp!, }, { simp! only, split_ifs, { apply list.subset.trans (darts_drop_until_subset _ _), apply list.subset_cons_of_subset _ p_ih, }, { rw darts_cons, exact list.cons_subset_cons _ p_ih, }, }, end lemma edges_bypass_subset {u v : V} (p : G.walk u v) : p.bypass.edges ⊆ p.edges := list.map_subset _ p.darts_bypass_subset lemma darts_to_path_subset {u v : V} (p : G.walk u v) : (p.to_path : G.walk u v).darts ⊆ p.darts := darts_bypass_subset _ lemma edges_to_path_subset {u v : V} (p : G.walk u v) : (p.to_path : G.walk u v).edges ⊆ p.edges := edges_bypass_subset _ end walk /-! ### Mapping paths -/ namespace walk variables {G G' G''} /-- Given a graph homomorphism, map walks to walks. -/ protected def map (f : G →g G') : Π {u v : V}, G.walk u v → G'.walk (f u) (f v) | _ _ nil := nil | _ _ (cons h p) := cons (f.map_adj h) (map p) variables (f : G →g G') (f' : G' →g G'') {u v u' v' : V} (p : G.walk u v) @[simp] lemma map_nil : (nil : G.walk u u).map f = nil := rfl @[simp] lemma map_cons {w : V} (h : G.adj w u) : (cons h p).map f = cons (f.map_adj h) (p.map f) := rfl @[simp] lemma map_copy (hu : u = u') (hv : v = v') : (p.copy hu hv).map f = (p.map f).copy (by rw hu) (by rw hv) := by { subst_vars, refl } @[simp] lemma map_id (p : G.walk u v) : p.map hom.id = p := by { induction p; simp [*] } @[simp] lemma map_map : (p.map f).map f' = p.map (f'.comp f) := by { induction p; simp [*] } /-- Unlike categories, for graphs vertex equality is an important notion, so needing to be able to to work with equality of graph homomorphisms is a necessary evil. -/ lemma map_eq_of_eq {f : G →g G'} (f' : G →g G') (h : f = f') : p.map f = (p.map f').copy (by rw h) (by rw h) := by { subst_vars, refl } @[simp] lemma length_map : (p.map f).length = p.length := by induction p; simp [*] lemma map_append {u v w : V} (p : G.walk u v) (q : G.walk v w) : (p.append q).map f = (p.map f).append (q.map f) := by induction p; simp [*] @[simp] lemma reverse_map : (p.map f).reverse = p.reverse.map f := by induction p; simp [map_append, *] @[simp] lemma support_map : (p.map f).support = p.support.map f := by induction p; simp [*] @[simp] lemma darts_map : (p.map f).darts = p.darts.map f.map_dart := by induction p; simp [*] @[simp] lemma edges_map : (p.map f).edges = p.edges.map (sym2.map f) := by induction p; simp [*] variables {p f} lemma map_is_path_of_injective (hinj : function.injective f) (hp : p.is_path) : (p.map f).is_path := begin induction p with w u v w huv hvw ih, { simp, }, { rw walk.cons_is_path_iff at hp, simp [ih hp.1], intros x hx hf, cases hinj hf, exact hp.2 hx, }, end protected lemma is_path.of_map {f : G →g G'} (hp : (p.map f).is_path) : p.is_path := begin induction p with w u v w huv hvw ih, { simp }, { rw [map_cons, walk.cons_is_path_iff, support_map] at hp, rw walk.cons_is_path_iff, cases hp with hp1 hp2, refine ⟨ih hp1, _⟩, contrapose! hp2, exact list.mem_map_of_mem f hp2, } end lemma map_is_path_iff_of_injective (hinj : function.injective f) : (p.map f).is_path ↔ p.is_path := ⟨is_path.of_map, map_is_path_of_injective hinj⟩ variables (p f) lemma map_injective_of_injective {f : G →g G'} (hinj : function.injective f) (u v : V) : function.injective (walk.map f : G.walk u v → G'.walk (f u) (f v)) := begin intros p p' h, induction p with _ _ _ _ _ _ ih generalizing p', { cases p', { refl }, simpa using h, }, { induction p', { simpa using h, }, { simp only [map_cons] at h, cases hinj h.1, simp only [eq_self_iff_true, heq_iff_eq, true_and], apply ih, simpa using h.2, } }, end end walk namespace path variables {G G'} /-- Given an injective graph homomorphism, map paths to paths. -/ @[simps] protected def map (f : G →g G') (hinj : function.injective f) {u v : V} (p : G.path u v) : G'.path (f u) (f v) := ⟨walk.map f p, walk.map_is_path_of_injective hinj p.2⟩ lemma map_injective {f : G →g G'} (hinj : function.injective f) (u v : V) : function.injective (path.map f hinj : G.path u v → G'.path (f u) (f v)) := begin rintros ⟨p, hp⟩ ⟨p', hp'⟩ h, simp only [path.map, subtype.coe_mk] at h, simp [walk.map_injective_of_injective hinj u v h], end /-- Given a graph embedding, map paths to paths. -/ @[simps] protected def map_embedding (f : G ↪g G') {u v : V} (p : G.path u v) : G'.path (f u) (f v) := path.map f.to_hom f.injective p lemma map_embedding_injective (f : G ↪g G') (u v : V) : function.injective (path.map_embedding f : G.path u v → G'.path (f u) (f v)) := map_injective f.injective u v end path /-! ## Deleting edges -/ namespace walk variables {G} /-- Given a walk that avoids a set of edges, produce a walk in the graph with those edges deleted. -/ @[simp] def to_delete_edges (s : set (sym2 V)) : Π {v w : V} (p : G.walk v w) (hp : ∀ e, e ∈ p.edges → ¬ e ∈ s), (G.delete_edges s).walk v w | _ _ nil _ := nil | _ _ (cons' u v w huv p) hp := cons ((G.delete_edges_adj _ _ _).mpr ⟨huv, hp ⟦(u, v)⟧ (by simp)⟩) (p.to_delete_edges (λ e he, hp e (by simp [he]))) /-- Given a walk that avoids an edge, create a walk in the subgraph with that edge deleted. This is an abbreviation for `simple_graph.walk.to_delete_edges`. -/ abbreviation to_delete_edge {v w : V} (e : sym2 V) (p : G.walk v w) (hp : e ∉ p.edges) : (G.delete_edges {e}).walk v w := p.to_delete_edges {e} (λ e', by { contrapose!, simp [hp] { contextual := tt } }) @[simp] lemma map_to_delete_edges_eq (s : set (sym2 V)) {v w : V} {p : G.walk v w} (hp) : walk.map (hom.map_spanning_subgraphs (G.delete_edges_le s)) (p.to_delete_edges s hp) = p := by induction p; simp [*] lemma is_path.to_delete_edges (s : set (sym2 V)) {v w : V} {p : G.walk v w} (h : p.is_path) (hp) : (p.to_delete_edges s hp).is_path := by { rw ← map_to_delete_edges_eq s hp at h, exact h.of_map } @[simp] lemma to_delete_edges_copy (s : set (sym2 V)) {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') (h) : (p.copy hu hv).to_delete_edges s h = (p.to_delete_edges s (by { subst_vars, exact h })).copy hu hv := by { subst_vars, refl } end walk /-! ## `reachable` and `connected` -/ /-- Two vertices are *reachable* if there is a walk between them. This is equivalent to `relation.refl_trans_gen` of `G.adj`. See `simple_graph.reachable_iff_refl_trans_gen`. -/ def reachable (u v : V) : Prop := nonempty (G.walk u v) variables {G} lemma reachable_iff_nonempty_univ {u v : V} : G.reachable u v ↔ (set.univ : set (G.walk u v)).nonempty := set.nonempty_iff_univ_nonempty protected lemma reachable.elim {p : Prop} {u v : V} (h : G.reachable u v) (hp : G.walk u v → p) : p := nonempty.elim h hp protected lemma reachable.elim_path {p : Prop} {u v : V} (h : G.reachable u v) (hp : G.path u v → p) : p := begin classical, exact h.elim (λ q, hp q.to_path), end @[refl] protected lemma reachable.refl (u : V) : G.reachable u u := by { fsplit, refl } protected lemma reachable.rfl {u : V} : G.reachable u u := reachable.refl _ @[symm] protected lemma reachable.symm {u v : V} (huv : G.reachable u v) : G.reachable v u := huv.elim (λ p, ⟨p.reverse⟩) @[trans] protected lemma reachable.trans {u v w : V} (huv : G.reachable u v) (hvw : G.reachable v w) : G.reachable u w := huv.elim (λ puv, hvw.elim (λ pvw, ⟨puv.append pvw⟩)) lemma reachable_iff_refl_trans_gen (u v : V) : G.reachable u v ↔ relation.refl_trans_gen G.adj u v := begin split, { rintro ⟨h⟩, induction h, { refl, }, { exact (relation.refl_trans_gen.single h_h).trans h_ih, }, }, { intro h, induction h with _ _ _ ha hr, { refl, }, { exact reachable.trans hr ⟨walk.cons ha walk.nil⟩, }, }, end variables (G) lemma reachable_is_equivalence : equivalence G.reachable := mk_equivalence _ (@reachable.refl _ G) (@reachable.symm _ G) (@reachable.trans _ G) /-- The equivalence relation on vertices given by `simple_graph.reachable`. -/ def reachable_setoid : setoid V := setoid.mk _ G.reachable_is_equivalence /-- A graph is preconnected if every pair of vertices is reachable from one another. -/ def preconnected : Prop := ∀ (u v : V), G.reachable u v lemma preconnected.map {G : simple_graph V} {H : simple_graph V'} (f : G →g H) (hf : surjective f) (hG : G.preconnected) : H.preconnected := hf.forall₂.2 $ λ a b, (hG _ _).map $ walk.map _ lemma iso.preconnected_iff {G : simple_graph V} {H : simple_graph V'} (e : G ≃g H) : G.preconnected ↔ H.preconnected := ⟨preconnected.map e.to_hom e.to_equiv.surjective, preconnected.map e.symm.to_hom e.symm.to_equiv.surjective⟩ /-- A graph is connected if it's preconnected and contains at least one vertex. This follows the convention observed by mathlib that something is connected iff it has exactly one connected component. There is a `has_coe_to_fun` instance so that `h u v` can be used instead of `h.preconnected u v`. -/ @[protect_proj, mk_iff] structure connected : Prop := (preconnected : G.preconnected) [nonempty : nonempty V] instance : has_coe_to_fun G.connected (λ _, Π (u v : V), G.reachable u v) := ⟨λ h, h.preconnected⟩ lemma connected.map {G : simple_graph V} {H : simple_graph V'} (f : G →g H) (hf : surjective f) (hG : G.connected) : H.connected := by { haveI := hG.nonempty.map f, exact ⟨hG.preconnected.map f hf⟩ } lemma iso.connected_iff {G : simple_graph V} {H : simple_graph V'} (e : G ≃g H) : G.connected ↔ H.connected := ⟨connected.map e.to_hom e.to_equiv.surjective, connected.map e.symm.to_hom e.symm.to_equiv.surjective⟩ /-- The quotient of `V` by the `simple_graph.reachable` relation gives the connected components of a graph. -/ def connected_component := quot G.reachable /-- Gives the connected component containing a particular vertex. -/ def connected_component_mk (v : V) : G.connected_component := quot.mk G.reachable v @[simps] instance connected_component.inhabited [inhabited V] : inhabited G.connected_component := ⟨G.connected_component_mk default⟩ section connected_component variables {G} @[elab_as_eliminator] protected lemma connected_component.ind {β : G.connected_component → Prop} (h : ∀ (v : V), β (G.connected_component_mk v)) (c : G.connected_component) : β c := quot.ind h c @[elab_as_eliminator] protected lemma connected_component.ind₂ {β : G.connected_component → G.connected_component → Prop} (h : ∀ (v w : V), β (G.connected_component_mk v) (G.connected_component_mk w)) (c d : G.connected_component) : β c d := quot.induction_on₂ c d h protected lemma connected_component.sound {v w : V} : G.reachable v w → G.connected_component_mk v = G.connected_component_mk w := quot.sound protected lemma connected_component.exact {v w : V} : G.connected_component_mk v = G.connected_component_mk w → G.reachable v w := @quotient.exact _ G.reachable_setoid _ _ @[simp] protected lemma connected_component.eq {v w : V} : G.connected_component_mk v = G.connected_component_mk w ↔ G.reachable v w := @quotient.eq _ G.reachable_setoid _ _ /-- The `connected_component` specialization of `quot.lift`. Provides the stronger assumption that the vertices are connected by a path. -/ protected def connected_component.lift {β : Sort*} (f : V → β) (h : ∀ (v w : V) (p : G.walk v w), p.is_path → f v = f w) : G.connected_component → β := quot.lift f (λ v w (h' : G.reachable v w), h'.elim_path (λ hp, h v w hp hp.2)) @[simp] protected lemma connected_component.lift_mk {β : Sort*} {f : V → β} {h : ∀ (v w : V) (p : G.walk v w), p.is_path → f v = f w} {v : V} : connected_component.lift f h (G.connected_component_mk v) = f v := rfl protected lemma connected_component.«exists» {p : G.connected_component → Prop} : (∃ (c : G.connected_component), p c) ↔ ∃ v, p (G.connected_component_mk v) := (surjective_quot_mk G.reachable).exists protected lemma connected_component.«forall» {p : G.connected_component → Prop} : (∀ (c : G.connected_component), p c) ↔ ∀ v, p (G.connected_component_mk v) := (surjective_quot_mk G.reachable).forall lemma preconnected.subsingleton_connected_component (h : G.preconnected) : subsingleton G.connected_component := ⟨connected_component.ind₂ (λ v w, connected_component.sound (h v w))⟩ end connected_component variables {G} /-- A subgraph is connected if it is connected as a simple graph. -/ abbreviation subgraph.connected (H : G.subgraph) : Prop := H.coe.connected lemma preconnected.set_univ_walk_nonempty (hconn : G.preconnected) (u v : V) : (set.univ : set (G.walk u v)).nonempty := by { rw ← set.nonempty_iff_univ_nonempty, exact hconn u v } lemma connected.set_univ_walk_nonempty (hconn : G.connected) (u v : V) : (set.univ : set (G.walk u v)).nonempty := hconn.preconnected.set_univ_walk_nonempty u v /-! ### Walks of a given length -/ section walk_counting lemma set_walk_self_length_zero_eq (u : V) : {p : G.walk u u | p.length = 0} = {walk.nil} := by { ext p, simp } lemma set_walk_length_zero_eq_of_ne {u v : V} (h : u ≠ v) : {p : G.walk u v | p.length = 0} = ∅ := begin ext p, simp only [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ h', absurd (walk.eq_of_length_eq_zero h') h, end lemma set_walk_length_succ_eq (u v : V) (n : ℕ) : {p : G.walk u v | p.length = n.succ} = ⋃ (w : V) (h : G.adj u w), walk.cons h '' {p' : G.walk w v | p'.length = n} := begin ext p, cases p with _ _ w _ huw pwv, { simp [eq_comm], }, { simp only [nat.succ_eq_add_one, set.mem_set_of_eq, walk.length_cons, add_left_inj, set.mem_Union, set.mem_image, exists_prop], split, { rintro rfl, exact ⟨w, huw, pwv, rfl, rfl, heq.rfl⟩, }, { rintro ⟨w, huw, pwv, rfl, rfl, rfl⟩, refl, } }, end variables (G) [fintype V] [decidable_rel G.adj] [decidable_eq V] /-- The `finset` of length-`n` walks from `u` to `v`. This is used to give `{p : G.walk u v | p.length = n}` a `fintype` instance, and it can also be useful as a recursive description of this set when `V` is finite. See `simple_graph.coe_finset_walk_length_eq` for the relationship between this `finset` and the set of length-`n` walks. -/ def finset_walk_length : Π (n : ℕ) (u v : V), finset (G.walk u v) | 0 u v := if h : u = v then by { subst u, exact {walk.nil} } else ∅ | (n+1) u v := finset.univ.bUnion (λ (w : V), if h : G.adj u w then (finset_walk_length n w v).map ⟨λ p, walk.cons h p, λ p q, by simp⟩ else ∅) lemma coe_finset_walk_length_eq (n : ℕ) (u v : V) : (G.finset_walk_length n u v : set (G.walk u v)) = {p : G.walk u v | p.length = n} := begin induction n with n ih generalizing u v, { obtain rfl | huv := eq_or_ne u v; simp [finset_walk_length, set_walk_length_zero_eq_of_ne, *], }, { simp only [finset_walk_length, set_walk_length_succ_eq, finset.coe_bUnion, finset.mem_coe, finset.mem_univ, set.Union_true], ext p, simp only [set.mem_Union, finset.mem_coe, set.mem_image, set.mem_set_of_eq], congr' 2, ext w, simp only [set.ext_iff, finset.mem_coe, set.mem_set_of_eq] at ih, split_ifs with huw; simp [huw, ih], }, end variables {G} lemma walk.length_eq_of_mem_finset_walk_length {n : ℕ} {u v : V} (p : G.walk u v) : p ∈ G.finset_walk_length n u v → p.length = n := (set.ext_iff.mp (G.coe_finset_walk_length_eq n u v) p).mp variables (G) instance fintype_set_walk_length (u v : V) (n : ℕ) : fintype {p : G.walk u v | p.length = n} := fintype.subtype (G.finset_walk_length n u v) $ λ p, by rw [←finset.mem_coe, coe_finset_walk_length_eq] lemma set_walk_length_to_finset_eq (n : ℕ) (u v : V) : {p : G.walk u v | p.length = n}.to_finset = G.finset_walk_length n u v := by { ext p, simp [←coe_finset_walk_length_eq] } /- See `simple_graph.adj_matrix_pow_apply_eq_card_walk` for the cardinality in terms of the `n`th power of the adjacency matrix. -/ lemma card_set_walk_length_eq (u v : V) (n : ℕ) : fintype.card {p : G.walk u v | p.length = n} = (G.finset_walk_length n u v).card := fintype.card_of_subtype (G.finset_walk_length n u v) $ λ p, by rw [←finset.mem_coe, coe_finset_walk_length_eq] end walk_counting end simple_graph
70d2b73f99dbf8de280fdf6c390d6741fde37bea
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/additive_tests.lean
33cc46a39c4fc708a61210f8084264c846548ed4
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,429
lean
import control variables x y z : ℚ #exit example (e1 : x < 1*y) (e2 : z < 1*y) (e3 : x + z > 3*y) (e4 : x + z >0) : false := by polya e1 e2 e3 e4 /-exps ← monad.mapm get_local [`e1, `e2, `e3, `e4], bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_exprs, (_, bb) ← return $ add_new_ineqs bb, bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, trace pf, apply pf-/ --triv example (e1 : x < 2*y) (e2 : z ≤ 4*y) (e3 : 1*x + 1*z > 6*y) : false := by polya e1 e2 e3 /-do exps ← monad.mapm get_local [`e1, `e2, `e3], bb ← add_proofs_to_blackboard blackboard.mk_empty exps, bb.trace_exprs, (_, bb) ← return $ add_new_ineqs bb, bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, apply pf-/ --set_option pp.all true def g (e1 : x = 2*y) (e2 : x > 1*y) (e3 : y < 0) : false := by polya e1 e2 e3 /-by do e1 ← get_local `e1, e2 ← get_local `e2, e3 ← get_local `e3,-- e4 ← get_local `e4, bb ← add_proofs_to_blackboard blackboard.mk_empty [e1, e2], bb.trace, bb ← add_proofs_to_blackboard bb [e3], bb.trace, trace $ ("contr found", bb.contr_found), pf ← bb.contr.reconstruct, trace pf, apply pf-/ #print g --set_option profiler true example (e1 : 4*x+7*z = 0) (e2 : (-12)*x + (-3)*y ≤ 0) (e3 : 17*x + (-17)*y + 14*z = 0) (e4 : 9*y + (-17)*z < 0) : false := by polya e1 e2 e3 e4
d1d2b7db5e4686445f301080a720deed14b582c5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Ring/limits.lean
c59aaa2422e9d061d59ed98da1b707de6a7ebaf1
[ "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
18,609
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.ring.pi import algebra.category.Ring.basic import algebra.category.Group.limits import ring_theory.subring.basic /-! # The category of (commutative) rings has all limits > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ /- We use the following trick a lot of times in this file.-/ /-- Some definitions may be extremely slow to elaborate, when the target type to be constructed is complicated and when the type of the term given in the definition is also complicated and does not obviously match the target type. In this case, instead of just giving the term, prefixing it with `by apply` may speed up things considerably as the types are not elaborated in the same order. -/ library_note "change elaboration strategy with `by apply`" open category_theory open category_theory.limits universes v u noncomputable theory namespace SemiRing variables {J : Type v} [small_category J] instance semiring_obj (F : J ⥤ SemiRing.{max v u}) (j) : semiring ((F ⋙ forget SemiRing).obj j) := by { change semiring (F.obj j), apply_instance } /-- The flat sections of a functor into `SemiRing` form a subsemiring of all sections. -/ def sections_subsemiring (F : J ⥤ SemiRing.{max v u}) : subsemiring (Π j, F.obj j) := { carrier := (F ⋙ forget SemiRing).sections, ..(AddMon.sections_add_submonoid (F ⋙ forget₂ SemiRing AddCommMon.{max v u} ⋙ forget₂ AddCommMon AddMon.{max v u})), ..(Mon.sections_submonoid (F ⋙ forget₂ SemiRing Mon.{max v u})) } instance limit_semiring (F : J ⥤ SemiRing.{max v u}) : semiring (types.limit_cone (F ⋙ forget SemiRing.{max v u})).X := (sections_subsemiring F).to_semiring /-- `limit.π (F ⋙ forget SemiRing) j` as a `ring_hom`. -/ def limit_π_ring_hom (F : J ⥤ SemiRing.{max v u}) (j) : (types.limit_cone (F ⋙ forget SemiRing)).X →+* (F ⋙ forget SemiRing).obj j := { to_fun := (types.limit_cone (F ⋙ forget SemiRing)).π.app j, ..AddMon.limit_π_add_monoid_hom (F ⋙ forget₂ SemiRing AddCommMon.{max v u} ⋙ forget₂ AddCommMon AddMon.{max v u}) j, ..Mon.limit_π_monoid_hom (F ⋙ forget₂ SemiRing Mon.{max v u}) j, } namespace has_limits -- The next two definitions are used in the construction of `has_limits SemiRing`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `SemiRing`. (Internal use only; use the limits API.) -/ def limit_cone (F : J ⥤ SemiRing.{max v u}) : cone F := { X := SemiRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := limit_π_ring_hom F, naturality' := λ j j' f, ring_hom.coe_inj ((types.limit_cone (F ⋙ forget _)).π.naturality f) } } /-- Witness that the limit cone in `SemiRing` is a limit cone. (Internal use only; use the limits API.) -/ def limit_cone_is_limit (F : J ⥤ SemiRing.{max v u}) : is_limit (limit_cone F) := begin refine is_limit.of_faithful (forget SemiRing) (types.limit_cone_is_limit _) (λ s, ⟨_, _, _, _, _⟩) (λ s, rfl); tidy end end has_limits open has_limits /-- The category of rings has all limits. -/ @[irreducible] instance has_limits_of_size : has_limits_of_size.{v} SemiRing.{max v u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } instance has_limits : has_limits SemiRing.{u} := SemiRing.has_limits_of_size.{u u} /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommMon_preserves_limits_aux (F : J ⥤ SemiRing.{max v u}) : is_limit ((forget₂ SemiRing AddCommMon).map_cone (limit_cone F)) := by apply AddCommMon.limit_cone_is_limit (F ⋙ forget₂ SemiRing AddCommMon.{max v u}) /-- The forgetful functor from semirings to additive commutative monoids preserves all limits. -/ instance forget₂_AddCommMon_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ SemiRing AddCommMon.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommMon_preserves_limits_aux F) } } instance forget₂_AddCommMon_preserves_limits : preserves_limits (forget₂ SemiRing AddCommMon.{u}) := SemiRing.forget₂_AddCommMon_preserves_limits_of_size.{u u} /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_Mon_preserves_limits_aux (F : J ⥤ SemiRing.{max v u}) : is_limit ((forget₂ SemiRing Mon).map_cone (limit_cone F)) := by apply Mon.has_limits.limit_cone_is_limit (F ⋙ forget₂ SemiRing Mon.{max v u}) /-- The forgetful functor from semirings to monoids preserves all limits. -/ instance forget₂_Mon_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ SemiRing Mon.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_Mon_preserves_limits_aux F) } } instance forget₂_Mon_preserves_limits : preserves_limits (forget₂ SemiRing Mon.{u}) := SemiRing.forget₂_Mon_preserves_limits_of_size.{u u} /-- The forgetful functor from semirings to types preserves all limits. -/ instance forget_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget SemiRing.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (types.limit_cone_is_limit (F ⋙ forget _)) } } instance forget_preserves_limits : preserves_limits (forget SemiRing.{u}) := SemiRing.forget_preserves_limits_of_size.{u u} end SemiRing namespace CommSemiRing variables {J : Type v} [small_category J] instance comm_semiring_obj (F : J ⥤ CommSemiRing.{max v u}) (j) : comm_semiring ((F ⋙ forget CommSemiRing).obj j) := by { change comm_semiring (F.obj j), apply_instance } instance limit_comm_semiring (F : J ⥤ CommSemiRing.{max v u}) : comm_semiring (types.limit_cone (F ⋙ forget CommSemiRing.{max v u})).X := @subsemiring.to_comm_semiring (Π j, F.obj j) _ (SemiRing.sections_subsemiring (F ⋙ forget₂ CommSemiRing SemiRing.{max v u})) /-- We show that the forgetful functor `CommSemiRing ⥤ SemiRing` creates limits. All we need to do is notice that the limit point has a `comm_semiring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ CommSemiRing.{max v u}) : creates_limit F (forget₂ CommSemiRing SemiRing.{max v u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommSemiRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := by apply SemiRing.limit_π_ring_hom (F ⋙ forget₂ CommSemiRing SemiRing.{max v u}), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ CommSemiRing SemiRing.{max v u})).π.naturality, } }, valid_lift := by apply is_limit.unique_up_to_iso (SemiRing.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ CommSemiRing SemiRing.{max v u}) (by apply SemiRing.has_limits.limit_cone_is_limit _) (λ s, (SemiRing.has_limits.limit_cone_is_limit _).lift ((forget₂ _ SemiRing).map_cone s)) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommSemiRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ CommSemiRing.{max v u}) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommSemiRing SemiRing.{max v u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ CommSemiRing.{max v u}) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of rings has all limits. -/ @[irreducible] instance has_limits_of_size : has_limits_of_size.{v v} CommSemiRing.{max v u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommSemiRing SemiRing.{max v u}) } } instance has_limits : has_limits CommSemiRing.{u} := CommSemiRing.has_limits_of_size.{u u} /-- The forgetful functor from rings to semirings preserves all limits. -/ instance forget₂_SemiRing_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ CommSemiRing SemiRing.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } instance forget₂_SemiRing_preserves_limits : preserves_limits (forget₂ CommSemiRing SemiRing.{u}) := CommSemiRing.forget₂_SemiRing_preserves_limits_of_size.{u u} /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget CommSemiRing.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommSemiRing SemiRing) (forget SemiRing) } } instance forget_preserves_limits : preserves_limits (forget CommSemiRing.{u}) := CommSemiRing.forget_preserves_limits_of_size.{u u} end CommSemiRing namespace Ring variables {J : Type v} [small_category J] instance ring_obj (F : J ⥤ Ring.{max v u}) (j) : ring ((F ⋙ forget Ring).obj j) := by { change ring (F.obj j), apply_instance } /-- The flat sections of a functor into `Ring` form a subring of all sections. -/ def sections_subring (F : J ⥤ Ring.{max v u}) : subring (Π j, F.obj j) := { carrier := (F ⋙ forget Ring).sections, .. AddGroup.sections_add_subgroup (F ⋙ forget₂ Ring AddCommGroup.{max v u} ⋙ forget₂ AddCommGroup AddGroup.{max v u}), .. SemiRing.sections_subsemiring (F ⋙ forget₂ Ring SemiRing.{max v u}) } instance limit_ring (F : J ⥤ Ring.{max v u}) : ring (types.limit_cone (F ⋙ forget Ring.{max v u})).X := (sections_subring F).to_ring /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `ring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ Ring.{max v u}) : creates_limit F (forget₂ Ring SemiRing.{max v u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := Ring.of (types.limit_cone (F ⋙ forget _)).X, π := { app := by apply SemiRing.limit_π_ring_hom (F ⋙ forget₂ Ring SemiRing.{max v u}), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ Ring SemiRing.{max v u})).π.naturality, } }, valid_lift := by apply is_limit.unique_up_to_iso (SemiRing.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ Ring SemiRing.{max v u}) (by apply SemiRing.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `Ring`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ Ring.{max v u}) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ Ring SemiRing.{max v u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ Ring.{max v u}) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of rings has all limits. -/ @[irreducible] instance has_limits_of_size : has_limits_of_size.{v v} Ring.{max v u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ Ring SemiRing.{max v u}) } } instance has_limits : has_limits Ring.{u} := Ring.has_limits_of_size.{u u} /-- The forgetful functor from rings to semirings preserves all limits. -/ instance forget₂_SemiRing_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ Ring SemiRing.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } instance forget₂_SemiRing_preserves_limits : preserves_limits (forget₂ Ring SemiRing.{u}) := Ring.forget₂_SemiRing_preserves_limits_of_size.{u u} /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommGroup_preserves_limits_aux (F : J ⥤ Ring.{max v u}) : is_limit ((forget₂ Ring AddCommGroup).map_cone (limit_cone F)) := by apply AddCommGroup.limit_cone_is_limit (F ⋙ forget₂ Ring AddCommGroup.{max v u}) /-- The forgetful functor from rings to additive commutative groups preserves all limits. -/ instance forget₂_AddCommGroup_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ Ring AddCommGroup.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommGroup_preserves_limits_aux F) } } instance forget₂_AddCommGroup_preserves_limits : preserves_limits (forget₂ Ring AddCommGroup.{u}) := Ring.forget₂_AddCommGroup_preserves_limits_of_size.{u u} /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget Ring.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ Ring SemiRing) (forget SemiRing.{max v u}) } } instance forget_preserves_limits : preserves_limits (forget Ring.{u}) := Ring.forget_preserves_limits_of_size.{u u} end Ring namespace CommRing variables {J : Type v} [small_category J] instance comm_ring_obj (F : J ⥤ CommRing.{max v u}) (j) : comm_ring ((F ⋙ forget CommRing).obj j) := by { change comm_ring (F.obj j), apply_instance } instance limit_comm_ring (F : J ⥤ CommRing.{max v u}) : comm_ring (types.limit_cone (F ⋙ forget CommRing.{max v u})).X := @subring.to_comm_ring (Π j, F.obj j) _ (Ring.sections_subring (F ⋙ forget₂ CommRing Ring.{max v u})) /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `comm_ring` instance available, and then reuse the existing limit. -/ instance (F : J ⥤ CommRing.{max v u}) : creates_limit F (forget₂ CommRing Ring.{max v u}) := /- A terse solution here would be ``` creates_limit_of_fully_faithful_of_iso (CommRing.of (limit (F ⋙ forget _))) (iso.refl _) ``` but it seems this would introduce additional identity morphisms in `limit.π`. -/ creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommRing.of (types.limit_cone (F ⋙ forget _)).X, π := { app := by apply SemiRing.limit_π_ring_hom (F ⋙ forget₂ CommRing Ring.{max v u} ⋙ forget₂ Ring SemiRing.{max v u}), naturality' := (SemiRing.has_limits.limit_cone (F ⋙ forget₂ _ Ring.{max v u} ⋙ forget₂ _ SemiRing.{max v u})).π.naturality } }, valid_lift := by apply is_limit.unique_up_to_iso (Ring.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ _ Ring.{max v u}) (by apply Ring.limit_cone_is_limit (F ⋙ forget₂ CommRing Ring.{max v u})) (λ s, (Ring.limit_cone_is_limit _).lift ((forget₂ _ Ring.{max v u}).map_cone s)) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone (F : J ⥤ CommRing.{max v u}) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommRing Ring.{max v u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit (F : J ⥤ CommRing.{max v u}) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of commutative rings has all limits. -/ @[irreducible] instance has_limits_of_size : has_limits_of_size.{v v} CommRing.{max v u} := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommRing Ring.{max v u}) } } instance has_limits : has_limits CommRing.{u} := CommRing.has_limits_of_size.{u u} /-- The forgetful functor from commutative rings to rings preserves all limits. (That is, the underlying rings could have been computed instead as limits in the category of rings.) -/ instance forget₂_Ring_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ CommRing Ring.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } instance forget₂_Ring_preserves_limits : preserves_limits (forget₂ CommRing Ring.{u}) := CommRing.forget₂_Ring_preserves_limits_of_size.{u u} /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_CommSemiRing_preserves_limits_aux (F : J ⥤ CommRing.{max v u}) : is_limit ((forget₂ CommRing CommSemiRing).map_cone (limit_cone F)) := by apply CommSemiRing.limit_cone_is_limit (F ⋙ forget₂ CommRing CommSemiRing.{max v u}) /-- The forgetful functor from commutative rings to commutative semirings preserves all limits. (That is, the underlying commutative semirings could have been computed instead as limits in the category of commutative semirings.) -/ instance forget₂_CommSemiRing_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget₂ CommRing CommSemiRing.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_CommSemiRing_preserves_limits_aux F) } } instance forget₂_CommSemiRing_preserves_limits : preserves_limits (forget₂ CommRing CommSemiRing.{u}) := CommRing.forget₂_CommSemiRing_preserves_limits_of_size.{u u} /-- The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits_of_size : preserves_limits_of_size.{v v} (forget CommRing.{max v u}) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommRing Ring) (forget Ring) } } instance forget_preserves_limits : preserves_limits (forget CommRing.{u}) := CommRing.forget_preserves_limits_of_size.{u u} end CommRing
1d78a746f04c0736d4219ff5ed277beca7ae4e21
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/group/defs.lean
ddc201b75a2cdb98b393fc990e403aad9727a532
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
29,653
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Simon Hudon, Mario Carneiro -/ import algebra.group.to_additive import tactic.basic /-! # Typeclasses for (semi)groups and monoids In this file we define typeclasses for algebraic structures with one binary operation. The classes are named `(add_)?(comm_)?(semigroup|monoid|group)`, where `add_` means that the class uses additive notation and `comm_` means that the class assumes that the binary operation is commutative. The file does not contain any lemmas except for * axioms of typeclasses restated in the root namespace; * lemmas required for instances. For basic lemmas about these classes see `algebra.group.basic`. We also introduce notation classes `has_scalar` and `has_vadd` for multiplicative and additive actions and register the following instances: - `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`; - `has_scalar ℕ M` for additive monoids `M`, and `has_scalar ℤ G` for additive groups `G`. ## Notation - `+`, `-`, `*`, `/`, `^` : the usual arithmetic operations; the underlying functions are `has_add.add`, `has_neg.neg`/`has_sub.sub`, `has_mul.mul`, `has_div.div`, and `has_pow.pow`. - `a • b` is used as notation for `has_scalar.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. -/ /-- Type class for the `+ᵥ` notation. -/ class has_vadd (G : Type*) (P : Type*) := (vadd : G → P → P) /-- Type class for the `-ᵥ` notation. -/ class has_vsub (G : out_param Type*) (P : Type*) := (vsub : P → P → G) /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ @[to_additive has_vadd] class has_scalar (M : Type*) (α : Type*) := (smul : M → α → α) infix ` +ᵥ `:65 := has_vadd.vadd infix ` -ᵥ `:65 := has_vsub.vsub infixr ` • `:73 := has_scalar.smul attribute [to_additive_reorder 1] has_pow attribute [to_additive_reorder 1 4] has_pow.pow attribute [to_additive has_scalar] has_pow attribute [to_additive has_scalar.smul] has_pow.pow set_option old_structure_cmd true universe u /- Additive "sister" structures. Example, add_semigroup mirrors semigroup. These structures exist just to help automation. In an alternative design, we could have the binary operation as an extra argument for semigroup, monoid, group, etc. However, the lemmas would be hard to index since they would not contain any constant. For example, mul_assoc would be lemma mul_assoc {α : Type u} {op : α → α → α} [semigroup α op] : ∀ a b c : α, op (op a b) c = op a (op b c) := semigroup.mul_assoc The simplifier cannot effectively use this lemma since the pattern for the left-hand-side would be ?op (?op ?a ?b) ?c Remark: we use a tactic for transporting theorems from the multiplicative fragment to the additive one. -/ section has_mul variables {G : Type u} [has_mul G] /-- `left_mul g` denotes left multiplication by `g` -/ @[to_additive "`left_add g` denotes left addition by `g`"] def left_mul : G → G → G := λ g : G, λ x : G, g * x /-- `right_mul g` denotes right multiplication by `g` -/ @[to_additive "`right_add g` denotes right addition by `g`"] def right_mul : G → G → G := λ g : G, λ x : G, x * g end has_mul /-- A semigroup is a type with an associative `(*)`. -/ @[protect_proj, ancestor has_mul, ext] class semigroup (G : Type u) extends has_mul G := (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) /-- An additive semigroup is a type with an associative `(+)`. -/ @[protect_proj, ancestor has_add, ext] class add_semigroup (G : Type u) extends has_add G := (add_assoc : ∀ a b c : G, a + b + c = a + (b + c)) attribute [to_additive] semigroup section semigroup variables {G : Type u} [semigroup G] @[no_rsimp, to_additive] lemma mul_assoc : ∀ a b c : G, a * b * c = a * (b * c) := semigroup.mul_assoc @[to_additive] instance semigroup.to_is_associative : is_associative G (*) := ⟨mul_assoc⟩ end semigroup /-- A commutative semigroup is a type with an associative commutative `(*)`. -/ @[protect_proj, ancestor semigroup, ext] class comm_semigroup (G : Type u) extends semigroup G := (mul_comm : ∀ a b : G, a * b = b * a) /-- A commutative additive semigroup is a type with an associative commutative `(+)`. -/ @[protect_proj, ancestor add_semigroup, ext] class add_comm_semigroup (G : Type u) extends add_semigroup G := (add_comm : ∀ a b : G, a + b = b + a) attribute [to_additive] comm_semigroup section comm_semigroup variables {G : Type u} [comm_semigroup G] @[no_rsimp, to_additive] lemma mul_comm : ∀ a b : G, a * b = b * a := comm_semigroup.mul_comm @[to_additive] instance comm_semigroup.to_is_commutative : is_commutative G (*) := ⟨mul_comm⟩ end comm_semigroup /-- A `left_cancel_semigroup` is a semigroup such that `a * b = a * c` implies `b = c`. -/ @[protect_proj, ancestor semigroup, ext] class left_cancel_semigroup (G : Type u) extends semigroup G := (mul_left_cancel : ∀ a b c : G, a * b = a * c → b = c) /-- An `add_left_cancel_semigroup` is an additive semigroup such that `a + b = a + c` implies `b = c`. -/ @[protect_proj, ancestor add_semigroup, ext] class add_left_cancel_semigroup (G : Type u) extends add_semigroup G := (add_left_cancel : ∀ a b c : G, a + b = a + c → b = c) attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup section left_cancel_semigroup variables {G : Type u} [left_cancel_semigroup G] {a b c : G} @[to_additive] lemma mul_left_cancel : a * b = a * c → b = c := left_cancel_semigroup.mul_left_cancel a b c @[to_additive] lemma mul_left_cancel_iff : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ @[to_additive] theorem mul_right_injective (a : G) : function.injective ((*) a) := λ b c, mul_left_cancel @[simp, to_additive] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c ↔ b = c := (mul_right_injective a).eq_iff @[to_additive] theorem mul_ne_mul_right (a : G) {b c : G} : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective a).ne_iff end left_cancel_semigroup /-- A `right_cancel_semigroup` is a semigroup such that `a * b = c * b` implies `a = c`. -/ @[protect_proj, ancestor semigroup, ext] class right_cancel_semigroup (G : Type u) extends semigroup G := (mul_right_cancel : ∀ a b c : G, a * b = c * b → a = c) /-- An `add_right_cancel_semigroup` is an additive semigroup such that `a + b = c + b` implies `a = c`. -/ @[protect_proj, ancestor add_semigroup, ext] class add_right_cancel_semigroup (G : Type u) extends add_semigroup G := (add_right_cancel : ∀ a b c : G, a + b = c + b → a = c) attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup section right_cancel_semigroup variables {G : Type u} [right_cancel_semigroup G] {a b c : G} @[to_additive] lemma mul_right_cancel : a * b = c * b → a = c := right_cancel_semigroup.mul_right_cancel a b c @[to_additive] lemma mul_right_cancel_iff : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ @[to_additive] theorem mul_left_injective (a : G) : function.injective (λ x, x * a) := λ b c, mul_right_cancel @[simp, to_additive] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a ↔ b = c := (mul_left_injective a).eq_iff @[to_additive] theorem mul_ne_mul_left (a : G) {b c : G} : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective a).ne_iff end right_cancel_semigroup /-- Typeclass for expressing that a type `M` with multiplication and a one satisfies `1 * a = a` and `a * 1 = a` for all `a : M`. -/ @[ancestor has_one has_mul] class mul_one_class (M : Type u) extends has_one M, has_mul M := (one_mul : ∀ (a : M), 1 * a = a) (mul_one : ∀ (a : M), a * 1 = a) /-- Typeclass for expressing that a type `M` with addition and a zero satisfies `0 + a = a` and `a + 0 = a` for all `a : M`. -/ @[ancestor has_zero has_add] class add_zero_class (M : Type u) extends has_zero M, has_add M := (zero_add : ∀ (a : M), 0 + a = a) (add_zero : ∀ (a : M), a + 0 = a) attribute [to_additive] mul_one_class @[ext, to_additive] lemma mul_one_class.ext {M : Type u} : ∀ ⦃m₁ m₂ : mul_one_class M⦄, m₁.mul = m₂.mul → m₁ = m₂ := begin rintros ⟨one₁, mul₁, one_mul₁, mul_one₁⟩ ⟨one₂, mul₂, one_mul₂, mul_one₂⟩ (rfl : mul₁ = mul₂), congr, exact (one_mul₂ one₁).symm.trans (mul_one₁ one₂), end section mul_one_class variables {M : Type u} [mul_one_class M] @[ematch, simp, to_additive] lemma one_mul : ∀ a : M, 1 * a = a := mul_one_class.one_mul @[ematch, simp, to_additive] lemma mul_one : ∀ a : M, a * 1 = a := mul_one_class.mul_one @[to_additive] instance mul_one_class.to_is_left_id : is_left_id M (*) 1 := ⟨ mul_one_class.one_mul ⟩ @[to_additive] instance mul_one_class.to_is_right_id : is_right_id M (*) 1 := ⟨ mul_one_class.mul_one ⟩ end mul_one_class section variables {M : Type u} -- use `x * npow_rec n x` and not `npow_rec n x * x` in the definition to make sure that -- definitional unfolding of `npow_rec` is blocked, to avoid deep recursion issues. /-- The fundamental power operation in a monoid. `npow_rec n a = a*a*...*a` n times. Use instead `a ^ n`, which has better definitional behavior. -/ def npow_rec [has_one M] [has_mul M] : ℕ → M → M | 0 a := 1 | (n+1) a := a * npow_rec n a /-- The fundamental scalar multiplication in an additive monoid. `nsmul_rec n a = a+a+...+a` n times. Use instead `n • a`, which has better definitional behavior. -/ def nsmul_rec [has_zero M] [has_add M] : ℕ → M → M | 0 a := 0 | (n+1) a := a + nsmul_rec n a attribute [to_additive] npow_rec end /-- Suppose that one can put two mathematical structures on a type, a rich one `R` and a poor one `P`, and that one can deduce the poor structure from the rich structure through a map `F` (called a forgetful functor) (think `R = metric_space` and `P = topological_space`). A possible implementation would be to have a type class `rich` containing a field `R`, a type class `poor` containing a field `P`, and an instance from `rich` to `poor`. However, this creates diamond problems, and a better approach is to let `rich` extend `poor` and have a field saying that `F R = P`. To illustrate this, consider the pair `metric_space` / `topological_space`. Consider the topology on a product of two metric spaces. With the first approach, it could be obtained by going first from each metric space to its topology, and then taking the product topology. But it could also be obtained by considering the product metric space (with its sup distance) and then the topology coming from this distance. These would be the same topology, but not definitionally, which means that from the point of view of Lean's kernel, there would be two different `topological_space` instances on the product. This is not compatible with the way instances are designed and used: there should be at most one instance of a kind on each type. This approach has created an instance diamond that does not commute definitionally. The second approach solves this issue. Now, a metric space contains both a distance, a topology, and a proof that the topology coincides with the one coming from the distance. When one defines the product of two metric spaces, one uses the sup distance and the product topology, and one has to give the proof that the sup distance induces the product topology. Following both sides of the instance diamond then gives rise (definitionally) to the product topology on the product space. Another approach would be to have the rich type class take the poor type class as an instance parameter. It would solve the diamond problem, but it would lead to a blow up of the number of type classes one would need to declare to work with complicated classes, say a real inner product space, and would create exponential complexity when working with products of such complicated spaces, that are avoided by bundling things carefully as above. Note that this description of this specific case of the product of metric spaces is oversimplified compared to mathlib, as there is an intermediate typeclass between `metric_space` and `topological_space` called `uniform_space`. The above scheme is used at both levels, embedding a topology in the uniform space structure, and a uniform structure in the metric space structure. Note also that, when `P` is a proposition, there is no such issue as any two proofs of `P` are definitionally equivalent in Lean. To avoid boilerplate, there are some designs that can automatically fill the poor fields when creating a rich structure if one doesn't want to do something special about them. For instance, in the definition of metric spaces, default tactics fill the uniform space fields if they are not given explicitly. One can also have a helper function creating the rich structure from a structure with fewer fields, where the helper function fills the remaining fields. See for instance `uniform_space.of_core` or `real_inner_product.of_core`. For more details on this question, called the forgetful inheritance pattern, see [Competing inheritance paths in dependent type theory: a case study in functional analysis](https://hal.inria.fr/hal-02463336). -/ library_note "forgetful inheritance" /-- `try_refl_tac` solves goals of the form `∀ a b, f a b = g a b`, if they hold by definition. -/ meta def try_refl_tac : tactic unit := `[intros; refl] /-! ### Design note on `add_monoid` and `monoid` An `add_monoid` has a natural `ℕ`-action, defined by `n • a = a + ... + a`, that we want to declare as an instance as it makes it possible to use the language of linear algebra. However, there are often other natural `ℕ`-actions. For instance, for any semiring `R`, the space of polynomials `polynomial R` has a natural `R`-action defined by multiplication on the coefficients. This means that `polynomial ℕ` would have two natural `ℕ`-actions, which are equal but not defeq. The same goes for linear maps, tensor products, and so on (and even for `ℕ` itself). To solve this issue, we embed an `ℕ`-action in the definition of an `add_monoid` (which is by default equal to the naive action `a + ... + a`, but can be adjusted when needed), and declare a `has_scalar ℕ α` instance using this action. See Note [forgetful inheritance] for more explanations on this pattern. For example, when we define `polynomial R`, then we declare the `ℕ`-action to be by multiplication on each coefficient (using the `ℕ`-action on `R` that comes from the fact that `R` is an `add_monoid`). In this way, the two natural `has_scalar ℕ (polynomial ℕ)` instances are defeq. The tactic `to_additive` transfers definitions and results from multiplicative monoids to additive monoids. To work, it has to map fields to fields. This means that we should also add corresponding fields to the multiplicative structure `monoid`, which could solve defeq problems for powers if needed. These problems do not come up in practice, so most of the time we will not need to adjust the `npow` field when defining multiplicative objects. A basic theory for the power function on monoids and the `ℕ`-action on additive monoids is built in the file `algebra.group_power.basic`. For now, we only register the most basic properties that we need right away. In the definition, we use `n.succ` instead of `n + 1` in the `nsmul_succ'` and `npow_succ'` fields to make sure that `to_additive` is not confused (otherwise, it would try to convert `1 : ℕ` to `0 : ℕ`). -/ /-- An `add_monoid` is an `add_semigroup` with an element `0` such that `0 + a = a + 0 = a`. -/ @[ancestor add_semigroup add_zero_class] class add_monoid (M : Type u) extends add_semigroup M, add_zero_class M := (nsmul : ℕ → M → M := nsmul_rec) (nsmul_zero' : ∀ x, nsmul 0 x = 0 . try_refl_tac) (nsmul_succ' : ∀ (n : ℕ) x, nsmul n.succ x = x + nsmul n x . try_refl_tac) /-- A `monoid` is a `semigroup` with an element `1` such that `1 * a = a * 1 = a`. -/ @[ancestor semigroup mul_one_class, to_additive] class monoid (M : Type u) extends semigroup M, mul_one_class M := (npow : ℕ → M → M := npow_rec) (npow_zero' : ∀ x, npow 0 x = 1 . try_refl_tac) (npow_succ' : ∀ (n : ℕ) x, npow n.succ x = x * npow n x . try_refl_tac) instance monoid.has_pow {M : Type*} [monoid M] : has_pow M ℕ := ⟨λ x n, monoid.npow n x⟩ instance add_monoid.has_scalar_nat {M : Type*} [add_monoid M] : has_scalar ℕ M := ⟨add_monoid.nsmul⟩ attribute [to_additive add_monoid.has_scalar_nat] monoid.has_pow section variables {M : Type*} [monoid M] @[simp, to_additive nsmul_eq_smul] lemma npow_eq_pow (n : ℕ) (x : M) : monoid.npow n x = x^n := rfl -- the attributes are intentionally out of order. `zero_smul` proves `zero_nsmul`. @[to_additive zero_nsmul, simp] theorem pow_zero (a : M) : a^0 = 1 := monoid.npow_zero' _ @[to_additive succ_nsmul] theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := monoid.npow_succ' n a end section monoid variables {M : Type u} [monoid M] @[to_additive] lemma left_inv_eq_right_inv {a b c : M} (hba : b * a = 1) (hac : a * c = 1) : b = c := by rw [←one_mul c, ←hba, mul_assoc, hac, mul_one b] end monoid /-- An additive commutative monoid is an additive monoid with commutative `(+)`. -/ @[protect_proj, ancestor add_monoid add_comm_semigroup] class add_comm_monoid (M : Type u) extends add_monoid M, add_comm_semigroup M /-- A commutative monoid is a monoid with commutative `(*)`. -/ @[protect_proj, ancestor monoid comm_semigroup, to_additive] class comm_monoid (M : Type u) extends monoid M, comm_semigroup M section left_cancel_monoid /-- An additive monoid in which addition is left-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_left_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_left_cancel_semigroup add_monoid] class add_left_cancel_monoid (M : Type u) extends add_left_cancel_semigroup M, add_monoid M /-- A monoid in which multiplication is left-cancellative. -/ @[protect_proj, ancestor left_cancel_semigroup monoid, to_additive add_left_cancel_monoid] class left_cancel_monoid (M : Type u) extends left_cancel_semigroup M, monoid M end left_cancel_monoid section right_cancel_monoid /-- An additive monoid in which addition is right-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_right_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_right_cancel_semigroup add_monoid] class add_right_cancel_monoid (M : Type u) extends add_right_cancel_semigroup M, add_monoid M /-- A monoid in which multiplication is right-cancellative. -/ @[protect_proj, ancestor right_cancel_semigroup monoid, to_additive add_right_cancel_monoid] class right_cancel_monoid (M : Type u) extends right_cancel_semigroup M, monoid M end right_cancel_monoid section cancel_monoid /-- An additive monoid in which addition is cancellative on both sides. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_right_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_left_cancel_monoid add_right_cancel_monoid] class add_cancel_monoid (M : Type u) extends add_left_cancel_monoid M, add_right_cancel_monoid M /-- A monoid in which multiplication is cancellative. -/ @[protect_proj, ancestor left_cancel_monoid right_cancel_monoid, to_additive add_cancel_monoid] class cancel_monoid (M : Type u) extends left_cancel_monoid M, right_cancel_monoid M /-- Commutative version of add_cancel_monoid. -/ @[protect_proj, ancestor add_left_cancel_monoid add_comm_monoid] class add_cancel_comm_monoid (M : Type u) extends add_left_cancel_monoid M, add_comm_monoid M /-- Commutative version of cancel_monoid. -/ @[protect_proj, ancestor left_cancel_monoid comm_monoid, to_additive add_cancel_comm_monoid] class cancel_comm_monoid (M : Type u) extends left_cancel_monoid M, comm_monoid M @[priority 100, to_additive] -- see Note [lower instance priority] instance cancel_comm_monoid.to_cancel_monoid (M : Type u) [cancel_comm_monoid M] : cancel_monoid M := { mul_right_cancel := λ a b c h, mul_left_cancel $ by rw [mul_comm, h, mul_comm], .. ‹cancel_comm_monoid M› } end cancel_monoid /-- The fundamental power operation in a group. `zpow_rec n a = a*a*...*a` n times, for integer `n`. Use instead `a ^ n`, which has better definitional behavior. -/ def zpow_rec {M : Type*} [has_one M] [has_mul M] [has_inv M] : ℤ → M → M | (int.of_nat n) a := npow_rec n a | -[1+ n] a := (npow_rec n.succ a) ⁻¹ /-- The fundamental scalar multiplication in an additive group. `zsmul_rec n a = a+a+...+a` n times, for integer `n`. Use instead `n • a`, which has better definitional behavior. -/ def zsmul_rec {M : Type*} [has_zero M] [has_add M] [has_neg M]: ℤ → M → M | (int.of_nat n) a := nsmul_rec n a | -[1+ n] a := - (nsmul_rec n.succ a) attribute [to_additive] zpow_rec /-- A `div_inv_monoid` is a `monoid` with operations `/` and `⁻¹` satisfying `div_eq_mul_inv : ∀ a b, a / b = a * b⁻¹`. This is the immediate common ancestor of `group` and `group_with_zero`, in order to deduplicate the name `div_eq_mul_inv`. The default for `div` is such that `a / b = a * b⁻¹` holds by definition. Adding `div` as a field rather than defining `a / b := a * b⁻¹` allows us to avoid certain classes of unification failures, for example: Let `foo X` be a type with a `∀ X, has_div (foo X)` instance but no `∀ X, has_inv (foo X)`, e.g. when `foo X` is a `euclidean_domain`. Suppose we also have an instance `∀ X [cromulent X], group_with_zero (foo X)`. Then the `(/)` coming from `group_with_zero_has_div` cannot be definitionally equal to the `(/)` coming from `foo.has_div`. In the same way, adding a `zpow` field makes it possible to avoid definitional failures in diamonds. See the definition of `monoid` and Note [forgetful inheritance] for more explanations on this. -/ @[protect_proj, ancestor monoid has_inv has_div] class div_inv_monoid (G : Type u) extends monoid G, has_inv G, has_div G := (div := λ a b, a * b⁻¹) (div_eq_mul_inv : ∀ a b : G, a / b = a * b⁻¹ . try_refl_tac) (zpow : ℤ → G → G := zpow_rec) (zpow_zero' : ∀ (a : G), zpow 0 a = 1 . try_refl_tac) (zpow_succ' : ∀ (n : ℕ) (a : G), zpow (int.of_nat n.succ) a = a * zpow (int.of_nat n) a . try_refl_tac) (zpow_neg' : ∀ (n : ℕ) (a : G), zpow (-[1+ n]) a = (zpow n.succ a)⁻¹ . try_refl_tac) /-- A `sub_neg_monoid` is an `add_monoid` with unary `-` and binary `-` operations satisfying `sub_eq_add_neg : ∀ a b, a - b = a + -b`. The default for `sub` is such that `a - b = a + -b` holds by definition. Adding `sub` as a field rather than defining `a - b := a + -b` allows us to avoid certain classes of unification failures, for example: Let `foo X` be a type with a `∀ X, has_sub (foo X)` instance but no `∀ X, has_neg (foo X)`. Suppose we also have an instance `∀ X [cromulent X], add_group (foo X)`. Then the `(-)` coming from `add_group.has_sub` cannot be definitionally equal to the `(-)` coming from `foo.has_sub`. In the same way, adding a `zsmul` field makes it possible to avoid definitional failures in diamonds. See the definition of `add_monoid` and Note [forgetful inheritance] for more explanations on this. -/ @[protect_proj, ancestor add_monoid has_neg has_sub] class sub_neg_monoid (G : Type u) extends add_monoid G, has_neg G, has_sub G := (sub := λ a b, a + -b) (sub_eq_add_neg : ∀ a b : G, a - b = a + -b . try_refl_tac) (zsmul : ℤ → G → G := zsmul_rec) (zsmul_zero' : ∀ (a : G), zsmul 0 a = 0 . try_refl_tac) (zsmul_succ' : ∀ (n : ℕ) (a : G), zsmul (int.of_nat n.succ) a = a + zsmul (int.of_nat n) a . try_refl_tac) (zsmul_neg' : ∀ (n : ℕ) (a : G), zsmul (-[1+ n]) a = - (zsmul n.succ a) . try_refl_tac) attribute [to_additive sub_neg_monoid] div_inv_monoid instance div_inv_monoid.has_pow {M} [div_inv_monoid M] : has_pow M ℤ := ⟨λ x n, div_inv_monoid.zpow n x⟩ instance sub_neg_monoid.has_scalar_int {M} [sub_neg_monoid M] : has_scalar ℤ M := ⟨sub_neg_monoid.zsmul⟩ attribute [to_additive sub_neg_monoid.has_scalar_int] div_inv_monoid.has_pow section variables {G : Type*} [div_inv_monoid G] @[simp, to_additive zsmul_eq_smul] lemma zpow_eq_pow (n : ℤ) (x : G) : div_inv_monoid.zpow n x = x^n := rfl @[simp, to_additive zero_zsmul] theorem zpow_zero (a : G) : a ^ (0:ℤ) = 1 := div_inv_monoid.zpow_zero' a @[simp, norm_cast, to_additive coe_nat_zsmul] theorem zpow_coe_nat (a : G) : ∀ n : ℕ, a ^ (n:ℤ) = a ^ n | 0 := (zpow_zero _).trans (pow_zero _).symm | (n + 1) := calc a ^ (↑(n + 1) : ℤ) = a * a ^ (n : ℤ) : div_inv_monoid.zpow_succ' _ _ ... = a * a ^ n : congr_arg ((*) a) (zpow_coe_nat n) ... = a ^ (n + 1) : (pow_succ _ _).symm @[to_additive of_nat_zsmul] theorem zpow_of_nat (a : G) (n : ℕ) : a ^ (int.of_nat n) = a ^ n := zpow_coe_nat a n @[simp, to_additive] theorem zpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ (n + 1))⁻¹ := by { rw ← zpow_coe_nat, exact div_inv_monoid.zpow_neg' n a } end @[to_additive] lemma div_eq_mul_inv {G : Type u} [div_inv_monoid G] : ∀ a b : G, a / b = a * b⁻¹ := div_inv_monoid.div_eq_mul_inv /-- A `group` is a `monoid` with an operation `⁻¹` satisfying `a⁻¹ * a = 1`. There is also a division operation `/` such that `a / b = a * b⁻¹`, with a default so that `a / b = a * b⁻¹` holds by definition. -/ @[protect_proj, ancestor div_inv_monoid] class group (G : Type u) extends div_inv_monoid G := (mul_left_inv : ∀ a : G, a⁻¹ * a = 1) /-- An `add_group` is an `add_monoid` with a unary `-` satisfying `-a + a = 0`. There is also a binary operation `-` such that `a - b = a + -b`, with a default so that `a - b = a + -b` holds by definition. -/ @[protect_proj, ancestor sub_neg_monoid] class add_group (A : Type u) extends sub_neg_monoid A := (add_left_neg : ∀ a : A, -a + a = 0) attribute [to_additive] group /-- Abbreviation for `@div_inv_monoid.to_monoid _ (@group.to_div_inv_monoid _ _)`. Useful because it corresponds to the fact that `Grp` is a subcategory of `Mon`. Not an instance since it duplicates `@div_inv_monoid.to_monoid _ (@group.to_div_inv_monoid _ _)`. See note [reducible non-instances]. -/ @[reducible, to_additive "Abbreviation for `@sub_neg_monoid.to_add_monoid _ (@add_group.to_sub_neg_monoid _ _)`. Useful because it corresponds to the fact that `AddGroup` is a subcategory of `AddMon`. Not an instance since it duplicates `@sub_neg_monoid.to_add_monoid _ (@add_group.to_sub_neg_monoid _ _)`."] def group.to_monoid (G : Type u) [group G] : monoid G := @div_inv_monoid.to_monoid _ (@group.to_div_inv_monoid _ _) section group variables {G : Type u} [group G] {a b c : G} @[simp, to_additive] lemma mul_left_inv : ∀ a : G, a⁻¹ * a = 1 := group.mul_left_inv @[to_additive] lemma inv_mul_self (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp, to_additive] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := by rw [← mul_assoc, mul_left_inv, one_mul] @[simp, to_additive] lemma inv_eq_of_mul_eq_one (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp, to_additive] lemma inv_inv (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp, to_additive] lemma mul_right_inv (a : G) : a * a⁻¹ = 1 := have a⁻¹⁻¹ * a⁻¹ = 1 := mul_left_inv a⁻¹, by rwa [inv_inv] at this @[to_additive] lemma mul_inv_self (a : G) : a * a⁻¹ = 1 := mul_right_inv a @[simp, to_additive] lemma mul_inv_cancel_right (a b : G) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] @[priority 100, to_additive] -- see Note [lower instance priority] instance group.to_cancel_monoid : cancel_monoid G := { mul_right_cancel := λ a b c h, by rw [← mul_inv_cancel_right a b, h, mul_inv_cancel_right], mul_left_cancel := λ a b c h, by rw [← inv_mul_cancel_left a b, h, inv_mul_cancel_left], ..‹group G› } end group @[to_additive] lemma group.to_div_inv_monoid_injective {G : Type*} : function.injective (@group.to_div_inv_monoid G) := begin rintros ⟨⟩ ⟨⟩ h, replace h := div_inv_monoid.mk.inj h, dsimp at h, rcases h with ⟨rfl, rfl, rfl, rfl, rfl, rfl⟩, refl end /-- A commutative group is a group with commutative `(*)`. -/ @[protect_proj, ancestor group comm_monoid] class comm_group (G : Type u) extends group G, comm_monoid G /-- An additive commutative group is an additive group with commutative `(+)`. -/ @[protect_proj, ancestor add_group add_comm_monoid] class add_comm_group (G : Type u) extends add_group G, add_comm_monoid G attribute [to_additive] comm_group attribute [instance, priority 300] add_comm_group.to_add_comm_monoid @[to_additive] lemma comm_group.to_group_injective {G : Type u} : function.injective (@comm_group.to_group G) := begin rintros ⟨⟩ ⟨⟩ h, replace h := group.mk.inj h, dsimp at h, rcases h with ⟨rfl, rfl, rfl, rfl, rfl, rfl⟩, refl end section comm_group variables {G : Type u} [comm_group G] @[priority 100, to_additive] -- see Note [lower instance priority] instance comm_group.to_cancel_comm_monoid : cancel_comm_monoid G := { ..‹comm_group G›, ..group.to_cancel_monoid } end comm_group
adde855b525c007069cc4e516973754841684741
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/converter.lean
7b15d876172b86aa3b4dedb4dc88c72e2c310321
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,866
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 Converter monad for building simplifiers. -/ prelude import init.meta.tactic init.meta.simp_tactic import init.meta.congr_lemma init.meta.match_tactic open tactic meta structure conv_result (α : Type) := (val : α) (rhs : expr) (proof : option expr) meta def conv (α : Type) : Type := name → expr → tactic (conv_result α) namespace conv meta def lhs : conv expr := λ r e, return ⟨e, e, none⟩ meta def change (new_p : pexpr) : conv unit := λ r e, do new_e ← to_expr new_p, unify e new_e, return ⟨(), new_e, none⟩ protected meta def pure {α : Type} : α → conv α := λ a r e, return ⟨a, e, none⟩ private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) := match o₁, o₂ with | none, _ := return o₂ | _, none := return o₁ | some p₁, some p₂ := do env ← get_env, match env^.trans_for r with | some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr | none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not transitive" end end protected meta def seq {α β : Type} (c₁ : conv (α → β)) (c₂ : conv α) : conv β := λ r e, do ⟨fn, e₁, pr₁⟩ ← c₁ r e, ⟨a, e₂, pr₂⟩ ← c₂ r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨fn a, e₂, pr⟩ protected meta def fail {α : Type} : conv α := λ r e, failed protected meta def orelse {α : Type} (c₁ : conv α) (c₂ : conv α) : conv α := λ r e, c₁ r e <|> c₂ r e protected meta def map {α β : Type} (f : α → β) (c : conv α) : conv β := λ r e, do ⟨a, e₁, pr⟩ ← c r e, return ⟨f a, e₁, pr⟩ protected meta def bind {α β : Type} (c₁ : conv α) (c₂ : α → conv β) : conv β := λ r e, do ⟨a, e₁, pr₁⟩ ← c₁ r e, ⟨b, e₂, pr₂⟩ ← c₂ a r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨b, e₂, pr⟩ meta instance : monad conv := { map := @conv.map, pure := @conv.pure, bind := @conv.bind } meta instance : alternative conv := { conv.monad with failure := @conv.fail, orelse := @conv.orelse } meta def whnf (md : transparency := reducible) : conv unit := λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩ meta def dsimp : conv unit := λ r e, do s ← simp_lemmas.mk_default, n ← s^.dsimplify e, return ⟨(), n, none⟩ meta def try (c : conv unit) : conv unit := c <|> return () meta def tryb (c : conv unit) : conv bool := (c >> return tt) <|> return ff meta def trace {α : Type} [has_to_tactic_format α] (a : α) : conv unit := λ r e, tactic.trace a >> return ⟨(), e, none⟩ meta def trace_lhs : conv unit := lhs >>= trace meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit := λ r e, do (new_e, pr) ← s^.rewrite prove r e, return ⟨(), new_e, some pr⟩ meta def apply_lemmas (s : simp_lemmas) : conv unit := apply_lemmas_core s failed /- αdapter for using iff-lemmas as eq-lemmas -/ meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit := λ r e, do guard (r = `eq), (new_e, pr) ← s^.rewrite prove `iff e, new_pr ← mk_app `propext [pr], return ⟨(), new_e, some new_pr⟩ meta def apply_propext_lemmas (s : simp_lemmas) : conv unit := apply_propext_lemmas_core s failed private meta def mk_refl_proof (r : name) (e : expr) : tactic expr := do env ← get_env, match (environment.refl_for env r) with | (some refl) := do pr ← mk_app refl [e], return pr | none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not reflexive" end meta def to_tactic (c : conv unit) : name → expr → tactic (expr × expr) := λ r e, do ⟨u, e₁, o⟩ ← c r e, match o with | none := do p ← mk_refl_proof r e, return (e₁, p) | some p := return (e₁, p) end meta def lift_tactic {α : Type} (t : tactic α) : conv α := λ r e, do a ← t, return ⟨a, e, none⟩ meta def apply_simp_set (attr_name : name) : conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas meta def apply_propext_simp_set (attr_name : name) : conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas meta def skip : conv unit := return () meta def repeat : conv unit → conv unit | c r lhs := (do ⟨_, rhs₁, pr₁⟩ ← c r lhs, guard (¬ lhs =ₐ rhs₁), ⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁, pr ← join_proofs r pr₁ pr₂, return ⟨(), rhs₂, pr⟩) <|> return ⟨(), lhs, none⟩ meta def first {α : Type} : list (conv α) → conv α | [] := conv.fail | (c::cs) := c <|> first cs meta def match_pattern (p : pattern) : conv unit := λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩ meta def mk_match_expr (p : pexpr) : tactic (conv unit) := do new_p ← pexpr_to_pattern p, return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩) meta def match_expr (p : pexpr) : conv unit := λ r e, do new_p ← pexpr_to_pattern p, tactic.match_pattern new_p e >> return ⟨(), e, none⟩ meta def funext (c : conv unit) : conv unit := λ r lhs, do guard (r = `eq), (expr.lam n bi d b) ← return lhs, let aux_type := expr.pi n bi d (expr.const `true []), (result, _) ← solve_aux aux_type $ do { x ← intro1, c_result ← c r (b^.instantiate_var x), let rhs := expr.lam n bi d (c_result^.rhs^.abstract x), match c_result^.proof : _ → tactic (conv_result unit) with | some pr := do let aux_pr := expr.lam n bi d (pr^.abstract x), new_pr ← mk_app `funext [lhs, rhs, aux_pr], return ⟨(), rhs, some new_pr⟩ | none := return ⟨(), rhs, none⟩ end }, return result meta def congr_core (c_f c_a : conv unit) : conv unit := λ r lhs, do guard (r = `eq), (expr.app f a) ← return lhs, f_type ← infer_type f >>= tactic.whnf, guard (f_type^.is_arrow), ⟨(), new_f, of⟩ ← try c_f r f, ⟨(), new_a, oa⟩ ← try c_a r a, rhs ← return $ new_f new_a, match of, oa with | none, none := return ⟨(), rhs, none⟩ | none, some pr_a := do pr ← mk_app `congr_arg [a, new_a, f, pr_a], return ⟨(), new_f new_a, some pr⟩ | some pr_f, none := do pr ← mk_app `congr_fun [f, new_f, pr_f, a], return ⟨(), rhs, some pr⟩ | some pr_f, some pr_a := do pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a], return ⟨(), rhs, some pr⟩ end meta def congr (c : conv unit) : conv unit := congr_core c c meta def bottom_up (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, failed) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) r e, return ⟨(), new_e, some pr⟩ meta def top_down (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, (do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)) <|> return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find_pattern (pat : pattern) (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, if matched then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff) else return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def findp : pexpr → conv unit → conv unit := λ p c r e, do pat ← pexpr_to_pattern p, find_pattern pat c r e meta def conversion (c : conv unit) : tactic unit := do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"), (new_lhs, pr) ← to_tactic c r lhs, (unify new_lhs rhs <|> do new_lhs_fmt ← pp new_lhs, rhs_fmt ← pp rhs, fail (to_fmt "conversion failed, expected" ++ rhs_fmt^.indent 4 ++ format.line ++ "provided" ++ new_lhs_fmt^.indent 4)), exact pr end conv
00eff52efbad5d5f28bf284cf5060abc1653bdd6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/prod.lean
e46ad8a5ded577e0ad7526025fa411a7ad132179
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,070
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.card import data.finset.prod /-! # fintype instance for the product of two fintypes. -/ open function open_locale nat universes u v variables {α β γ : Type*} open finset function namespace set variables {s t : set α} lemma to_finset_prod (s : set α) (t : set β) [fintype s] [fintype t] [fintype (s ×ˢ t)] : (s ×ˢ t).to_finset = s.to_finset ×ˢ t.to_finset := by { ext, simp } lemma to_finset_off_diag {s : set α} [decidable_eq α] [fintype s] [fintype s.off_diag] : s.off_diag.to_finset = s.to_finset.off_diag := finset.ext $ by simp end set instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ ×ˢ univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α) ×ˢ (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ section open_locale classical @[simp] lemma infinite_prod : infinite (α × β) ↔ infinite α ∧ nonempty β ∨ nonempty α ∧ infinite β := begin refine ⟨λ H, _, λ H, H.elim (and_imp.2 $ @prod.infinite_of_left α β) (and_imp.2 $ @prod.infinite_of_right α β)⟩, rw and.comm, contrapose! H, introI H', rcases infinite.nonempty (α × β) with ⟨a, b⟩, haveI := fintype_of_not_infinite (H.1 ⟨b⟩), haveI := fintype_of_not_infinite (H.2 ⟨a⟩), exact H'.false end instance pi.infinite_of_left {ι : Sort*} {π : ι → Sort*} [∀ i, nontrivial $ π i] [infinite ι] : infinite (Π i : ι, π i) := begin choose m n hm using λ i, exists_pair_ne (π i), refine infinite.of_injective (λ i, m.update i (n i)) (λ x y h, not_not.1 $ λ hne, _), simp_rw [update_eq_iff, update_noteq hne] at h, exact (hm x h.1.symm).elim, end /-- If at least one `π i` is infinite and the rest nonempty, the pi type of all `π` is infinite. -/ lemma pi.infinite_of_exists_right {ι : Type*} {π : ι → Type*} (i : ι) [infinite $ π i] [∀ i, nonempty $ π i] : infinite (Π i : ι, π i) := let ⟨m⟩ := @pi.nonempty ι π _ in infinite.of_injective _ (update_injective m i) /-- See `pi.infinite_of_exists_right` for the case that only one `π i` is infinite. -/ instance pi.infinite_of_right {ι : Sort*} {π : ι → Sort*} [∀ i, infinite $ π i] [nonempty ι] : infinite (Π i : ι, π i) := pi.infinite_of_exists_right (classical.arbitrary ι) /-- Non-dependent version of `pi.infinite_of_left`. -/ instance function.infinite_of_left {ι π : Sort*} [nontrivial π] [infinite ι] : infinite (ι → π) := pi.infinite_of_left /-- Non-dependent version of `pi.infinite_of_exists_right` and `pi.infinite_of_right`. -/ instance function.infinite_of_right {ι π : Sort*} [infinite π] [nonempty ι] : infinite (ι → π) := pi.infinite_of_right end
3aeada49d68e2cfaf9e09b72bbefb728b266c932
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/field_theory/is_alg_closed/algebraic_closure.lean
1a755a816eeefb05ccd8f150a8a4687fe475fec2
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
10,844
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.direct_limit import field_theory.is_alg_closed.basic /-! # Algebraic Closure In this file we construct the algebraic closure of a field ## Main Definitions - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## Tags algebraic closure, algebraically closed -/ universes u v w noncomputable theory open_locale classical big_operators open polynomial variables (k : Type u) [field k] namespace algebraic_closure open mv_polynomial /-- The subtype of monic irreducible polynomials -/ @[reducible] def monic_irreducible : Type u := { f : polynomial k // monic f ∧ irreducible f } /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (X f) f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span $ set.range $ eval_X_self k /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (s : finset (monic_irreducible k)) : mv_polynomial (monic_irreducible k) k →ₐ[k] splitting_field (∏ x in s, x : polynomial k) := mv_polynomial.aeval $ λ f, if hf : f ∈ s then root_of_splits _ ((splits_prod_iff _ $ λ (j : monic_irreducible k) _, j.2.2.ne_zero).1 (splitting_field.splits _) f hf) (mt is_unit_iff_degree_eq_zero.2 f.2.2.not_unit) else 37 theorem to_splitting_field_eval_X_self {s : finset (monic_irreducible k)} {f} (hf : f ∈ s) : to_splitting_field k s (eval_X_self k f) = 0 := by { rw [to_splitting_field, eval_X_self, ← alg_hom.coe_to_ring_hom, hom_eval₂, alg_hom.coe_to_ring_hom, mv_polynomial.aeval_X, dif_pos hf, ← algebra_map_eq, alg_hom.comp_algebra_map], exact map_root_of_splits _ _ _ } theorem span_eval_ne_top : span_eval k ≠ ⊤ := begin rw [ideal.ne_top_iff_one, span_eval, ideal.span, ← set.image_univ, finsupp.mem_span_image_iff_total], rintros ⟨v, _, hv⟩, replace hv := congr_arg (to_splitting_field k v.support) hv, rw [alg_hom.map_one, finsupp.total_apply, finsupp.sum, alg_hom.map_sum, finset.sum_eq_zero] at hv, { exact zero_ne_one hv }, intros j hj, rw [smul_eq_mul, alg_hom.map_mul, to_splitting_field_eval_X_self k hj, mul_zero] end /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal : ideal (mv_polynomial (monic_irreducible k) k) := classical.some $ ideal.exists_le_maximal _ $ span_eval_ne_top k instance max_ideal.is_maximal : (max_ideal k).is_maximal := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).1 theorem le_max_ideal : span_eval k ≤ max_ideal k := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).2 /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic : Type u := mv_polynomial (monic_irreducible k) k ⧸ max_ideal k instance adjoin_monic.field : field (adjoin_monic k) := ideal.quotient.field _ instance adjoin_monic.inhabited : inhabited (adjoin_monic k) := ⟨37⟩ /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic : k →+* adjoin_monic k := (ideal.quotient.mk _).comp C instance adjoin_monic.algebra : algebra k (adjoin_monic k) := (to_adjoin_monic k).to_algebra theorem adjoin_monic.algebra_map : algebra_map k (adjoin_monic k) = (ideal.quotient.mk _).comp C := rfl theorem adjoin_monic.is_integral (z : adjoin_monic k) : is_integral k z := let ⟨p, hp⟩ := ideal.quotient.mk_surjective z in hp ▸ mv_polynomial.induction_on p (λ x, is_integral_algebra_map) (λ p q, is_integral_add) (λ p f ih, @is_integral_mul _ _ _ _ _ _ (ideal.quotient.mk _ _) ih ⟨f, f.2.1, by { erw [adjoin_monic.algebra_map, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span ⟨f, rfl⟩) }⟩) theorem adjoin_monic.exists_root {f : polynomial k} (hfm : f.monic) (hfi : irreducible f) : ∃ x : adjoin_monic k, f.eval₂ (to_adjoin_monic k) x = 0 := ⟨ideal.quotient.mk _ $ X (⟨f, hfm, hfi⟩ : monic_irreducible k), by { rw [to_adjoin_monic, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span $ ⟨_, rfl⟩) }⟩ /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (n : ℕ) : Σ α : Type u, field α := nat.rec_on n ⟨k, infer_instance⟩ $ λ n ih, ⟨@adjoin_monic ih.1 ih.2, @adjoin_monic.field ih.1 ih.2⟩ /-- The `n`th step of constructing `algebraic_closure`. -/ def step (n : ℕ) : Type u := (step_aux k n).1 instance step.field (n : ℕ) : field (step k n) := (step_aux k n).2 instance step.inhabited (n) : inhabited (step k n) := ⟨37⟩ /-- The canonical inclusion to the `0`th step. -/ def to_step_zero : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (n : ℕ) : step k n →+* step k (n + 1) := @to_adjoin_monic (step k n) (step.field k n) instance step.algebra_succ (n) : algebra (step k n) (step k (n + 1)) := (to_step_succ k n).to_algebra theorem to_step_succ.exists_root {n} {f : polynomial (step k n)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : step k (n + 1), f.eval₂ (to_step_succ k n) x = 0 := @adjoin_monic.exists_root _ (step.field k n) _ hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (m n : ℕ) (h : m ≤ n) : step k m →+* step k n := { to_fun := nat.le_rec_on h (λ n, to_step_succ k n), map_one' := begin induction h with n h ih, { exact nat.le_rec_on_self 1 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_one] end, map_mul' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_mul] end, map_zero' := begin induction h with n h ih, { exact nat.le_rec_on_self 0 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_zero] end, map_add' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_add] end } @[simp] lemma coe_to_step_of_le (m n : ℕ) (h : m ≤ n) : (to_step_of_le k m n h : step k m → step k n) = nat.le_rec_on h (λ n, to_step_succ k n) := rfl instance step.algebra (n) : algebra k (step k n) := (to_step_of_le k 0 n n.zero_le).to_algebra instance step.scalar_tower (n) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq $ λ z, @nat.le_rec_on_succ (step k) 0 n n.zero_le (n + 1).zero_le (λ n, to_step_succ k n) z theorem step.is_integral (n) : ∀ z : step k n, is_integral k z := nat.rec_on n (λ z, is_integral_algebra_map) $ λ n ih z, is_integral_trans ih _ (adjoin_monic.is_integral (step k n) z : _) instance to_step_of_le.directed_system : directed_system (step k) (λ i j h, to_step_of_le k i j h) := ⟨λ i x h, nat.le_rec_on_self x, λ i₁ i₂ i₃ h₁₂ h₂₃ x, (nat.le_rec_on_trans h₁₂ h₂₃ x).symm⟩ end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure : Type u := ring.direct_limit (algebraic_closure.step k) (λ i j h, algebraic_closure.to_step_of_le k i j h) namespace algebraic_closure instance : field (algebraic_closure k) := field.direct_limit.field _ _ instance : inhabited (algebraic_closure k) := ⟨37⟩ /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (n : ℕ) : step k n →+* algebraic_closure k := ring.direct_limit.of _ _ _ instance algebra_of_step (n) : algebra (step k n) (algebraic_closure k) := (of_step k n).to_algebra theorem of_step_succ (n : ℕ) : (of_step k (n + 1)).comp (to_step_succ k n) = of_step k n := ring_hom.ext $ λ x, show ring.direct_limit.of (step k) (λ i j h, to_step_of_le k i j h) _ _ = _, by { convert ring.direct_limit.of_f n.le_succ x, ext x, exact (nat.le_rec_on_succ' x).symm } theorem exists_of_step (z : algebraic_closure k) : ∃ n x, of_step k n x = z := ring.direct_limit.exists_of z -- slow theorem exists_root {f : polynomial (algebraic_closure k)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : algebraic_closure k, f.eval x = 0 := begin have : ∃ n p, polynomial.map (of_step k n) p = f, { convert ring.direct_limit.polynomial.exists_of f }, unfreezingI { obtain ⟨n, p, rfl⟩ := this }, rw monic_map_iff at hfm, have := hfm.irreducible_of_irreducible_map (of_step k n) p hfi, obtain ⟨x, hx⟩ := to_step_succ.exists_root k hfm this, refine ⟨of_step k (n + 1) x, _⟩, rw [← of_step_succ k n, eval_map, ← hom_eval₂, hx, ring_hom.map_zero] end instance : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root _ $ λ f, exists_root k instance {R : Type*} [comm_semiring R] [alg : algebra R k] : algebra R (algebraic_closure k) := ((of_step k 0).comp (@algebra_map _ _ _ _ alg)).to_algebra lemma algebra_map_def {R : Type*} [comm_semiring R] [alg : algebra R k] : algebra_map R (algebraic_closure k) = ((of_step k 0 : k →+* _).comp (@algebra_map _ _ _ _ alg)) := rfl instance {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] [algebra S k] [algebra R k] [is_scalar_tower R S k] : is_scalar_tower R S (algebraic_closure k) := is_scalar_tower.of_algebra_map_eq (λ x, ring_hom.congr_arg _ (is_scalar_tower.algebra_map_apply R S k x : _)) /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (n) : step k n →ₐ[k] algebraic_closure k := { commutes' := λ x, ring.direct_limit.of_f n.zero_le x, .. of_step k n } theorem is_algebraic : algebra.is_algebraic k (algebraic_closure k) := λ z, is_algebraic_iff_is_integral.2 $ let ⟨n, x, hx⟩ := exists_of_step k z in hx ▸ is_integral_alg_hom (of_step_hom k n) (step.is_integral k n x) instance : is_alg_closure k (algebraic_closure k) := ⟨algebraic_closure.is_alg_closed k, is_algebraic k⟩ end algebraic_closure
20edf8e8ebd26964e4bb96e75fcf7d28d2709a1a
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/kleene/l4.lean
fa14b769a77891d8e17945cdc6d48df0a2fc0d75
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
1,723
lean
namespace hidden constant and : Prop → Prop → Prop constant or : Prop → Prop → Prop constant imp : Prop → Prop → Prop constant neg : Prop → Prop constant top : Prop constant bot : Prop notation a `or` b := or a b notation a `imp` b := imp a b notation a `and` b := and a b axiom cl₁ : ∀ {a b : Prop}, a → (a imp b) → b axiom cl₂ : ∀ {a b : Prop}, a imp (b imp a) axiom cl₃ : ∀ {a b c : Prop}, (a imp (b imp c)) imp ((a imp b) imp (a imp c)) axiom cl₄ : ∀ {a b : Prop}, (a and b) imp a axiom cl₅ : ∀ {a b : Prop}, (a and b) imp b axiom cl₆ : ∀ {a b : Prop}, a imp (b imp (a and b)) axiom cl₇ : ∀ {a b : Prop}, a imp (a or b) axiom cl₈ : ∀ {a b : Prop}, b imp (a or b) axiom cl₉ : ∀ {a b c : Prop}, (a imp c) imp ((b imp c) imp ((a or b) imp c)) axiom cl₁₀ : ∀ {a b : Prop}, (a imp b) imp ((a imp (neg b)) imp (neg a)) axiom cl₁₁ : ∀ {a : Prop}, (neg (neg a)) imp a axiom cl₁₂ : top axiom cl₁₃ : ∀ {a : Prop}, bot imp a example {a : Prop} : a imp a := have h₁ : (a imp ((a imp a) imp a)) imp ((a imp (a imp a)) imp (a imp a)), from cl₃, have h₂ : a imp ((a imp a) imp a), from cl₂, have h₃ : ((a imp (a imp a)) imp (a imp a)), from cl₁ h₂ h₁, have h₄ : a imp (a imp a), from cl₂, show a imp a, from cl₁ h₄ h₃ theorem cl₁₄ {a b c : Prop} (h₁ : a imp b) (h₂ : b imp c) : a imp c := have h₃ : (a imp (b imp c)) imp ((a imp b) imp (a imp c)), from cl₃, have h₄ : (b imp c) imp (a imp (b imp c)), from cl₂, have h₅ : a imp (b imp c), from cl₁ h₂ h₄, have h₆ : (a imp b) imp (a imp c), from cl₁ h₅ h₃, show a imp c, from cl₁ h₁ h₆ end hidden
f6763ca64a0a0ed46c96eca5535c28ceaf8ebb38
df561f413cfe0a88b1056655515399c546ff32a5
/8-inequality-world/l4.lean
2033fdec2fe1874ac712d0c73011bbc7eb766807
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
74
lean
lemma zero_le (a : mynat) : 0 ≤ a := begin use a, rw zero_add, refl, end
c5f25a1b90d9c0cfa36f9bee7fe83f43d23a3831
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/Lsp/Capabilities.lean
e6c178544f6cc0f070e74677d860331959416b53
[ "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
3,262
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.JsonRpc import Lean.Data.Lsp.TextSync import Lean.Data.Lsp.LanguageFeatures import Lean.Data.Lsp.CodeActions /-! Minimal LSP servers/clients do not have to implement a lot of functionality. Most useful additional behavior is instead opted into via capabilities. -/ namespace Lean namespace Lsp open Json structure CompletionItemCapabilities where insertReplaceSupport? : Option Bool := none deriving ToJson, FromJson structure CompletionClientCapabilities where completionItem? : Option CompletionItemCapabilities := none deriving ToJson, FromJson structure TextDocumentClientCapabilities where completion? : Option CompletionClientCapabilities := none codeAction? : Option CodeActionClientCapabilities := none deriving ToJson, FromJson structure ShowDocumentClientCapabilities where support : Bool deriving ToJson, FromJson structure WindowClientCapabilities where showDocument? : Option ShowDocumentClientCapabilities := none deriving ToJson, FromJson structure ChangeAnnotationSupport where groupsOnLabel? : Option Bool := none deriving ToJson, FromJson structure WorkspaceEditClientCapabilities where /-- The client supports versioned document changes in `WorkspaceEdit`s. -/ documentChanges? : Option Bool := none /-- Whether the client in general supports change annotations on text edits. -/ changeAnnotationSupport? : Option ChangeAnnotationSupport := none /-- The resource operations the client supports. Clients should at least support 'create', 'rename' and 'delete' files and folders. -/ resourceOperations? : Option (Array String) := none deriving ToJson, FromJson structure WorkspaceClientCapabilities where applyEdit: Bool workspaceEdit? : Option WorkspaceEditClientCapabilities := none deriving ToJson, FromJson structure ClientCapabilities where textDocument? : Option TextDocumentClientCapabilities := none window? : Option WindowClientCapabilities := none workspace? : Option WorkspaceClientCapabilities := none deriving ToJson, FromJson -- TODO largely unimplemented structure ServerCapabilities where textDocumentSync? : Option TextDocumentSyncOptions := none completionProvider? : Option CompletionOptions := none hoverProvider : Bool := false documentHighlightProvider : Bool := false documentSymbolProvider : Bool := false definitionProvider : Bool := false declarationProvider : Bool := false typeDefinitionProvider : Bool := false referencesProvider : Bool := false workspaceSymbolProvider : Bool := false foldingRangeProvider : Bool := false semanticTokensProvider? : Option SemanticTokensOptions := none codeActionProvider? : Option CodeActionOptions := none deriving ToJson, FromJson end Lsp end Lean
728927e4c630755ca89ee07553ac8afb49dce842
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/shapes/concrete_category.lean
4956e18c20747a70e0a341a5fc78829ff81c987a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
673
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 category_theory.limits.shapes.kernels import category_theory.concrete_category.basic import tactic.elementwise /-! # Facts about limits of functors into concrete categories This file doesn't yet attempt to be exhaustive; it just contains lemmas that are useful while comparing categorical limits with existing constructions in concrete categories. -/ universes u open category_theory namespace category_theory.limits attribute [elementwise] kernel.condition cokernel.condition end category_theory.limits
ce86bdb30bd16e8e2f2adc783d5a79005b1d0de9
9e90bb7eb4d1bde1805f9eb6187c333fdf09588a
/src/lib/attributed/to_mathlib.lean
0311ea45405740e883e5bc93e1cd94ee9686e4d8
[ "Apache-2.0" ]
permissive
alexjbest/stump-learnable
6311d0c3a1a1a0e65ce83edcbb3b4b7cecabb851
f8fd812fc646d2ece312ff6ffc2a19848ac76032
refs/heads/master
1,659,486,805,691
1,590,454,024,000
1,590,454,024,000
266,173,720
0
0
Apache-2.0
1,590,169,884,000
1,590,169,883,000
null
UTF-8
Lean
false
false
31,317
lean
/- Various lemmas intended for mathlib. Some parts of this file are originally from https://github.com/johoelzl/mathlib/blob/c9507242274ac18defbceb917f30d6afb8b839a5/src/measure_theory/measurable_space.lean Authors: Johannes Holzl, John Tristan, Koundinya Vajjha -/ import tactic.tidy import measure_theory.giry_monad measure_theory.integration measure_theory.borel_space .dvector import .probability_theory import analysis.special_functions.exp_log local attribute [instance] classical.prop_decidable noncomputable theory -- set_option pp.implicit true -- set_option pp.coercions true -- set_option trace.class_instances true -- set_option class.instance_max_depth 39 -- local attribute [instance] classical.prop_decidable universes u v open nnreal measure_theory nat list measure_theory.measure set lattice ennreal measurable_space probability_measure infixl ` >>=ₐ `:55 := measure.bind infixl ` <$>ₐ `:55 := measure.map local notation `doₐ` binders ` ←ₐ ` m ` ; ` t:(scoped p, m >>=ₐ p) := t local notation `ret` := measure.dirac namespace to_integration variables {α : Type u} {β : Type u} -- Auxilary results about simple functions and characteristic functions. The results in this section should go into integration.lean in mathlib. @[simp] lemma integral_sum [measurable_space α] (m : measure α) (f g : α → ennreal) [hf : measurable f] [hg : measurable g] : m.integral (f + g) = m.integral f + m.integral g := begin rw [integral, integral, integral,←lintegral_add], refl, repeat{assumption}, end @[simp] lemma integral_const_mul [measurable_space α] (m : measure α) {f : α → ennreal} (hf : measurable f) (k:ennreal): m.integral (λ x, k*f(x)) = k * m.integral f := by rw [integral,lintegral_const_mul,integral] ; assumption /-- The characteristic function (indicator function) of a set A. -/ noncomputable def char_fun [measurable_space α] (A : set α) := simple_func.restrict (simple_func.const α (1 : ennreal)) A notation `χ` `⟦` A `⟧` := char_fun A notation `∫` f `ð`m := integral m f -- variables (A : set α) (a : α) [measurable_space α] @[simp] lemma char_fun_apply [measurable_space α] {A : set α} (hA : is_measurable A)(a : α): (χ ⟦A⟧ : simple_func α ennreal) a = ite (a ∈ A) 1 0 := by unfold_coes ; apply (simple_func.restrict_apply _ hA) @[simp] lemma integral_char_fun [measurable_space α] [ne : nonempty α] (m : measure α) {A : set α} (hA : is_measurable A) : (∫ χ⟦A⟧ ðm) = m A := begin rw [char_fun, integral, simple_func.lintegral_eq_integral, simple_func.restrict_integral], unfold set.preimage, dsimp, erw [simple_func.range_const α], simp, rw [←set.univ_def, set.univ_inter], refl, assumption, end lemma dirac_char_fun [measurable_space α] {A : set α} (hA : is_measurable A) : (λ (x : α), (ret x : measure α) A) = χ⟦A⟧ := begin funext,rw [measure.dirac_apply _ hA, char_fun_apply hA], by_cases x ∈ A, split_ifs, simp [h], split_ifs, simp [h], end lemma prob.dirac_char_fun [measurable_space α] {B: set α} (hB : is_measurable B) : (λ x:α,((retₚ x).to_measure : measure α) B) = χ⟦B⟧ := begin conv {congr, funext, rw ret_to_measure}, exact dirac_char_fun hB, end lemma measurable_dirac_fun [measurable_space α] {A : set α} (hA : is_measurable A) : measurable (λ (x : α), (ret x : measure α) A) := by rw dirac_char_fun hA ; apply simple_func.measurable instance simple_func.add_comm_monoid [measurable_space α] [add_comm_monoid β] : add_comm_monoid (simple_func α β) := { add_comm := assume a b, simple_func.ext (assume a, add_comm _ _), .. simple_func.add_monoid } lemma integral_finset_sum [measurable_space α] (m : measure α) (s : finset (set α)) (hX : ∀ (A : set α) , is_measurable (A)) : m.integral (s.sum (λ A, χ ⟦ A ⟧)) = s.sum (λ A, m A) := begin rw integral, refine finset.induction_on s _ _, { simp, erw lintegral_zero }, { assume a s has ih, simp [has], erw [lintegral_add], rw simple_func.lintegral_eq_integral,unfold char_fun, erw simple_func.restrict_const_integral, dsimp, erw ih, ext1,cases a_1, dsimp at *, simp at *, refl, exact(hX a), { intros i h, dsimp at *, solve_by_elim [hX] }, { intros a b, dsimp at *, solve_by_elim }, }, end lemma integral_le_integral [measurable_space α] (m : measure α) (f g : α → ennreal) (h : f ≤ g) : (∫ f ðm) ≤ (∫ g ðm) := begin rw integral, rw integral, apply lintegral_mono, assumption, end noncomputable def char_prod [measurable_space α]{f : α → ennreal}{ε : ennreal}(hf : measurable f)(eh : ε > 0): simple_func α ennreal := ⟨ λ x, if (f(x) ≥ ε) then ε else 0, assume x, by letI : measurable_space ennreal := borel ennreal; exact measurable.if (is_measurable_le measurable_const hf) measurable_const measurable_const _ (is_closed_singleton.is_measurable), begin apply finite_subset (finite_union (finite_singleton ε) ((finite_singleton 0))), rintro _ ⟨a, rfl⟩, by_cases (f a ≥ ε); simp [h], end ⟩ @[simp] lemma char_prod_apply [measurable_space α]{f : α → ennreal}{ε : ennreal}(hf : measurable f)(eh : ε > 0) (a : α): (char_prod hf eh) a = if (f a ≥ ε) then ε else 0 := rfl /-- Markov's inequality. -/ theorem measure_fun_ge_le_integral [measurable_space α] [nonempty α] (m : measure α) {f : α → ennreal} (hf : measurable f) : ∀ (ε > 0), ε*m({x | f(x) ≥ ε}) ≤ ∫ f ðm := begin intros ε eh, let s := char_prod hf eh, have hsf : ∀ x, s x ≤ f x, { intro x, by_cases g : (f(x) ≥ ε), dsimp [s], split_ifs, exact g, dsimp [s], split_ifs, exact zero_le (f x), }, convert (integral_le_integral _ _ _ hsf), have seq : s = (simple_func.const α ε) * (χ ⟦{x : α | f x ≥ ε} ⟧),{ apply simple_func.ext, intro a, simp * at *, dunfold char_fun, rw [simple_func.restrict_apply, simple_func.const_apply], split_ifs, rw mul_one, rw mul_zero, apply (@is_measurable_le ennreal α _ _), exact measurable_const, assumption, }, rw seq, simp, rw [integral_const_mul m, integral_char_fun], apply (@is_measurable_le ennreal α _ _), exact measurable_const, assumption, apply simple_func.measurable, end /-- Chebyshev's inequality for a nondecreasing function `g`. -/ theorem measure_fun_ge_le_integral_comp [measurable_space α][nonempty α] (m : measure α) {f : α → ennreal} {g : ennreal → ennreal}(hf : measurable f) (hg : measurable g) (nondec : ∀ x y,x ≤ y → g x ≤ g y): ∀ (t > 0), g(t)*m({x | f(x) ≥ t}) ≤ ∫ g ∘ f ðm := begin intros t ht, have hsf : ∀ x, g(t) * (χ ⟦{x : α | f x ≥ t} ⟧ x) ≤ (g (f x)), { intro x, dunfold char_fun, rw [simple_func.restrict_apply, simple_func.const_apply], split_ifs, rw [mul_one], apply (@nondec _ _ h), finish, apply (@is_measurable_le ennreal α _ _), exact measurable_const, assumption, }, rw [←integral_char_fun, ←integral_const_mul m], apply (integral_le_integral m), exact hsf, apply simple_func.measurable, apply (@is_measurable_le ennreal α _ _), exact measurable_const, assumption, end end to_integration namespace giry_pi -- Auxilary results about infinite products of measure spaces. -- This section has to go back to `constructions` in `measure_theory/measurable_space`. Originally from Johannes' fork. instance pi.measurable_space (ι : Type*) (α : ι → Type*) [m : ∀i, measurable_space (α i)] : measurable_space (Πi, α i) := ⨆i, (m i).comap (λf, f i) instance pi.measurable_space_Prop (ι : Prop) (α : ι → Type*) [m : ∀i, measurable_space (α i)] : measurable_space (Πi, α i) := ⨆i, (m i).comap (λf, f i) lemma measurable_pi {ι : Type*} {α : ι → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] {f : β → Πi, α i} : measurable f ↔ (∀i, measurable (λb, f b i)):= begin rw [measurable, pi.measurable_space, supr_le_iff], refine forall_congr (assume i, _), rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], refl end lemma measurable_apply {ι : Type*} {α : ι → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] (f : β → Πi, α i) (i : ι) (hf : measurable f) : measurable (λb, f b i) := measurable_pi.1 hf _ lemma measurable_pi_Prop {ι : Prop} {α : ι → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] {f : β → Πi, α i} : measurable f ↔ (∀i, measurable (λb, f b i)):= begin rw [measurable, pi.measurable_space_Prop, supr_le_iff], refine forall_congr (assume i, _), rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], refl end lemma measurable_apply_Prop {p : Prop} {α : p → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] (f : β → Πi, α i) (h : p) (hf : measurable f) : measurable (λb, f b h) := measurable_pi_Prop.1 hf _ end giry_pi section giry_prod open to_integration variables {α : Type u} {β : Type u} {γ : Type v} /- Auxilary results about the Giry monad and binary products. The following results should go back to giry_monad.lean -/ /-- Right identity monad law for the Giry monad. -/ lemma giry.bind_return_comp [measurable_space α][measurable_space β] (D : measure α) {p : α → β} (hp : measurable p) : (doₐ (x : α) ←ₐ D ; ret (p x)) = p <$>ₐ D := measure.ext $ assume s hs, begin rw [measure.bind_apply hs _], rw [measure.map_apply hp hs], conv_lhs{congr, skip, funext, rw [measure.dirac_apply _ hs]}, transitivity, apply lintegral_supr_const, exact hp _ hs, rw one_mul, refl, exact measurable.comp measurable_dirac hp, end /-- Left identity monad law for compositions in the Giry monad -/ lemma giry.return_bind_comp [measurable_space α][measurable_space β] {p : α → measure β} {f : α → α} (hf : measurable f)(hp : measurable p) (a : α) : (doₐ x ←ₐ dirac a ; p (f x)) = p (f a) := measure.ext $ assume s hs, begin rw measure.bind_apply hs, rw measure.integral_dirac a, swap, exact measurable.comp hp hf, exact measurable.comp (measurable_coe hs) (measurable.comp hp hf), end def prod_measure [measurable_space α][measurable_space β] (μ : measure α) (ν : measure β) : measure (α × β) := doₐ x ←ₐ μ ; doₐ y ←ₐ ν ; ret (x, y) infixl ` ⊗ₐ `:55 := prod_measure instance prod.measure_space [measurable_space α] [measurable_space β] (μ : measure α) (ν : measure β) : measure_space (α × β) := ⟨ μ ⊗ₐ ν ⟩ lemma inl_measurable [measurable_space α][measurable_space β] : ∀ y : β, measurable (λ x : α, (x,y)) := assume y, begin apply measurable.prod, dsimp, exact measurable_id, dsimp, exact measurable_const, end lemma inr_measurable [measurable_space α][measurable_space β] : ∀ x : α, measurable (λ y : β, (x,y)) := assume y, begin apply measurable.prod, dsimp, exact measurable_const, dsimp, exact measurable_id, end lemma inl_measurable_dirac [measurable_space α][measurable_space β] : ∀ y : β, measurable (λ (x : α), ret (x, y)) := assume y, begin apply measurable_of_measurable_coe, intros s hs, simp [hs, supr_eq_if, mem_prod_eq], apply measurable_const.if _ measurable_const, apply measurable.preimage _ hs, apply measurable.prod, dsimp, exact measurable_id, dsimp, exact measurable_const, end lemma inr_measurable_dirac [measurable_space β][measurable_space α] : ∀ x : α, measurable (λ (y : β), ret (x, y)) := assume x, begin apply measurable_of_measurable_coe, intros s hs, simp [hs, supr_eq_if, mem_prod_eq], apply measurable_const.if _ measurable_const, apply measurable.preimage _ hs, apply measurable.prod, dsimp, exact measurable_const, dsimp, exact measurable_id, end lemma inr_section_is_measurable [measurable_space α] [measurable_space β] {E : set (α × β)} (hE : is_measurable E) (x : α) : is_measurable ({ y:β | (x,y) ∈ E}) := begin change (is_measurable ((λ z:β, (x,z))⁻¹' E)), apply inr_measurable, assumption, end lemma inl_section_is_measurable [measurable_space α] [measurable_space β] {E : set (α × β)} (hE : is_measurable E) (y : β) : is_measurable ({ x:α | (x,y) ∈ E}) := begin change (is_measurable ((λ z:α, (z,y))⁻¹' E)), apply inl_measurable, assumption, end lemma snd_comp_measurable [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} (hf : measurable f) (x : α) : measurable (λ y:β, f (x, y)) := (measurable.comp hf (inr_measurable _)) lemma fst_comp_measurable [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} (hf : measurable f) (y : β) : measurable ((λ x:α, f (x, y))) := (measurable.comp hf (inl_measurable _)) lemma measurable_pair_iff [measurable_space α] [measurable_space β] [measurable_space γ] (f : γ → α × β) : measurable f ↔ (measurable (prod.fst ∘ f) ∧ measurable (prod.snd ∘ f)) := iff.intro (assume h, and.intro (measurable.fst h) (measurable.snd h)) (assume ⟨h₁, h₂⟩, measurable.prod h₁ h₂) @[simp] lemma dirac.prod_apply [measurable_space α][measurable_space β]{A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) (a : α) (b : β) : (ret (a,b) : measure (α × β)) (A.prod B) = ((ret a : measure α) A) * ((ret b : measure β) B) := begin rw [dirac_apply, dirac_apply, dirac_apply, mem_prod_eq], dsimp, by_cases Ha: (a ∈ A); by_cases Hb: (b ∈ B), repeat {simp [Ha, Hb]}, repeat {assumption}, exact is_measurable.prod hA hB, end lemma prod.bind_ret_comp [measurable_space α] [measurable_space β] (μ : measure α) : ∀ y : β, (doₐ (x : α) ←ₐ μ; ret (x,y)) = (λ x, (x,y)) <$>ₐ μ := assume y, begin apply giry.bind_return_comp, apply measurable.prod, dsimp, exact measurable_id, dsimp, exact measurable_const, end -- TODO(Kody) : move this back to mathlib/measurable_space.lean lemma measure_rect_generate_from [measurable_space α] [measurable_space β] : prod.measurable_space = generate_from {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} := begin rw eq_iff_le_not_lt, split, { apply generate_from_le_generate_from, intros s hs, rcases hs with ⟨A₀, hA, rfl⟩ | ⟨B₀, hB, rfl⟩, existsi [A₀, univ], fsplit, ext1, cases x, simp, exact and.intro hA is_measurable.univ, existsi [univ, B₀], fsplit, ext1, cases x, simp, exact and.intro is_measurable.univ hB, }, { apply not_lt_of_le, apply measurable_space.generate_from_le, intros t ht, dsimp at ht, rcases ht with ⟨A, B, rfl, hA, hB⟩, exact is_measurable.prod hA hB, } end def measurable_prod_bind_ret [measurable_space α] [measurable_space β] (ν : probability_measure β): set(α × β) → Prop := λ s, measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) s) lemma measure_rect_inter [measurable_space α] [measurable_space β] : ∀t₁ t₂, t₁ ∈ {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} → t₂ ∈ {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} := begin rintros t₁ t₂ ⟨A, B, rfl, hA, hB⟩ ⟨A', B', rfl, hA', hB'⟩ hI, rw prod_inter_prod, existsi [(A ∩ A'),(B ∩ B')], fsplit, refl, exact and.intro (is_measurable.inter hA hA') (is_measurable.inter hB hB'), end lemma measurable_prod_bind_ret_empty [measurable_space α] [measurable_space β] (ν : probability_measure β): measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) ∅):= by simp ; exact measurable_const lemma measurable_prod_bind_ret_compl [measurable_space α] [measurable_space β] (ν : probability_measure β) : ∀ t : set (α × β), is_measurable t → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) t) → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) (- t)) := begin intros t ht hA, rw compl_eq_univ_diff, conv{congr, funext, rw [probability_measure.prob_diff _ (subset_univ _) is_measurable.univ ht]}, simp, refine measurable.comp _ hA, refine measurable.comp _ (measurable.sub measurable_const _), exact nnreal.continuous_of_real.measurable, exact nnreal.continuous_coe.measurable, end lemma measurable_prod_bind_ret_basic [measurable_space α] [measurable_space β] (ν : probability_measure β) : ∀ (t : set (α × β)),t ∈ {E : set (α × β) | ∃ (A : set α) (B : set β), E = set.prod A B ∧ is_measurable A ∧ is_measurable B} → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) t) := begin rintros t ⟨A, B, rfl, hA, hB⟩, conv{congr,funext,rw [_root_.bind_apply (is_measurable.prod hA hB) (prob_inr_measurable_dirac x)],}, refine measurable.comp _ _, exact measurable_to_nnreal, dsimp, conv{congr,funext,simp [coe_eq_to_measure]}, simp [prob.dirac_apply' hA hB], have h : measurable (λ (x : β), ((retₚ x).to_measure : measure β) B),{ conv{congr,funext,rw ret_to_measure,}, exact measurable_dirac_fun hB, }, conv {congr, funext, rw [integral_const_mul ν.to_measure h],}, refine measurable.ennreal_mul _ _, exact measurable_dirac_fun hA, exact measurable_const, end lemma measurable_prod_bind_ret_union [measurable_space α] [measurable_space β] (ν : probability_measure β): ∀h:ℕ → set (α × β), (∀i j, i ≠ j → h i ∩ h j ⊆ ∅) → (∀i, is_measurable (h i)) → (∀i, measurable(λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) (h i))) → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) (⋃i, h i)) := begin rintros h hI hA hB, unfold_coes, refine measurable.comp (measurable_of_measurable_nnreal measurable_id) _, conv{congr,funext,rw [m_Union _ hA hI,ennreal.tsum_eq_supr_nat]}, apply measurable_supr, intro i, apply finset.measurable_sum, intros i, have h := hB i, clear hB, refine measurable_of_ne_top _ _ _, assume x, refine probability_measure.to_measure_ne_top _ _, assumption, end -- Push this back to ennreal.lean lemma to_nnreal_mul (a b : ennreal) : ennreal.to_nnreal(a*b) = ennreal.to_nnreal(a) * ennreal.to_nnreal(b) := begin cases a; cases b, { simp [none_eq_top] }, { by_cases h : b = 0; simp [none_eq_top, some_eq_coe, h, top_mul] }, { by_cases h : a = 0; simp [none_eq_top, some_eq_coe, h, mul_top] }, { simp [some_eq_coe, coe_mul.symm, -coe_mul] } end @[simp] theorem prod.prob_measure_apply [measurable_space α] [measurable_space β][nonempty α] [nonempty β] (μ : probability_measure α) (ν : probability_measure β) {A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) : (μ ⊗ₚ ν) (A.prod B) = μ (A) * ν (B) := begin dunfold prod.prob_measure, rw _root_.bind_apply (is_measurable.prod hA hB), conv_lhs{congr, congr, skip, funext, erw [_root_.bind_apply ( is_measurable.prod hA hB) (prob_inr_measurable_dirac a)]}, simp[coe_eq_to_measure, prob.dirac_apply' hA hB], -- move this to probability_theory have h : measurable (λ (x : β), ((retₚ x).to_measure : measure β) B), { conv{congr,funext,rw ret_to_measure,}, exact measurable_dirac_fun hB, }, conv {congr, funext, congr, congr, skip, funext, rw [integral_const_mul ν.to_measure h,ret_to_measure,mul_comm],}, rw [prob.dirac_char_fun hB, integral_char_fun ν.to_measure hB], -- move this to measurable_space have g : ∀ a:α, ((ret a : measure α) A) < ⊤, { assume a, rw dirac_apply _ hA, by_cases(a ∈ A), simp[h],exact lt_top_iff_ne_top.2 one_ne_top, simp[h], }, conv_lhs{congr, congr, skip, funext, rw [coe_to_nnreal (lt_top_iff_ne_top.1 (mul_lt_top (to_measure_lt_top _ _) (g a)))]}, conv_lhs{congr, rw [integral_const_mul μ.to_measure (measurable_dirac_fun hA)]}, rw [dirac_char_fun hA, integral_char_fun _ hA, mul_comm, to_nnreal_mul], refl, apply prob.measurable_of_measurable_coe, exact ( @induction_on_inter _ (measurable_prod_bind_ret ν) ({E | ∃ (A : set α) (B : set β), (E = A.prod B) ∧ is_measurable A ∧ is_measurable B}) _ measure_rect_generate_from measure_rect_inter (measurable_prod_bind_ret_empty ν) (measurable_prod_bind_ret_basic ν) (measurable_prod_bind_ret_compl ν) (measurable_prod_bind_ret_union ν) ), end end giry_prod section fubini variables {α : Type u} {β : Type u} [measure_space α] [measure_space β] open to_integration local notation `∫` f `𝒹`m := integral m.to_measure f lemma integral_char_rect [measurable_space α] [measurable_space β] [n₁ : nonempty α] [n₂ : nonempty β](μ : probability_measure α) (ν : probability_measure β) {A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) : (∫ χ ⟦ A.prod B ⟧ 𝒹(μ ⊗ₚ ν)) = (μ A) * (ν B) := begin haveI := (nonempty_prod.2 (and.intro n₁ n₂)), rw [integral_char_fun _ (is_measurable.prod hA hB),←coe_eq_to_measure, (prod.prob_measure_apply _ _ hA hB)], simp, end --lemma measurable_integral_fst {f : α × β → ennreal}(hf : measurable f) (ν : probability_measure β) : measurable (λ x:α, (∫ (λ y:β, f(x,y)) 𝒹 ν)) := --begin -- conv{congr,funext,rw integral, rw @lintegral_eq_supr_eapprox_integral β {μ := ν.to_measure} (λ y, f(x,y)) (snd_comp_measurable hf _),}, -- refine measurable.supr _, -- assume i, -- dunfold simple_func.integral, -- sorry, --end end fubini section prod_measure_measurable /- This section aims to prove `measurable (λ x : α , f x ⊗ₚ g x)` using Dynkin's π-λ theorem. Push this back to giry_monad.lean -/ variables {α : Type u} {β : Type u} {γ : Type u} def measurable_prod_measure_pred [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g) : set (β × γ) → Prop := λ s : set (β × γ), measurable (λ b:α,(f b ⊗ₚ g b) s) lemma measurable_rect_empty {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g): measurable (λ b:α,(f b ⊗ₚ g b) ∅) := by simp ; exact measurable_const lemma measure_rect_union {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] (f : α → probability_measure β) (g : α → probability_measure γ) : ∀h:ℕ → set (β × γ), (∀i j, i ≠ j → h i ∩ h j ⊆ ∅) → (∀i, is_measurable (h i)) → (∀i, measurable (λ b:α,(f b ⊗ₚ g b) (h i))) → measurable (λ b:α,(f b ⊗ₚ g b) (⋃i, h i)) := begin rintros h hI hA hB, unfold_coes, conv{congr,funext,rw [m_Union _ hA hI]}, dsimp, conv{congr,funext,rw ennreal.tsum_eq_supr_nat,}, refine measurable.comp measurable_to_nnreal _, apply measurable_supr, intro i, apply finset.measurable_sum, assume i, refine measurable_of_ne_top _ _ _, assume a, refine probability_measure.to_measure_ne_top _ _, solve_by_elim, end lemma measurable_rect_compl {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ](f : α → probability_measure β) (g : α → probability_measure γ) : ∀ t : set (β × γ), is_measurable t → measurable (λ b:α,(f b ⊗ₚ g b) t) → measurable (λ b:α,(f b ⊗ₚ g b) (- t)) := begin intros t ht hA, rw compl_eq_univ_diff, conv{congr, funext, rw [probability_measure.prob_diff _ (subset_univ _) is_measurable.univ ht]}, simp, refine measurable.comp _ hA, refine measurable.comp _ (measurable.sub measurable_const _), exact nnreal.continuous_of_real.measurable, exact nnreal.continuous_coe.measurable, end -- Move back to Giry monad lemma measurable_measure_kernel [measurable_space α] [measurable_space β] {f : α → measure β} {A : set β} (hf : measurable f) (hA : is_measurable A) : measurable (λ a, f a A) := measurable.comp (measurable_coe hA) hf lemma measurable_rect_basic {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] [nonempty β] [nonempty γ] {f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g) : ∀ (t : set (β × γ)),t ∈ {E : set (β × γ) | ∃ (A : set β) (B : set γ), E = set.prod A B ∧ is_measurable A ∧ is_measurable B} → measurable (λ b:α,(f b ⊗ₚ g b) t) := begin rintros t ⟨A, B, rfl, hA, hB⟩, simp [prod.prob_measure_apply _ _ hA hB], exact measurable.mul (prob.measurable_measure_kernel hf hA) (prob.measurable_measure_kernel hg hB), end theorem measurable_pair_measure {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] [nonempty β] [nonempty γ]{f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g) : measurable (λ x : α , f x ⊗ₚ g x) := begin apply prob.measurable_of_measurable_coe, exact @induction_on_inter _ (measurable_prod_measure_pred hf hg) ({E | ∃ (A : set β) (B : set γ), (E = A.prod B) ∧ is_measurable A ∧ is_measurable B}) _ (measure_rect_generate_from) (measure_rect_inter) (measurable_rect_empty hf hg) (measurable_rect_basic hf hg) (measurable_rect_compl f g) (measure_rect_union f g), end end prod_measure_measurable section giry_vec /- Auxilary lemmas about vectors as iterated binary prodcuts. -/ variable {α : Type u} def vec : Type u → ℕ → Type u | A 0 := A | A (succ k) := A × vec A k @[simp] def kth_projn : Π {n}, vec α n → dfin (succ n) → α | 0 x _ := x | (succ n) x dfin.fz := x.fst | (succ n) (x,xs) (dfin.fs k) := kth_projn xs k def vec.set_prod {n : ℕ}(A : set α) (B : set (vec α n)) : set (vec α (succ n)) := do l ← A, xs ← B, pure $ (l,xs) instance nonempty.vec [nonempty α] : ∀ n, nonempty (vec α n) := λ n, begin induction n with k ih, rwa vec, rw vec, apply nonempty_prod.2, exact (and.intro _inst_1 ih) end instance vec.measurable_space (n : ℕ) [m : measurable_space α]: measurable_space (vec α n) := begin induction n with k ih, exact m, rw vec, exact (m.comap prod.fst ⊔ ih.comap prod.snd) end noncomputable def vec.prod_measure [measurable_space α] (μ : probability_measure α) : Π n : ℕ, probability_measure (vec α n) | 0 := μ | (succ k) := doₚ x ←ₚ μ ; doₚ xs ←ₚ (vec.prod_measure k); retₚ (x,xs) instance vec.measure_space [measurable_space α] (μ : probability_measure α) : Π n:ℕ, measure_space (vec α n) | 0 := ⟨ μ.to_measure ⟩ | (succ k) := ⟨ (vec.prod_measure μ _).to_measure ⟩ -- Why doesn't refl work here?! @[simp] lemma vec.prod_measure_eq (n : ℕ) [measurable_space α](μ : probability_measure α) : (vec.prod_measure μ (n+1)) = μ ⊗ₚ (vec.prod_measure μ n) := by dunfold vec.prod_measure;refl lemma vec.inl_measurable [measurable_space α] (n : ℕ): ∀ xs : vec α n, measurable (λ x : α, (x, xs)) := inl_measurable lemma vec.inr_measurable [measurable_space α] (n : ℕ): ∀ x : α, measurable (λ xs : vec α n,(x,xs)) := inr_measurable lemma vec.dirac_prod_apply [measurable_space α]{A : set α} {n : ℕ} {B : set (vec α n)} (hA : is_measurable A) (hB : is_measurable B) (a : α) (as : vec α n) : (ret (a,as) : measure (vec α (succ n))) (A.prod B) = ((ret a : measure α) A) * ((ret as : measure (vec α n)) B) := dirac.prod_apply hA hB _ _ @[simp] lemma vec.prod_measure_apply {n : ℕ} [measurable_space α][nonempty α] (μ : probability_measure α) (ν : probability_measure (vec α n)) {A : set α} {B : set (vec α n)} (hA : is_measurable A) (hB : is_measurable B) : (μ ⊗ₚ ν) (A.prod B) = μ (A) * ν (B) := prod.prob_measure_apply _ _ hA hB def vec_map {α: Type} {β: Type} (f: α → β): Π n: ℕ, vec α n → vec β n | 0 := λ x, f x | (nat.succ n) := λ v, (f v.fst,vec_map n v.snd) lemma kth_projn_map_comm {α: Type} {β: Type}: ∀ f: α → β, ∀ n: ℕ, ∀ v: vec α n, ∀ i: dfin (succ n), f (kth_projn v i) = kth_projn (vec_map f n v) i := begin intros f n, induction n; intros, { dunfold vec_map, cases i, simp, refl, }, { cases v, cases i, { simp, dunfold vec_map, simp, }, { simp,rw n_ih, refl, } } end lemma measurable_map {α: Type} {β: Type} [measurable_space α] [measurable_space β]: ∀ n: ℕ, ∀ f: α → β, measurable f → measurable (vec_map f n) := begin intros, induction n, { intros, dunfold vec_map, assumption, }, { intros, dunfold vec_map, apply measurable.prod; simp, { apply measurable.comp, assumption, apply measurable.fst, apply measurable_id, }, { apply measurable.comp, assumption, apply measurable.snd, apply measurable_id, } }, end end giry_vec section hoeffding_aux open complex real lemma abs_le_one_iff_ge_neg_one_le_one {x : ℝ} : (complex.abs x ≤ 1) ↔ (-1 ≤ x ∧ x ≤ 1) := by rw abs_of_real ; apply abs_le lemma abs_neg_exp_sub_one_le_double {x : ℝ} (h₁ : complex.abs x ≤ 1)(h₂ : x ≥ 0): complex.abs(exp(-x) - 1) ≤ 2*x := calc complex.abs(exp(-x) - 1) ≤ 2*complex.abs(-x) : @abs_exp_sub_one_le (-x) ((complex.abs_neg x).symm ▸ h₁) ... = 2*complex.abs(x) : by rw (complex.abs_neg x) ... = 2*x : by rw [abs_of_real,((abs_eq h₂).2)]; left; refl lemma neg_exp_ge {x : ℝ} (h₀ : 0 ≤ x) (h₁ : x ≤ 1) : 1 - 2 * x ≤ exp (-x) := begin have h : -(2*x) ≤ exp(-x) -1, { apply (abs_le.1 _).left, rw ←abs_of_real, simp [-add_comm, -sub_eq_add_neg], apply abs_neg_exp_sub_one_le_double _ h₀, rw abs_le_one_iff_ge_neg_one_le_one, split, linarith, assumption, }, linarith, end -- lemma pow_neg_exp_ge {x : ℝ} (h₀ : 0 ≤ x) (h₁ : x ≤ 1) (n : ℕ) : (1 - 2*x)^n ≤ exp (-n*x) := -- begin -- induction n with k ih, -- simp, -- rw _root_.pow_succ, simp [-sub_eq_add_neg], -- conv in (_ * x) {rw right_distrib}, rw real.exp_add, -- rw (neg_eq_neg_one_mul x).symm, -- apply mul_le_mul (neg_exp_ge h₀ h₁) ih _ _, swap, -- apply le_of_lt (exp_pos (-x)), -- sorry -- end end hoeffding_aux instance : conditionally_complete_linear_order nnreal := { Sup := Sup, Inf := Inf, le_cSup := assume s a x has, le_cSup x has, cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a x has, cInf_le x has, le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order, .. nnreal.order_bot }
7c856c6d4e43cbeaad7c3b146d4e9ec8604c5e72
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Parser/Extension.lean
e01c29f5c442de2d861ae4135cd9cf85b53291f7
[ "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
26,301
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ScopedEnvExtension import Lean.Parser.Basic import Lean.Parser.StrInterpolation import Lean.KeyedDeclsAttribute /-! Extensible parsing via attributes -/ namespace Lean namespace Parser builtin_initialize builtinTokenTable : IO.Ref TokenTable ← IO.mkRef {} /- Global table with all SyntaxNodeKind's -/ builtin_initialize builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet ← IO.mkRef {} def registerBuiltinNodeKind (k : SyntaxNodeKind) : IO Unit := builtinSyntaxNodeKindSetRef.modify fun s => s.insert k builtin_initialize registerBuiltinNodeKind choiceKind registerBuiltinNodeKind identKind registerBuiltinNodeKind strLitKind registerBuiltinNodeKind numLitKind registerBuiltinNodeKind scientificLitKind registerBuiltinNodeKind charLitKind registerBuiltinNodeKind nameLitKind builtin_initialize builtinParserCategoriesRef : IO.Ref ParserCategories ← IO.mkRef {} private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α := throw s!"parser category '{catName}' has already been defined" private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories := if categories.contains catName then throwParserCategoryAlreadyDefined catName else pure $ categories.insert catName initial /-- All builtin parser categories are Pratt's parsers -/ private def addBuiltinParserCategory (catName : Name) (behavior : LeadingIdentBehavior) : IO Unit := do let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParserCategoryCore categories catName { tables := {}, behavior := behavior} builtinParserCategoriesRef.set categories namespace ParserExtension inductive OLeanEntry where | token (val : Token) : OLeanEntry | kind (val : SyntaxNodeKind) : OLeanEntry | category (catName : Name) (behavior : LeadingIdentBehavior) | parser (catName : Name) (declName : Name) (prio : Nat) : OLeanEntry deriving Inhabited inductive Entry where | token (val : Token) : Entry | kind (val : SyntaxNodeKind) : Entry | category (catName : Name) (behavior : LeadingIdentBehavior) | parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Entry deriving Inhabited def Entry.toOLeanEntry : Entry → OLeanEntry | token v => OLeanEntry.token v | kind v => OLeanEntry.kind v | category c b => OLeanEntry.category c b | parser c d _ _ prio => OLeanEntry.parser c d prio structure State where tokens : TokenTable := {} kinds : SyntaxNodeKindSet := {} categories : ParserCategories := {} deriving Inhabited end ParserExtension open ParserExtension in abbrev ParserExtension := ScopedEnvExtension OLeanEntry Entry State private def ParserExtension.mkInitial : IO ParserExtension.State := do let tokens ← builtinTokenTable.get let kinds ← builtinSyntaxNodeKindSetRef.get let categories ← builtinParserCategoriesRef.get pure { tokens := tokens, kinds := kinds, categories := categories } private def addTokenConfig (tokens : TokenTable) (tk : Token) : Except String TokenTable := do if tk == "" then throw "invalid empty symbol" else match tokens.find? tk with | none => pure $ tokens.insert tk tk | some _ => pure tokens def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α := throw s!"unknown parser category '{catName}'" abbrev getCategory (categories : ParserCategories) (catName : Name) : Option ParserCategory := categories.find? catName def addLeadingParser (categories : ParserCategories) (catName : Name) (parserName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => let addTokens (tks : List Token) : Except String ParserCategories := let tks := tks.map $ fun tk => Name.mkSimple tk let tables := tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with leadingTable := tables.leadingTable.insert tk (p, prio) }) cat.tables pure $ categories.insert catName { cat with tables := tables } match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => let tables := { cat.tables with leadingParsers := (p, prio) :: cat.tables.leadingParsers } pure $ categories.insert catName { cat with tables := tables } private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) (prio : Nat) : PrattParsingTables := let addTokens (tks : List Token) : PrattParsingTables := let tks := tks.map fun tk => Name.mkSimple tk tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with trailingTable := tables.trailingTable.insert tk (p, prio) }) tables match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => { tables with trailingParsers := (p, prio) :: tables.trailingParsers } def addTrailingParser (categories : ParserCategories) (catName : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => pure $ categories.insert catName { cat with tables := addTrailingParserAux cat.tables p prio } def addParser (categories : ParserCategories) (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories := match leading, p with | true, p => addLeadingParser categories catName declName p prio | false, p => addTrailingParser categories catName p prio def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable := let newTokens := info.collectTokens [] newTokens.foldlM addTokenConfig tokenTable private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do let tokenTable ← builtinTokenTable.swap {} match addParserTokens tokenTable info with | Except.ok tokenTable => builtinTokenTable.set tokenTable | Except.error msg => throw (IO.userError s!"invalid builtin parser '{declName}', {msg}") def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : IO Unit := do let p := evalInsideQuot declName p let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParser categories catName declName leading p prio builtinParserCategoriesRef.set categories builtinSyntaxNodeKindSetRef.modify p.info.collectKinds updateBuiltinTokens p.info declName def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) (prio : Nat) : IO Unit := addBuiltinParser catName declName true p prio def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) (prio : Nat) : IO Unit := addBuiltinParser catName declName false p prio def ParserExtension.addEntryImpl (s : State) (e : Entry) : State := match e with | Entry.token tk => match addTokenConfig s.tokens tk with | Except.ok tokens => { s with tokens := tokens } | _ => unreachable! | Entry.kind k => { s with kinds := s.kinds.insert k } | Entry.category catName behavior => if s.categories.contains catName then s else { s with categories := s.categories.insert catName { tables := {}, behavior := behavior } } | Entry.parser catName declName leading parser prio => match addParser s.categories catName declName leading parser prio with | Except.ok categories => { s with categories := categories } | _ => unreachable! unsafe def mkParserOfConstantUnsafe (categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) := do let env := (← read).env let opts := (← read).opts match env.find? constName with | none => throw ↑s!"unknow constant '{constName}'" | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => let p ← IO.ofExcept $ env.evalConst Parser opts constName pure ⟨false, p⟩ | Expr.const `Lean.Parser.Parser _ _ => let p ← IO.ofExcept $ env.evalConst Parser opts constName pure ⟨true, p⟩ | Expr.const `Lean.ParserDescr _ _ => let d ← IO.ofExcept $ env.evalConst ParserDescr opts constName let p ← compileParserDescr d pure ⟨true, p⟩ | Expr.const `Lean.TrailingParserDescr _ _ => let d ← IO.ofExcept $ env.evalConst TrailingParserDescr opts constName let p ← compileParserDescr d pure ⟨false, p⟩ | _ => throw ↑s!"unexpected parser type at '{constName}' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected" @[implementedBy mkParserOfConstantUnsafe] constant mkParserOfConstantAux (categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) /- Parser aliases for making `ParserDescr` extensible -/ inductive AliasValue (α : Type) where | const (p : α) | unary (p : α → α) | binary (p : α → α → α) abbrev AliasTable (α) := NameMap (AliasValue α) def registerAliasCore {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) (value : AliasValue α) : IO Unit := do unless (← IO.initializing) do throw ↑"aliases can only be registered during initialization" if (← mapRef.get).contains aliasName then throw ↑s!"alias '{aliasName}' has already been declared" mapRef.modify (·.insert aliasName value) def getAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (Option (AliasValue α)) := do return (← mapRef.get).find? aliasName def getConstAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO α := do match (← getAlias mapRef aliasName) with | some (AliasValue.const v) => pure v | some (AliasValue.unary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes one argument" | some (AliasValue.binary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes two arguments" | none => throw ↑s!"parser '{aliasName}' was not found" def getUnaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α) := do match (← getAlias mapRef aliasName) with | some (AliasValue.unary v) => pure v | some _ => throw ↑s!"parser '{aliasName}' does not take one argument" | none => throw ↑s!"parser '{aliasName}' was not found" def getBinaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α → α) := do match (← getAlias mapRef aliasName) with | some (AliasValue.binary v) => pure v | some _ => throw ↑s!"parser '{aliasName}' does not take two arguments" | none => throw ↑s!"parser '{aliasName}' was not found" abbrev ParserAliasValue := AliasValue Parser builtin_initialize parserAliasesRef : IO.Ref (NameMap ParserAliasValue) ← IO.mkRef {} -- Later, we define macro registerParserAlias! which registers a parser, formatter and parenthesizer def registerAlias (aliasName : Name) (p : ParserAliasValue) : IO Unit := do registerAliasCore parserAliasesRef aliasName p instance : Coe Parser ParserAliasValue := { coe := AliasValue.const } instance : Coe (Parser → Parser) ParserAliasValue := { coe := AliasValue.unary } instance : Coe (Parser → Parser → Parser) ParserAliasValue := { coe := AliasValue.binary } def isParserAlias (aliasName : Name) : IO Bool := do match (← getAlias parserAliasesRef aliasName) with | some _ => pure true | _ => pure false def ensureUnaryParserAlias (aliasName : Name) : IO Unit := discard $ getUnaryAlias parserAliasesRef aliasName def ensureBinaryParserAlias (aliasName : Name) : IO Unit := discard $ getBinaryAlias parserAliasesRef aliasName def ensureConstantParserAlias (aliasName : Name) : IO Unit := discard $ getConstAlias parserAliasesRef aliasName partial def compileParserDescr (categories : ParserCategories) (d : ParserDescr) : ImportM Parser := let rec visit : ParserDescr → ImportM Parser | ParserDescr.const n => getConstAlias parserAliasesRef n | ParserDescr.unary n d => return (← getUnaryAlias parserAliasesRef n) (← visit d) | ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parserAliasesRef n) (← visit d₁) (← visit d₂) | ParserDescr.node k prec d => return leadingNode k prec (← visit d) | ParserDescr.nodeWithAntiquot n k d => return nodeWithAntiquot n k (← visit d) (anonymous := true) | ParserDescr.sepBy p sep psep trail => return sepBy (← visit p) sep (← visit psep) trail | ParserDescr.sepBy1 p sep psep trail => return sepBy1 (← visit p) sep (← visit psep) trail | ParserDescr.trailingNode k prec lhsPrec d => return trailingNode k prec lhsPrec (← visit d) | ParserDescr.symbol tk => return symbol tk | ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol tk includeIdent | ParserDescr.parser constName => do let (_, p) ← mkParserOfConstantAux categories constName visit; pure p | ParserDescr.cat catName prec => match getCategory categories catName with | some _ => pure $ categoryParser catName prec | none => IO.ofExcept $ throwUnknownParserCategory catName visit d def mkParserOfConstant (categories : ParserCategories) (constName : Name) : ImportM (Bool × Parser) := mkParserOfConstantAux categories constName (compileParserDescr categories) structure ParserAttributeHook where /- Called after a parser attribute is applied to a declaration. -/ postAdd (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit builtin_initialize parserAttributeHooks : IO.Ref (List ParserAttributeHook) ← IO.mkRef {} def registerParserAttributeHook (hook : ParserAttributeHook) : IO Unit := do parserAttributeHooks.modify fun hooks => hook::hooks def runParserAttributeHooks (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit := do let hooks ← parserAttributeHooks.get hooks.forM fun hook => hook.postAdd catName declName builtin builtin_initialize registerBuiltinAttribute { name := `runBuiltinParserAttributeHooks, descr := "explicitly run hooks normally activated by builtin parser attributes", add := fun decl stx persistent => do Attribute.Builtin.ensureNoArgs stx runParserAttributeHooks Name.anonymous decl (builtin := true) } builtin_initialize registerBuiltinAttribute { name := `runParserAttributeHooks, descr := "explicitly run hooks normally activated by parser attributes", add := fun decl stx persistent => do Attribute.Builtin.ensureNoArgs stx runParserAttributeHooks Name.anonymous decl (builtin := false) } private def ParserExtension.OLeanEntry.toEntry (s : State) : OLeanEntry → ImportM Entry | token tk => return Entry.token tk | kind k => return Entry.kind k | category c l => return Entry.category c l | parser catName declName prio => do let (leading, p) ← mkParserOfConstant s.categories declName Entry.parser catName declName leading p prio builtin_initialize parserExtension : ParserExtension ← registerScopedEnvExtension { name := `parserExt mkInitial := ParserExtension.mkInitial addEntry := ParserExtension.addEntryImpl toOLeanEntry := ParserExtension.Entry.toOLeanEntry ofOLeanEntry := ParserExtension.OLeanEntry.toEntry } def isParserCategory (env : Environment) (catName : Name) : Bool := (parserExtension.getState env).categories.contains catName def addParserCategory (env : Environment) (catName : Name) (behavior : LeadingIdentBehavior) : Except String Environment := do if isParserCategory env catName then throwParserCategoryAlreadyDefined catName else return parserExtension.addEntry env <| ParserExtension.Entry.category catName behavior def leadingIdentBehavior (env : Environment) (catName : Name) : LeadingIdentBehavior := match getCategory (parserExtension.getState env).categories catName with | none => LeadingIdentBehavior.default | some cat => cat.behavior def mkCategoryAntiquotParser (kind : Name) : Parser := mkAntiquot kind.toString none -- helper decl to work around inlining issue https://github.com/leanprover/lean4/commit/3f6de2af06dd9a25f62294129f64bc05a29ea912#r41340377 @[inline] private def mkCategoryAntiquotParserFn (kind : Name) : ParserFn := (mkCategoryAntiquotParser kind).fn def categoryParserFnImpl (catName : Name) : ParserFn := fun ctx s => let catName := if catName == `syntax then `stx else catName -- temporary Hack let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | some cat => prattParser catName cat.tables cat.behavior (mkCategoryAntiquotParserFn catName) ctx s | none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'") @[builtinInit] def setCategoryParserFnRef : IO Unit := categoryParserFnRef.set categoryParserFnImpl def addToken (tk : Token) (kind : AttributeKind) : AttrM Unit := do -- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail. -- So, we must run it here to handle exception. discard <| ofExcept <| addTokenConfig (parserExtension.getState (← getEnv)).tokens tk parserExtension.add (ParserExtension.Entry.token tk) kind def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment := parserExtension.addEntry env <| ParserExtension.Entry.kind k def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool := let kinds := (parserExtension.getState env).kinds kinds.contains k def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := do let kinds := (parserExtension.getState env).kinds kinds.foldl (fun ks k _ => k::ks) [] def getTokenTable (env : Environment) : TokenTable := (parserExtension.getState env).tokens def mkInputContext (input : String) (fileName : String) : InputContext := { input := input, fileName := fileName, fileMap := input.toFileMap } def mkParserContext (ictx : InputContext) (pmctx : ParserModuleContext) : ParserContext := { prec := 0, toInputContext := ictx, toParserModuleContext := pmctx, tokens := getTokenTable pmctx.env } def mkParserState (input : String) : ParserState := { cache := initCacheForInput input } /- convenience function for testing -/ def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax := let c := mkParserContext (mkInputContext input fileName) { env := env, options := {} } let s := mkParserState input let s := whitespace c s let s := categoryParserFnImpl catName c s if s.hasError then Except.error (s.toErrorMsg c) else if input.atEnd s.pos then Except.ok s.stxStack.back else Except.error ((s.mkError "end of input").toErrorMsg c) def declareBuiltinParser (env : Environment) (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := let name := `_regBuiltinParser ++ declName let type := mkApp (mkConst `IO) (mkConst `Unit) let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkNatLit prio] let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error _ => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'")) | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) def declareLeadingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM? declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser catName declName prio def declareTrailingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM? declareBuiltinParser env `Lean.Parser.addBuiltinTrailingParser catName declName prio def getParserPriority (args : Syntax) : Except String Nat := match args.getNumArgs with | 0 => pure 0 | 1 => match (args.getArg 0).isNatLit? with | some prio => pure prio | none => throw "invalid parser attribute, numeral expected" | _ => throw "invalid parser attribute, no argument or numeral expected" private def BuiltinParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit := do let prio ← Attribute.Builtin.getPrio stx unless kind == AttributeKind.global do throwError "invalid attribute '{attrName}', must be global" let decl ← getConstInfo declName let env ← getEnv match decl.type with | Expr.const `Lean.Parser.TrailingParser _ _ => do let env ← declareTrailingBuiltinParser env catName declName prio setEnv env | Expr.const `Lean.Parser.Parser _ _ => do let env ← declareLeadingBuiltinParser env catName declName prio setEnv env | _ => throwError "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)" runParserAttributeHooks catName declName (builtin := true) /- The parsing tables for builtin parsers are "stored" in the extracted source code. -/ def registerBuiltinParserAttribute (attrName : Name) (catName : Name) (behavior := LeadingIdentBehavior.default) : IO Unit := do addBuiltinParserCategory catName behavior registerBuiltinAttribute { name := attrName, descr := "Builtin parser", add := fun declName stx kind => liftM $ BuiltinParserAttribute.add attrName catName declName stx kind, applicationTime := AttributeApplicationTime.afterCompilation } private def ParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (attrKind : AttributeKind) : AttrM Unit := do let prio ← Attribute.Builtin.getPrio stx let env ← getEnv let opts ← getOptions let categories := (parserExtension.getState env).categories let p ← mkParserOfConstant categories declName let leading := p.1 let parser := p.2 let tokens := parser.info.collectTokens [] tokens.forM fun token => do try addToken token attrKind catch | Exception.error ref msg => throwError "invalid parser '{declName}', {msg}" | ex => throw ex let kinds := parser.info.collectKinds {} kinds.forM fun kind _ => modifyEnv fun env => addSyntaxNodeKind env kind let entry := ParserExtension.Entry.parser catName declName leading parser prio match addParser categories catName declName leading parser prio with | Except.error ex => throwError ex | Except.ok _ => parserExtension.add entry attrKind runParserAttributeHooks catName declName (builtin := false) def mkParserAttributeImpl (attrName : Name) (catName : Name) : AttributeImpl where name := attrName descr := "parser" add declName stx attrKind := ParserAttribute.add attrName catName declName stx attrKind applicationTime := AttributeApplicationTime.afterCompilation /- A builtin parser attribute that can be extended by users. -/ def registerBuiltinDynamicParserAttribute (attrName : Name) (catName : Name) : IO Unit := do registerBuiltinAttribute (mkParserAttributeImpl attrName catName) @[builtinInit] private def registerParserAttributeImplBuilder : IO Unit := registerAttributeImplBuilder `parserAttr fun args => match args with | [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName | _ => throw "invalid parser attribute implementation builder arguments" def registerParserCategory (env : Environment) (attrName : Name) (catName : Name) (behavior := LeadingIdentBehavior.default) : IO Environment := do let env ← IO.ofExcept $ addParserCategory env catName behavior registerAttributeOfBuilder env `parserAttr [DataValue.ofName attrName, DataValue.ofName catName] -- declare `termParser` here since it is used everywhere via antiquotations builtin_initialize registerBuiltinParserAttribute `builtinTermParser `term builtin_initialize registerBuiltinDynamicParserAttribute `termParser `term -- declare `commandParser` to break cyclic dependency builtin_initialize registerBuiltinParserAttribute `builtinCommandParser `command builtin_initialize registerBuiltinDynamicParserAttribute `commandParser `command @[inline] def commandParser (rbp : Nat := 0) : Parser := categoryParser `command rbp def notFollowedByCategoryTokenFn (catName : Name) : ParserFn := fun ctx s => let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | none => s.mkUnexpectedError s!"unknown parser category '{catName}'" | some cat => let (s, stx) := peekToken ctx s match stx with | Except.ok (Syntax.atom _ sym) => if ctx.quotDepth > 0 && sym == "$" then s else match cat.tables.leadingTable.find? (Name.mkSimple sym) with | some _ => s.mkUnexpectedError (toString catName) | _ => s | Except.ok _ => s | Except.error _ => s @[inline] def notFollowedByCategoryToken (catName : Name) : Parser := { fn := notFollowedByCategoryTokenFn catName } abbrev notFollowedByCommandToken : Parser := notFollowedByCategoryToken `command abbrev notFollowedByTermToken : Parser := notFollowedByCategoryToken `term end Parser end Lean
5a4ecd1d6251a34f5832e9503e963bc0f33ab33a
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Init/Core.lean
de20f0154169b16eb95e80c872fb4f225c3fe764
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,229
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 notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.SizeOf universes u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /- Remark: thunks have an efficient implementation in the runtime. -/ structure Thunk (α : Type u) : Type u where fn : Unit → α attribute [extern "lean_mk_thunk"] Thunk.mk @[noinline, extern "lean_thunk_pure"] protected def Thunk.pure {α : Type u} (a : α) : Thunk α := ⟨fun _ => a⟩ @[noinline, extern "lean_thunk_get_own"] protected def Thunk.get {α : Type u} (x : @& Thunk α) : α := x.fn () @[noinline, extern "lean_thunk_map"] protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[noinline, extern "lean_thunk_bind"] protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : Eq a b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop where intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff /- Eq basic support -/ inductive Sum (α : Type u) (β : Type v) where | inl (val : α) : Sum α β | inr (val : β) : Sum α β inductive PSum (α : Sort u) (β : Sort v) where | inl (val : α) : PSum α β | inr (val : β) : PSum α β structure Sigma {α : Type u} (β : α → Type v) where fst : α snd : β fst attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) where fst : α snd : β fst inductive Exists {α : Sort u} (p : α → Prop) : Prop where | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) where | done : α → ForInStep α | yield : α → ForInStep α class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β export ForIn (forIn) /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) where | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) where | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) where | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) where | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) where Equiv : α → α → Prop infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) where emptyCollection : α /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u where pure :: (get : α) attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /- Some type that is not a scalar value in our runtime. -/ structure NonScalar where val : Nat /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u where | mk (v : Nat) : PNonScalar theorem natAddZero (n : Nat) : n + 0 = n := rfl theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl /- Boolean operators -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem notFalse : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variable {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem falseOfNe : a ≠ a → False := Ne.irrefl theorem neFalseOfSelf : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem neTrueOfNot : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have ¬True from h ▸ hnp this trivial theorem trueNeFalse : ¬True = False := neFalseOfSelf trivial end Ne section variable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := eqOfHEq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : a ≅ b) : b ≅ a := HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a) theorem heqOfEq (h : a = a') : a ≅ a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := HEq.subst h₂ h₁ theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := HEq.trans h₁ (heqOfEq h₂) theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := HEq.trans (heqOfEq h₁) h₂ def typeEqOfHEq (h : a ≅ b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α) end theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : {a a' : α} → (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p | a, _, rfl, p => HEq.refl p theorem heqOfEqRecEq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by subst h₁ apply heqOfEq exact h₂ done theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α, _, rfl, a => HEq.refl a variable {a b c d : Prop} theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false := match h with | isFalse h => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := @decide p d theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := @decideEqTrue _ d h theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := @ofDecideEqTrue _ d h theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := @ofDecideEqFalse _ d h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse notFalse namespace Decidable variable {p q : Prop} @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem ofNotNot [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variable {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /- if-then-else expression theorems -/ theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | (isTrue hc) => rfl | (isFalse hnc) => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | (isTrue hc) => dT | (isFalse hc) => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | (isTrue hc) => dT hc | (isFalse hc) => dE hc /- Inhabited -/ instance : Inhabited Prop where default := True deriving instance Inhabited for Bool, NonScalar, PNonScalar, True, ForInStep class inductive Nonempty (α : Sort u) : Prop where | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α where val := arbitrary theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class Subsingleton (α : Sort u) : Prop where intro :: allEq : (a b : α) → a = b protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := h.allEq protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by subst h₂ apply heqOfEq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | (isTrue t₁) => fun | (isTrue t₂) => proofIrrel t₁ t₂ ▸ rfl | (isFalse f₂) => absurd t₁ f₂ | (isFalse f₁) => fun | (isTrue t₂) => absurd t₂ f₁ | (isFalse f₂) => proofIrrel f₁ f₂ ▸ rfl theorem recSubsingleton {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.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | (isTrue h) => h₃ h | (isFalse h) => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where refl : ∀ x, r x x symm : ∀ {x y}, r x y → r y x trans : ∀ {x y z}, r x y → r y z → r x z def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variable {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where default := ⟨a, h⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /- Sum -/ section variable {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where default := Sum.inl arbitrary instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where default := Sum.inr arbitrary instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | (Sum.inl a), (Sum.inl b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inr b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h) | (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h) end /- Product -/ section variable {α : Type u} {β : Type v} instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (arbitrary, arbitrary) instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun ⟨a, b⟩ ⟨a', b'⟩ => match (decEq a a') with | (isTrue e₁) => match (decEq b b') with | (isTrue e₂) => isTrue (e₁ ▸ e₂ ▸ rfl) | (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂)) | (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁)) instance [BEq α] [BEq β] : BEq (α × β) where beq := fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂ instance [HasLess α] [HasLess β] : HasLess (α × β) where Less s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance prodHasDecidableLt [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /- Dependent products -/ theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /- Universe polymorphic unit -/ theorem punitEq (a b : PUnit) : a = b := by cases a; cases b; exact rfl theorem punitEqPUnit (a : PUnit) : a = () := punitEq a () instance : Subsingleton PUnit := Subsingleton.intro punitEq instance : Inhabited PUnit where default := ⟨⟩ instance : DecidableEq PUnit := fun a b => isTrue (punitEq a b) /- Setoid -/ class Setoid (α : Sort u) where r : α → α → Prop iseqv {} : Equivalence r instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variable {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := Quot.rec f h q protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → f a ≅ f b) : motive q := Quot.recOn q f fun a b p => eqOfHEq <| have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRecHEq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q := Quot.ind protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.existsRep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (c : (a b : α) → (p : a ≈ b) → f a ≅ f b) : motive q := Quot.hrecOn q f c end section universes uA uB uC variable {α : Sort uA} {β : Sort uB} {φ : Sort uC} variable [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₃ [s₃ : Setoid φ] {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b := fun h => eqImpRel h end Exact section universes uA uB uC variable {α : Sort uA} {β : Sort uB} variable [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s apply g end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂ (fun a₁ a₂ => match (d a₁ a₂) with | (isTrue h₁) => isTrue (Quotient.sound h₁) | (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂)) /- Function extensionality -/ namespace Function variable {α : Sort u} {β : α → Sort v} def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl, symm := Equiv.symm, trans := Equiv.trans } end Function section open Quotient variable {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) := ⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩ /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => Subsingleton.elim _ _) s instance {α} : Subsingleton (Squash α) := ⟨fun a b => Squash.ind (motive := fun a => a = b) (fun a => Squash.ind (motive := fun b => Squash.mk a = b) (fun b => show Quot.mk _ a = Quot.mk _ b by apply Quot.sound; exact trivial) b) a⟩ namespace Lean /- Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your developement using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ constant reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
29c065587e47e9ca5b37b7585f4d797003da36f4
75c54c8946bb4203e0aaf196f918424a17b0de99
/old/language_term_ln.lean
e204449c11a26deea6a3cda62faf663eae0eb535
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
4,679
lean
/- 2018-10-12T21:52:34 Locally nameless formulas, built off Floris' preterms ---Jesse I wanted to avoid the headache over shifts (at the cost of needing to define a well-formedness predicate on terms); my implementation of locally nameless formulas is based off Chargueraud's paper (thanks for the pointer Jeremy!). TODO: - finish writing the coercion for variable lists - finish writing the substitution functions - add a well-formedness predicate -/ structure Language := (relations : Π n : nat, Type) (functions : Π n : nat, Type) section parameter L : Language /- preterm n is a partially applied term. if applied to n terms, it becomes a term -/ inductive preterm : ℕ → Type | bvar : ℕ → preterm 0 | fvar : string → preterm 0 | func : ∀ {n : nat}, L.functions n → preterm n | apply : ∀ {n : nat}, preterm (n + 1) → preterm 0 → preterm n open preterm def term := preterm 0 -- /- raise_depth_term _ t n m raises variables in t which are at least m by n -/ -- def raise_depth_term : ∀ {l}, preterm l → ℕ → ℕ → preterm l -- | _ (var L k) n m := if m ≤ k then var (k+m) else var k -- | _ (func f) n m := func f -- | _ (apply t1 t2) n m := apply (raise_depth_term t1 n m) (raise_depth_term t2 n m) -- /- substitute_term t s n substitutes s for (var n) and reduces the level of all variables above n by 1 -/ -- def substitute_term : ∀ {l}, preterm l → term → ℕ → preterm l -- | _ (var L k) s n := if k < n then var k else if k > n then var (k-1) else s -- | _ (func f) s n := func f -- | _ (apply t1 t2) s n := apply (substitute_term t1 s n) (substitute_term t2 s n) /-- Given a preterm, return a list of free variables which occur in it--/ def free_vars_preterm : Π n : ℕ, preterm n → list string | _ (bvar L k) := [] | _ (fvar L s) := [s] | _ (@func L _ f) := [] | _ (@apply L n t1 t2) := (free_vars_preterm (n+1) t1 ∪ free_vars_preterm 0 t2) def free_vars_term : term → list string := free_vars_preterm 0 lemma free_var_preterm_coercionl (n : ℕ) (t1 : preterm (n+1)) (t2 : term) : {x : string // x ∈ (free_vars_preterm (n+1) t1)} → {x : string // x ∈ (free_vars_preterm n (apply t1 t2))} := sorry def substitute_preterm : Π n : ℕ, Π (t : preterm n), term → {x : string // x ∈ (free_vars_preterm n t)} → preterm n | _ (bvar L k) t x := (bvar k) | _ (fvar L s) t x := sorry | _ (@func L _ f) t x := (func f) | _ (@apply L n t1 t2) t x := sorry end section parameter L : Language /- preformula n is a partially applied formula. if applied to n terms, it becomes a formula -/ inductive preformula : ℕ → Type | true : preformula 0 | false : preformula 0 | equal : (term L) → (term L) → preformula 0 | rel : ∀ {n : nat}, L.relations n → preformula n | apprel : ∀ {n : nat}, preformula (n + 1) → (term L) → preformula n | imp : preformula 0 → preformula 0 → preformula 0 | all : preformula 0 → preformula 0 open preformula def formula := preformula 0 def free_vars_preformula : Π n : ℕ, preformula n → list string | _ (true L) := [] | _ (false L) := [] | _ (equal t1 t2) := free_vars_term L t1 ∪ free_vars_term L t2 | _ (@rel L n R) := [] | _ (@apprel L n ψ t) := free_vars_preformula _ ψ ∪ free_vars_term L t | _ (imp ϕ ψ) := free_vars_preformula _ ϕ ∪ free_vars_preformula _ ψ | _ (all ψ) := free_vars_preformula _ ψ def free_vars_formula : formula → list string := free_vars_preformula 0 -- def raise_depth_formula : ∀ {l}, preformula l → ℕ → ℕ → preformula l -- | _ (true L) n m := true -- | _ (false L) n m := false -- | _ (equal t1 t2) n m := equal (raise_depth_term t1 n m) (raise_depth_term t2 n m) -- | _ (rel R) n m := rel R -- | _ (apprel f t) n m := apprel (raise_depth_formula f n m) (raise_depth_term t n m) -- | _ (imp f1 f2) n m := imp (raise_depth_formula f1 n m) (raise_depth_formula f2 n m) -- | _ (all f) n m := all (raise_depth_formula f n (m+1)) def substitute_formula : ∀ {l}, preformula l → (term L) → ℕ → preformula l | _ (true L) s n := true | _ (false L) s n := false | _ (equal t1 t2) s n := equal (substitute_term L t1 s n) (substitute_term L t2 s n) | _ (rel R) s n := rel R | _ (apprel f t) s n := apprel (substitute_formula f s n) (substitute_term t s n) | _ (imp f1 f2) s n := imp (substitute_formula f1 s n) (substitute_formula f2 s n) | _ (all f) s n := all (substitute_formula f s (n+1)) def substitute_preformula : Π n : ℕ, Π (ψ : preformula n), term → {x : string // x ∈ (free_vars_preformula _ ψ)} → preformula n | _ (true L) t x := true | _ (false L) t x := false | _ (equal t1 t2) := equal (substitute_preformula _ _ _ _ t1) (substitute_preformula _ _ _ _ t2) end
883c4e899ad7f55223b8fa56a59cdd6d0472cbc4
274748215b6d042f0d9c9a505f9551fa8e0c5f38
/src/affine_algebraic_set/intersection.lean
16612961424c776b5d0db7fafece75448dc6f1ce
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M4P33
878ecb515c77d20cc799ff1ebd78f1bf4fd65c12
1a179372db71ad6802d11eacbc1f02f327d55f8f
refs/heads/master
1,607,519,867,193
1,583,344,297,000
1,583,344,297,000
233,316,107
59
4
Apache-2.0
1,579,285,778,000
1,578,788,367,000
Lean
UTF-8
Lean
false
false
2,032
lean
/- The intersection of algebraic sets is an algebraic set. Kevin Buzzard -/ import affine_algebraic_set.basic -- the basic theory of affine algebraic sets. /- # The intersection of (any number of) affine algebraic sets is affine. Let k be a field and let n be a natural number. We prove the following theorem in this file: Theorem. If I is an index set, and for each i ∈ I we have an affine algebraic subset Vᵢ of kⁿ, then the intersection ⋂_{i ∈ I} Vᵢ is also an affine algebraic subset of kⁿ. Lean version: ** TODO Maths proof: if Vᵢ is cut out by the set Sᵢ ⊆ k[X_1,X_2,…,X_n] and we consider the set S = ⋃_{i ∈ I} Sᵢ then it is straightforward to check that this works. ## References Martin Orr's lecture notes at https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/ ## Tags algebraic geometry, algebraic variety -/ -- end of docstring; code starts here. -- We're proving theorems about affine algebraic sets so the names of the theorems -- should start with "affine_algebraic_set". namespace affine_algebraic_set -- let k be a field variables {k : Type*} [discrete_field k] -- and let σ be a set of indexes for our polynomial variables e.g. σ = {1,2,...,n} variable {σ : Type*} -- We're working with multivariable polynomials, so let's get access to their notation open mv_polynomial -- this should be proved by general nonsense really. /-- An arbitrary intersection of affine algebraic subsets of kⁿ is an affine algebraic subset of kⁿ -/ def Inter (I : Type*) (V : I → affine_algebraic_set k σ) : affine_algebraic_set k σ := { carrier := ⋂ (i : I), (V i : set (σ → k)), -- the underlying set is the union of the two sets defining V and W is_algebraic' := -- We now need to prove that the union is cut out by some set of polynomials. begin use ⋃ (i : I), (classical.some (V i).is_algebraic), ext x, rw 𝕍_Union, congr', funext i, exact classical.some_spec (V i).is_algebraic, end } end affine_algebraic_set
2bbf4cb2817d89aaf4ec464290b79402771bfb90
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/export.lean
7983c99a683f4cc915215355ef1de550b42a0663
[ "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
206
lean
import data.nat constants a b : nat namespace boo export nat (rec add) check a + b check nat.add check boo.add check add end boo check boo.rec open boo check a + b check boo.rec check nat.rec
1f14a5946cf48ae1076431a5e11457b6c464252c
367134ba5a65885e863bdc4507601606690974c1
/src/field_theory/minpoly.lean
d437ddc4ebebbd971697b89263e960832970fceb
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
17,956
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import data.polynomial.field_division import ring_theory.integral_closure import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ open_locale classical open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Let `B` be an `A`-algebra, and `x` an element of `B` that is integral over `A` so we have some term `hx : is_integral A x`. The minimal polynomial `minpoly A x` of `x` is a monic polynomial of smallest degree that has `x` as its root. For instance, if `V` is a `K`-vector space for some field `K`, and `f : V →ₗ[K] V` then the minimal polynomial of `f` is `minpoly f.is_integral`. -/ noncomputable def minpoly (x : B) : polynomial A := if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /--A minimal polynomial is monic.-/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := ne_zero_of_monic (monic hx) lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /--An element is a root of its minimal polynomial.-/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (well_founded.min_mem degree_lt_wf _ hx).2 }, { exact aeval_zero _ } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, subring.mem_top (-(minpoly A x).coeff 0), key.symm⟩, end /--The defining property of the minimal polynomial of an element x: it is the monic polynomial with smallest degree that has x as its root.-/ lemma min {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end -- TODO(Commelin, Brasca): this is a duplicate /-- If an element `x` is a root of a nonzero monic polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/ lemma degree_le_of_monic {p : polynomial A} (hmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := min A x hmonic (by simp [hp]) end ring section integral_domain variables [integral_domain A] section ring variables [ring B] [algebra A B] [nontrivial B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj [nontrivial A] (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1, { apply with_bot.coe_le_coe.1, rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)), with_top.coe_one, ←degree_X_sub_C a], refine min A (algebra_map A B a) (monic_X_sub_C a) _, simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] }, have hdeg : (minpoly A (algebra_map A B a)).degree = 1, { apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2, apply le_antisymm hdegle (nat_degree_pos (@is_integral_algebra_map A B _ _ _ a)) }, have hrw := eq_X_add_C_of_degree_eq_one hdeg, simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul, monic.leading_coeff, ring_hom.map_one] at hrw, have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a, { have hroot := aeval A (algebra_map A B a), rw [hrw, add_comm] at hroot, simp only [aeval_C, aeval_X, aeval_add] at hroot, replace hroot := eq_neg_of_add_eq_zero hroot, rw [←ring_hom.map_neg _ a] at hroot, exact (hf hroot) }, rw hrw, simp only [h0, ring_hom.map_neg, sub_eq_add_neg], end variables (A x) /-- A minimal polynomial is not a unit. -/ lemma not_is_unit : ¬ is_unit (minpoly A x) := begin by_cases hx : is_integral A x, { assume H, exact (ne_of_lt (degree_pos hx)).symm (degree_eq_zero_of_is_unit H) }, { delta minpoly, rw dif_neg hx, simp only [not_is_unit_zero, not_false_iff] } end end ring section domain variables [domain B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : polynomial A} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minpoly.min A x hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end /--A minimal polynomial is irreducible.-/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minpoly A x : hab_eq }, have hzero := aeval A x, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end domain end integral_domain section field variables [field A] section ring variables [ring B] [algebra A B] variables {x : B} variables (A x) /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/ lemma degree_le_of_ne_zero {p : polynomial A} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := calc degree (minpoly A x) ≤ degree (p * C (leading_coeff p)⁻¹) : min A x (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz /-- The minimal polynomial of an element x is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has x as a root, then this polynomial is equal to the minimal polynomial of x. -/ lemma unique {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : polynomial A, q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minpoly A x := begin have hx : is_integral A x := ⟨p, pmonic, hp⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero A x hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min A x pmonic hp) (pmin (minpoly A x) (monic hx) (aeval A x)) } end /-- If an element x is a root of a polynomial p, then the minimal polynomial of x divides p. -/ lemma dvd {p : polynomial A} (hp : polynomial.aeval x p = 0) : minpoly A x ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, dvd_zero] }, have hx : is_integral A x, { rw ← is_algebraic_iff_is_integral, exact ⟨p, hp0, hp⟩ }, rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero A x hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower (A K : Type*) {R : Type*} [comm_ring A] [field K] [comm_ring R] [algebra A K] [algebra A R] [algebra K R] [is_scalar_tower A K R] (x : R) : minpoly K x ∣ (minpoly A x).map (algebra_map A K) := by { refine minpoly.dvd K x _, rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } variables {A x} theorem unique' [nontrivial B] {p : polynomial A} (hx : is_integral A x) (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minpoly A x := let ⟨q, hq⟩ := dvd A x hp2 in eq_of_monic_of_associated hp3 (monic hx) $ mul_one (minpoly A x) ▸ hq.symm ▸ associated_mul_mul (associated.refl _) $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit A x /-- If `y` is the image of `x` in an extension, their minimal polynomials coincide. We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails since `is_integral R y` depends on y. -/ lemma eq_of_algebra_map_eq {K S T : Type*} [field K] [comm_ring S] [comm_ring T] [algebra K S] [algebra K T] [algebra S T] [is_scalar_tower K S T] (hST : function.injective (algebra_map S T)) {x : S} {y : T} (hx : is_integral K x) (h : y = algebra_map S T x) : minpoly K x = minpoly K y := minpoly.unique _ _ (minpoly.monic hx) (by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval, ring_hom.map_zero]) (λ q q_monic root_q, minpoly.min _ _ q_monic (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST (h ▸ root_q : polynomial.aeval (algebra_map S T x) q = 0))) section gcd_domain /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. -/ lemma gcd_domain_eq_field_fractions {A K R : Type*} [integral_domain A] [gcd_monoid A] [field K] [integral_domain R] (f : fraction_map A K) [algebra f.codomain R] [algebra A R] [is_scalar_tower A f.codomain R] {x : R} (hx : is_integral A x) : minpoly f.codomain x = (minpoly A x).map (localization_map.to_ring_hom f) := begin refine (unique' (@is_integral_of_is_scalar_tower A f.codomain R _ _ _ _ _ _ _ x hx) _ _ _).symm, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map f (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply A f.codomain R x (minpoly A x), simp only [localization_map.algebra_map_eq, aeval] at htower, exact htower.symm }, { exact monic_map _ (monic hx) } end /-- The minimal polynomial over `ℤ` is the same as the minimal polynomial over `ℚ`. -/ --TODO use `gcd_domain_eq_field_fractions` directly when localizations are defined -- in terms of algebras instead of `ring_hom`s lemma over_int_eq_over_rat {A : Type*} [integral_domain A] {x : A} [hℚA : algebra ℚ A] (hx : is_integral ℤ x) : minpoly ℚ x = map (int.cast_ring_hom ℚ) (minpoly ℤ x) := begin refine (unique' (@is_integral_of_is_scalar_tower ℤ ℚ A _ _ _ _ _ _ _ x hx) _ _ _).symm, { exact (is_primitive.int.irreducible_iff_irreducible_map_cast (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply ℤ ℚ A x (minpoly ℤ x), simp only [localization_map.algebra_map_eq, aeval] at htower, exact htower.symm }, { exact monic_map _ (monic hx) } end /-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. -/ lemma gcd_domain_dvd {A K R : Type*} [integral_domain A] [gcd_monoid A] [field K] [integral_domain R] (f : fraction_map A K) [algebra f.codomain R] [algebra A R] [is_scalar_tower A f.codomain R] {x : R} (hx : is_integral A x) {P : polynomial A} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) : minpoly A x ∣ P := begin apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map f (monic.is_primitive (monic hx)) hprim ).2, rw [← gcd_domain_eq_field_fractions f hx], refine dvd _ _ _, rwa [← localization_map.algebra_map_eq, ← is_scalar_tower.aeval_apply] end /-- The minimal polynomial over `ℤ` divides any primitive polynomial that has the integral element as root. -/ -- TODO use `gcd_domain_dvd` directly when localizations are defined in terms of algebras -- instead of `ring_hom`s lemma integer_dvd {A : Type*} [integral_domain A] [algebra ℚ A] {x : A} (hx : is_integral ℤ x) {P : polynomial ℤ} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) : minpoly ℤ x ∣ P := begin apply (is_primitive.int.dvd_iff_map_cast_dvd_map_cast _ _ (monic.is_primitive (monic hx)) hprim ).2, rw [← over_int_eq_over_rat hx], refine dvd _ _ _, rwa [(int.cast_ring_hom ℚ).ext_int (algebra_map ℤ ℚ), ← is_scalar_tower.aeval_apply] end end gcd_domain variables (B) [nontrivial B] /-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`, then the minimal polynomial of `algebra_map K B x` is `X - C x`. -/ lemma eq_X_sub_C (a : A) : minpoly A (algebra_map A B a) = X - C a := eq_X_sub_C_of_algebra_map_inj a (algebra_map A B).injective lemma eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a variables (A) /-- The minimal polynomial of `0` is `X`. -/ @[simp] lemma zero : minpoly A (0:B) = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using eq_X_sub_C B (0:A) /-- The minimal polynomial of `1` is `X - 1`. -/ @[simp] lemma one : minpoly A (1:B) = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1:A) end ring section domain variables [domain B] [algebra A B] variables {x : B} /-- A minimal polynomial is prime. -/ lemma prime (hx : is_integral A x) : prime (minpoly A x) := begin refine ⟨ne_zero hx, not_is_unit A x, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval A x], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd A x) (dvd A x) this end /-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/ lemma root {x : B} (hx : is_integral A x) {y : A} (h : is_root (minpoly A x) y) : algebra_map A B y = x := have key : minpoly A x = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd (dvd_symm_of_irreducible (irreducible_X_sub_C y) (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval A x, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /--The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/ @[simp] lemma coeff_zero_eq_zero (hx : is_integral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /--The minimal polynomial of a nonzero element has nonzero constant coefficient. -/ lemma coeff_zero_ne_zero (hx : is_integral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 := by { contrapose! h, simpa only [hx, coeff_zero_eq_zero] using h } end domain end field end minpoly
e85b093e5dda139a50abc9e424d74e3b104df423
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/decClassical.lean
ed2d59fd99b405bbf929646c700004994b09ab5d
[ "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
309
lean
open Classical theorem ex : if (fun x => x + 1) = (fun x => x + 2) then False else True := by have : (fun x => x + 1) ≠ (fun x => x + 2) := by intro h have : 1 = 2 := congrFun h 0 contradiction rw [ifNeg this] exact True.intro def tst (x : Nat) : Bool := if 1 < 2 then true else false