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
018abf270508e9c9d7eb29e4ce1878ffacea6ba3
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/data/repr.lean
1f402768c9bde132d3245aed4d043a2a46e19e8d
[ "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
4,425
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.string.basic init.data.bool.basic init.data.subtype.basic import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div open sum subtype nat universes u v /-- Implement `has_repr` if the output string is valid lean code that evaluates back to the original object. If you just want to view the object as a string for a trace message, use `has_to_string`. ### Example: ``` #eval to_string "hello world" -- [Lean] "hello world" #eval repr "hello world" -- [Lean] "\"hello world\"" ``` Reference: https://github.com/leanprover/lean/issues/1664 -/ class has_repr (α : Type u) := (repr : α → string) /-- `repr` is similar to `to_string` except that we should have the property `eval (repr x) = x` for most sensible datatypes. Hence, `repr "hello"` has the value `"\"hello\""` not `"hello"`. -/ def repr {α : Type u} [has_repr α] : α → string := has_repr.repr instance : has_repr bool := ⟨λ b, cond b "tt" "ff"⟩ instance {p : Prop} : has_repr (decidable p) := -- Remark: type class inference will not consider local instance `b` in the new elaborator ⟨λ b : decidable p, @ite p b _ "tt" "ff"⟩ protected def list.repr_aux {α : Type u} [has_repr α] : bool → list α → string | b [] := "" | tt (x::xs) := repr x ++ list.repr_aux ff xs | ff (x::xs) := ", " ++ repr x ++ list.repr_aux ff xs protected def list.repr {α : Type u} [has_repr α] : list α → string | [] := "[]" | (x::xs) := "[" ++ list.repr_aux tt (x::xs) ++ "]" instance {α : Type u} [has_repr α] : has_repr (list α) := ⟨list.repr⟩ instance : has_repr unit := ⟨λ u, "star"⟩ instance {α : Type u} [has_repr α] : has_repr (option α) := ⟨λ o, match o with | none := "none" | (some a) := "(some " ++ repr a ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_repr α] [has_repr β] : has_repr (α ⊕ β) := ⟨λ s, match s with | (inl a) := "(inl " ++ repr a ++ ")" | (inr b) := "(inr " ++ repr b ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_repr α] [has_repr β] : has_repr (α × β) := ⟨λ ⟨a, b⟩, "(" ++ repr a ++ ", " ++ repr b ++ ")"⟩ instance {α : Type u} {β : α → Type v} [has_repr α] [s : ∀ x, has_repr (β x)] : has_repr (sigma β) := ⟨λ ⟨a, b⟩, "⟨" ++ repr a ++ ", " ++ repr b ++ "⟩"⟩ instance {α : Type u} {p : α → Prop} [has_repr α] : has_repr (subtype p) := ⟨λ s, repr (val s)⟩ namespace nat def digit_char (n : ℕ) : char := if n = 0 then '0' else if n = 1 then '1' else if n = 2 then '2' else if n = 3 then '3' else if n = 4 then '4' else if n = 5 then '5' else if n = 6 then '6' else if n = 7 then '7' else if n = 8 then '8' else if n = 9 then '9' else if n = 0xa then 'a' else if n = 0xb then 'b' else if n = 0xc then 'c' else if n = 0xd then 'd' else if n = 0xe then 'e' else if n = 0xf then 'f' else '*' def digit_succ (base : ℕ) : list ℕ → list ℕ | [] := [1] | (d::ds) := if d+1 = base then 0 :: digit_succ ds else (d+1) :: ds def to_digits (base : ℕ) : ℕ → list ℕ | 0 := [0] | (n+1) := digit_succ base (to_digits n) protected def repr (n : ℕ) : string := ((to_digits 10 n).map digit_char).reverse.as_string end nat instance : has_repr nat := ⟨nat.repr⟩ def hex_digit_repr (n : nat) : string := string.singleton $ nat.digit_char n def char_to_hex (c : char) : string := let n := char.to_nat c, d2 := n / 16, d1 := n % 16 in hex_digit_repr d2 ++ hex_digit_repr d1 def char.quote_core (c : char) : string := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if c.to_nat <= 31 ∨ c = '\x7f' then "\\x" ++ char_to_hex c else string.singleton c instance : has_repr char := ⟨λ c, "'" ++ char.quote_core c ++ "'"⟩ def string.quote_aux : list char → string | [] := "" | (x::xs) := char.quote_core x ++ string.quote_aux xs def string.quote (s : string) : string := if s.is_empty = tt then "\"\"" else "\"" ++ string.quote_aux s.to_list ++ "\"" instance : has_repr string := ⟨string.quote⟩ instance (n : nat) : has_repr (fin n) := ⟨λ f, repr f.val⟩ instance : has_repr unsigned := ⟨λ n, repr n.val⟩ def char.repr (c : char) : string := repr c
a01e1da9999abc79726edbfd5e07fe822d58b78f
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/category_theory/functor.lean
3757ff229bf8624bb70e52dfbb870c1e4b82fb4d
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
3,494
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison Defines a functor between categories. (As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised by the underlying function on objects, the name is capitalised.) Introduces notations `C ⥤ D` for the type of all functors from `C` to `D`. (I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.) -/ import category_theory.category import tactic.tidy namespace category_theory universes u v u₁ v₁ u₂ v₂ u₃ v₃ /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`. The axiom `map_id_lemma` expresses preservation of identities, and `map_comp_lemma` expresses functoriality. -/ structure functor (C : Type u₁) [category.{u₁ v₁} C] (D : Type u₂) [category.{u₂ v₂} D] : Type (max u₁ v₁ u₂ v₂) := (obj : C → D) (map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) infixr ` ⥤ `:70 := functor -- type as \func -- restate_axiom functor.map_id' attribute [simp] functor.map_id restate_axiom functor.map_comp' attribute [simp] functor.map_comp namespace functor section variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] include 𝒞 /-- `functor.id C` is the identity functor on a category `C`. -/ protected def id : C ⥤ C := { obj := λ X, X, map := λ _ _ f, f } variable {C} @[simp] lemma id_obj (X : C) : (functor.id C).obj X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (functor.id C).map f = f := rfl end section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] {E : Type u₃} [ℰ : category.{u₃ v₃} E] include 𝒞 𝒟 ℰ /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G.obj (F.obj X), map := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) (X Y : C) (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl end section variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] include 𝒞 @[simp] def ulift_down : (ulift.{u₂} C) ⥤ C := { obj := λ X, X.down, map := λ X Y f, f } @[simp] def ulift_up : C ⥤ (ulift.{u₂} C) := { obj := λ X, ⟨ X ⟩, map := λ X Y f, f } end end functor def bundled.map {c : Type u → Type v} {d : Type u → Type v} (f : Π{a}, c a → d a) (s : bundled c) : bundled d := { α := s.α, str := f s.str } def concrete_functor {C : Type u → Type v} {hC : ∀{α β}, C α → C β → (α → β) → Prop} [concrete_category @hC] {D : Type u → Type v} {hD : ∀{α β}, D α → D β → (α → β) → Prop} [concrete_category @hD] (m : ∀{α}, C α → D α) (h : ∀{α β} {ia : C α} {ib : C β} {f}, hC ia ib f → hD (m ia) (m ib) f) : bundled C ⥤ bundled D := { obj := bundled.map @m, map := λ X Y f, ⟨ f, h f.2 ⟩} end category_theory
d58bfcd0aa9dbd286388d82063e22e4bb227e062
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/tactic/norm_cast.lean
a74a253439d8f29ea9ab39dd950a8ce8031bb476
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,216
lean
/- Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul-Nicolas Madelaine, Robert Y. Lewis Normalizing casts inside expressions. -/ import tactic.converter.interactive import tactic.hint /-! # A tactic for normalizing casts inside expressions This tactic normalizes casts inside expressions. It can be thought of as a call to the simplifier with a specific set of lemmas to move casts upwards in the expression. It has special handling of numerals and a simple heuristic to help moving casts "past" binary operators. Contrary to simp, it should be safe to use as a non-terminating tactic. The algorithm implemented here is described in the paper <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. ## Important definitions * `tactic.interactive.norm_cast` * `tactic.interactive.push_cast` * `tactic.interactive.exact_mod_cast` * `tactic.interactive.apply_mod_cast` * `tactic.interactive.rw_mod_cast` * `tactic.interactive.assumption_mod_cast` -/ setup_tactic_parser namespace tactic /-- Runs `mk_instance` with a time limit. This is a work around to the fact that in some cases mk_instance times out instead of failing, for example: `has_lift_t ℤ ℕ` `mk_instance_fast` is used when we assume the type class search should end instantly. -/ meta def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr := try_for timeout (mk_instance e) end tactic namespace norm_cast open tactic expr declare_trace norm_cast /-- Output a trace message if `trace.norm_cast` is enabled. -/ meta def trace_norm_cast {α} [has_to_tactic_format α] (msg : string) (a : α) : tactic unit := when_tracing `norm_cast $ do a ← pp a, trace ("[norm_cast] " ++ msg ++ a : format) mk_simp_attribute push_cast "The `push_cast` simp attribute uses `norm_cast` lemmas to move casts toward the leaf nodes of the expression." /-- `label` is a type used to classify `norm_cast` lemmas. * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes -/ @[derive [decidable_eq, has_reflect, inhabited]] inductive label | elim : label | move : label | squash : label namespace label /-- Convert `label` into `string`. -/ protected def to_string : label → string | elim := "elim" | move := "move" | squash := "squash" instance : has_to_string label := ⟨label.to_string⟩ instance : has_repr label := ⟨label.to_string⟩ meta instance : has_to_format label := ⟨λ l, l.to_string⟩ /-- Convert `string` into `label`. -/ def of_string : string -> option label | "elim" := some elim | "move" := some move | "squash" := some squash | _ := none end label open label /-- Count how many coercions are at the top of the expression. -/ meta def count_head_coes : expr → ℕ | `(coe %%e) := count_head_coes e + 1 | `(coe_sort %%e) := count_head_coes e + 1 | `(coe_fn %%e) := count_head_coes e + 1 | _ := 0 /-- Count how many coercions are inside the expression, including the top ones. -/ meta def count_coes : expr → tactic ℕ | `(coe %%e) := (+1) <$> count_coes e | `(coe_sort %%e) := (+1) <$> count_coes e | `(coe_fn %%e) := (+1) <$> count_coes e | (app `(coe_fn %%e) x) := (+) <$> count_coes x <*> (+1) <$> count_coes e | (expr.lam n bi t e) := do l ← mk_local' n bi t, count_coes $ e.instantiate_var l | e := do as ← e.get_simp_args, list.sum <$> as.mmap count_coes /-- Count how many coercions are inside the expression, excluding the top ones. -/ private meta def count_internal_coes (e : expr) : tactic ℕ := do ncoes ← count_coes e, pure $ ncoes - count_head_coes e /-- Classifies a declaration of type `ty` as a `norm_cast` rule. -/ meta def classify_type (ty : expr) : tactic label := do (_, ty) ← open_pis ty, (lhs, rhs) ← match ty with | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | _ := fail "norm_cast: lemma must be = or ↔" end, lhs_coes ← count_coes lhs, when (lhs_coes = 0) $ fail "norm_cast: badly shaped lemma, lhs must contain at least one coe", let lhs_head_coes := count_head_coes lhs, lhs_internal_coes ← count_internal_coes lhs, let rhs_head_coes := count_head_coes rhs, rhs_internal_coes ← count_internal_coes rhs, if lhs_head_coes = 0 then return elim else if lhs_head_coes = 1 then do when (rhs_head_coes ≠ 0) $ fail "norm_cast: badly shaped lemma, rhs can't start with coe", if rhs_internal_coes = 0 then return squash else return move else if rhs_head_coes < lhs_head_coes then do return squash else do fail "norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs" /-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/ meta structure norm_cast_cache := (up : simp_lemmas) (down : simp_lemmas) (squash : simp_lemmas) /-- Empty `norm_cast_cache`. -/ meta def empty_cache : norm_cast_cache := { up := simp_lemmas.mk, down := simp_lemmas.mk, squash := simp_lemmas.mk, } meta instance : inhabited norm_cast_cache := ⟨empty_cache⟩ /-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/ meta def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_up ← simp_lemmas.add cache.up e, return { up := new_up, down := cache.down, squash := cache.squash, } /-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/ meta def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do ty ← infer_type e, new_up ← cache.up.add e tt, new_down ← simp_lemmas.add cache.down e, return { up := new_up, down := new_down, squash := cache.squash, } /-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/ meta def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_squash ← simp_lemmas.add cache.squash e, new_down ← simp_lemmas.add cache.down e, return { up := cache.up, down := new_down, squash := new_squash, } /-- The type of the `norm_cast` attribute. The optional label is used to overwrite the classifier. -/ meta def norm_cast_attr_ty : Type := user_attribute norm_cast_cache (option label) /-- Efficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`. See Note [user attribute parameters]. -/ meta def get_label_param (attr : norm_cast_attr_ty) (decl : name) : tactic (option label) := do p ← attr.get_param_untyped decl, match p with | `(none) := pure none | `(some label.elim) := pure label.elim | `(some label.move) := pure label.move | `(some label.squash) := pure label.squash | _ := fail p end /-- `add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`. -/ meta def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : name) : tactic norm_cast_cache := do e ← mk_const decl, param ← get_label_param attr decl, l ← param <|> (infer_type e >>= classify_type), match l with | elim := add_elim cache e | move := add_move cache e | squash := add_squash cache e end -- special lemmas to handle the ≥, > and ≠ operators private lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl private lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl private lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl /-- `mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes for names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes. -/ meta def mk_cache (attr : thunk norm_cast_attr_ty) (names : list name) : tactic norm_cast_cache := do -- names has the declarations in reverse order cache ← names.mfoldr (λ name cache, add_lemma (attr ()) cache name) empty_cache, --some special lemmas to handle binary relations let up := cache.up, up ← up.add_simp ``ge_from_le, up ← up.add_simp ``gt_from_lt, up ← up.add_simp ``ne_from_not_eq, let down := cache.down, down ← down.add_simp ``coe_coe, pure { up := up, down := down, squash := cache.squash } /-- The `norm_cast` attribute. -/ @[user_attribute] meta def norm_cast_attr : user_attribute norm_cast_cache (option label) := { name := `norm_cast, descr := "attribute for norm_cast", parser := (do some l ← (label.of_string ∘ to_string) <$> ident, return l) <|> return none, after_set := some (λ decl prio persistent, do param ← get_label_param norm_cast_attr decl, match param with | some l := when (l ≠ elim) $ simp_attr.push_cast.set decl () tt | none := do e ← mk_const decl, ty ← infer_type e, l ← classify_type ty, norm_cast_attr.set decl l persistent prio end), before_unset := some $ λ _ _, tactic.skip, cache_cfg := { mk_cache := mk_cache norm_cast_attr, dependencies := [] } } /-- Classify a declaration as a `norm_cast` rule. -/ meta def make_guess (decl : name) : tactic label := do e ← mk_const decl, ty ← infer_type e, classify_type ty /-- Gets the `norm_cast` classification label for a declaration. Applies the override specified on the attribute, if necessary. -/ meta def get_label (decl : name) : tactic label := do param ← get_label_param norm_cast_attr decl, param <|> make_guess decl end norm_cast namespace tactic.interactive open norm_cast /-- `push_cast` rewrites the expression to move casts toward the leaf nodes. For example, `↑(a + b)` will be written to `↑a + ↑b`. Equivalent to `simp only with push_cast`. Can also be used at hypotheses. `push_cast` can also be used at hypotheses and with extra simp rules. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` -/ meta def push_cast (hs : parse tactic.simp_arg_list) (l : parse location) : tactic unit := tactic.interactive.simp none none tt hs [`push_cast] l end tactic.interactive namespace norm_cast open tactic expr /-- Prove `a = b` using the given simp set. -/ meta def prove_eq_using (s : simp_lemmas) (a b : expr) : tactic expr := do (a', a_a', _) ← simplify s [] a {fail_if_unchanged := ff}, (b', b_b', _) ← simplify s [] b {fail_if_unchanged := ff}, on_exception (trace_norm_cast "failed: " (to_expr ``(%%a' = %%b') >>= pp)) $ is_def_eq a' b' reducible, b'_b ← mk_eq_symm b_b', mk_eq_trans a_a' b'_b /-- Prove `a = b` by simplifying using move and squash lemmas. -/ meta def prove_eq_using_down (a b : expr) : tactic expr := do cache ← norm_cast_attr.get_cache, trace_norm_cast "proving: " (to_expr ``(%%a = %%b) >>= pp), prove_eq_using cache.down a b /-- This is the main heuristic used alongside the elim and move lemmas. The goal is to help casts move past operators by adding intermediate casts. An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ) is rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ) when (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma -/ meta def splitting_procedure : expr → tactic (expr × expr) | (app (app op x) y) := (do `(@coe %%α %%δ %%coe1 %%xx) ← return x, `(@coe %%β %%γ %%coe2 %%yy) ← return y, success_if_fail $ is_def_eq α β, is_def_eq δ γ, (do coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast, new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)), let new_e := app (app op new_x) y, eq_x ← prove_eq_using_down x new_x, pr ← mk_congr_arg op eq_x, pr ← mk_congr_fun pr y, return (new_e, pr) ) <|> (do coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)), let new_e := app (app op x) new_y, eq_y ← prove_eq_using_down y new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_one.one %%β %%h1) ← return y, h2 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_zero.zero %%β %%h1) ← return y, h2 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@has_one.one %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) <|> (do `(@has_zero.zero %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) | _ := failed /-- Discharging function used during simplification in the "squash" step. TODO: norm_cast takes a list of expressions to use as lemmas for the discharger TODO: a tactic to print the results the discharger fails to proove -/ private meta def prove : tactic unit := assumption /-- Core rewriting function used in the "squash" step, which moves casts upwards and eliminates them. It tries to rewrite an expression using the elim and move lemmas. On failure, it calls the splitting procedure heuristic. -/ meta def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) := (do r ← mcond (is_prop e) (return `iff) (return `eq), (new_e, pr) ← s.rewrite e prove r, pr ← match r with | `iff := mk_app `propext [pr] | _ := return pr end, return (new_e, pr) ) <|> splitting_procedure e /-! The following auxiliary functions are used to handle numerals. -/ /-- If possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`. Returns a pair of the new expression and proof that they are equal. -/ meta def numeral_to_coe (e : expr) : tactic (expr × expr) := do α ← infer_type e, success_if_fail $ is_def_eq α `(ℕ), n ← e.to_nat, h1 ← mk_app `has_lift_t [`(ℕ), α] >>= mk_instance_fast, let new_e : expr := reflect n, new_e ← to_expr ``(@coe ℕ %%α %%h1 %%new_e), pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- If possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral. Returns a pair of the new expression and proof that they are equal. -/ meta def coe_to_numeral (e : expr) : tactic (expr × expr) := do `(@coe ℕ %%α %%h1 %%e') ← return e, n ← e'.to_nat, -- replace e' by normalized numeral is_def_eq (reflect n) e' reducible, let e := e.app_fn (reflect n), new_e ← expr.of_nat α n, pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- A local variant on `simplify_top_down`. -/ private meta def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e /-- The core simplification routine of `norm_cast`. -/ meta def derive (e : expr) : tactic (expr × expr) := do cache ← norm_cast_attr.get_cache, e ← instantiate_mvars e, let cfg : simp_config := { zeta := ff, beta := ff, eta := ff, proj := ff, iota := ff, iota_eqn := ff, fail_if_unchanged := ff }, let e0 := e, -- step 1: pre-processing of numerals ((), e1, pr1) ← simplify_top_down' () (λ _ e, prod.mk () <$> numeral_to_coe e) e0 cfg, trace_norm_cast "after numeral_to_coe: " e1, -- step 2: casts are moved upwards and eliminated ((), e2, pr2) ← simplify_bottom_up () (λ _ e, prod.mk () <$> upward_and_elim cache.up e) e1 cfg, trace_norm_cast "after upward_and_elim: " e2, -- step 3: casts are squashed (e3, pr3, _) ← simplify cache.squash [] e2 cfg, trace_norm_cast "after squashing: " e3, -- step 4: post-processing of numerals ((), e4, pr4) ← simplify_top_down' () (λ _ e, prod.mk () <$> coe_to_numeral e) e3 cfg, trace_norm_cast "after coe_to_numeral: " e4, let new_e := e4, guard (¬ new_e =ₐ e), pr ← mk_eq_trans pr1 pr2, pr ← mk_eq_trans pr pr3, pr ← mk_eq_trans pr pr4, return (new_e, pr) /-- A small variant of `push_cast` suited for non-interactive use. `derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`. -/ meta def derive_push_cast (extra_lems : list simp_arg_type) (e : expr) : tactic (expr × expr) := do (s, _) ← mk_simp_set tt [`push_cast] extra_lems, (e, prf, _) ← simplify (s.erase [`int.coe_nat_succ]) [] e {fail_if_unchanged := ff}, return (e, prf) end norm_cast namespace tactic open expr norm_cast /-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it also normalizes the goal. -/ meta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr := match e with | local_const _ lc _ _ := do e ← get_local lc, replace_at derive [e] include_goal, get_local lc | e := do t ← infer_type e, e ← assertv `this t e, replace_at derive [e] include_goal, get_local `this end /-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/ meta def exact_mod_cast (e : expr) : tactic unit := decorate_error "exact_mod_cast failed:" $ do new_e ← aux_mod_cast e, exact new_e /-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/ meta def apply_mod_cast (e : expr) : tactic (list (name × expr)) := decorate_error "apply_mod_cast failed:" $ do new_e ← aux_mod_cast e, apply new_e /-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also normalizes `h` and tries to use that to close the goal. -/ meta def assumption_mod_cast : tactic unit := decorate_error "assumption_mod_cast failed:" $ do let cfg : simp_config := { fail_if_unchanged := ff, canonize_instances := ff, canonize_proofs := ff, proj := ff }, replace_at derive [] tt, ctx ← local_context, try_lst $ ctx.map (λ h, aux_mod_cast h ff >>= tactic.exact) end tactic namespace tactic.interactive open tactic norm_cast /-- Normalize casts at the given locations by moving them "upwards". As opposed to simp, norm_cast can be used without necessarily closing the goal. -/ meta def norm_cast (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← replace_at derive ns loc.include_goal | fail "norm_cast failed to simplify", when loc.include_goal $ try tactic.reflexivity, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Rewrite with the given rules and normalize casts between steps. -/ meta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit := decorate_error "rw_mod_cast failed:" $ do let cfg_norm : simp_config := {}, let cfg_rw : rewrite_cfg := {}, ns ← loc.get_locals, monad.mapm' (λ r : rw_rule, do save_info r.pos, replace_at derive ns loc.include_goal, rw ⟨[r], none⟩ loc {} ) rs.rules, replace_at derive ns loc.include_goal, skip /-- Normalize the goal and the given expression, then close the goal with exact. -/ meta def exact_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr e <|> do { ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), pty ← pp ty, ptgt ← pp e, fail ("exact_mod_cast failed, expression type not directly " ++ "inferrable. Try:\n\nexact_mod_cast ...\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, tactic.exact_mod_cast e /-- Normalize the goal and the given expression, then apply the expression to the goal. -/ meta def apply_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr_for_apply e, concat_tags $ tactic.apply_mod_cast e /-- Normalize the goal and every expression in the local context, then close the goal with assumption. -/ meta def assumption_mod_cast : tactic unit := tactic.assumption_mod_cast end tactic.interactive namespace conv.interactive open conv open norm_cast (derive) /-- the converter version of `norm_cast' -/ meta def norm_cast : conv unit := replace_lhs derive end conv.interactive -- TODO: move this elsewhere? @[norm_cast] lemma ite_cast {α β} [has_lift_t α β] {c : Prop} [decidable c] {a b : α} : ↑(ite c a b) = ite c (↑a : β) (↑b : β) := by by_cases h : c; simp [h] add_hint_tactic "norm_cast at *" /-- The `norm_cast` family of tactics is used to normalize casts inside expressions. It is basically a simp tactic with a specific set of lemmas to move casts upwards in the expression. Therefore it can be used more safely as a non-terminating tactic. It also has special handling of numerals. For instance, given an assumption ```lean a b : ℤ h : ↑a + ↑b < (10 : ℚ) ``` writing `norm_cast at h` will turn `h` into ```lean h : a + b < 10 ``` You can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast` or `assumption_mod_cast`. Writing `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and `h` before using `exact h` or `apply h`. Writing `assumption_mod_cast` will normalize the goal and for every expression `h` in the context it will try to normalize `h` and use `exact h`. `rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps. `push_cast` rewrites the expression to move casts toward the leaf nodes. This uses `norm_cast` lemmas in the forward direction. For example, `↑(a + b)` will be written to `↑a + ↑b`. It is equivalent to `simp only with push_cast`. It can also be used at hypotheses with `push_cast at h` and with extra simp lemmas with `push_cast [int.add_zero]`. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` The implementation and behavior of the `norm_cast` family is described in detail at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast", category := doc_category.tactic, decl_names := [``tactic.interactive.norm_cast, ``tactic.interactive.rw_mod_cast, ``tactic.interactive.apply_mod_cast, ``tactic.interactive.assumption_mod_cast, ``tactic.interactive.exact_mod_cast, ``tactic.interactive.push_cast], tags := ["coercions", "simplification"] } /-- The `norm_cast` attribute should be given to lemmas that describe the behaviour of a coercion in regard to an operator, a relation, or a particular function. It only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of the coercion functions. It does not apply to the explicit functions that define the coercions. Examples: ```lean @[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n @[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 @[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n @[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n @[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m @[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n @[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n @[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 ``` Lemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and `squash`. They are classified roughly as follows: * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes `norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression and to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean up the result. Occasionally you may want to override the automatic classification. You can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute. ```lean @[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] ``` Don't do this unless you understand what you are doing. A full description of the tactic, and the use of each lemma category, can be found at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast attributes", category := doc_category.attr, decl_names := [``norm_cast.norm_cast_attr], tags := ["coercions", "simplification"] } -- Lemmas defined in core. attribute [norm_cast] int.nat_abs_of_nat int.coe_nat_sub int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_add -- Lemmas about nat.succ need to get a low priority, so that they are tried last. -- This is because `nat.succ _` matches `1`, `3`, `x+1`, etc. -- Rewriting would then produce really wrong terms. attribute [norm_cast, priority 500] int.coe_nat_succ
fc0e1ce2621983c1ee8b45c200c51c9e0e319316
8f209eb34c0c4b9b6be5e518ebfc767a38bed79c
/code/src/internal/counterexample.lean
169582dbb6b46293210bf732d8af2366b21b0c3e
[]
no_license
hediet/masters-thesis
13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5
dc40c14cc4ed073673615412f36b4e386ee7aac9
refs/heads/master
1,680,591,056,302
1,617,710,887,000
1,617,710,887,000
311,762,038
4
0
null
null
null
null
UTF-8
Lean
false
false
589
lean
import tactic import data.finset import ..definitions import .internal_definitions import .Ant.rhss import .utils instance exmpl : GuardModule := { Rhs := ℕ, TGrd := ℕ, Env := ℕ, tgrd_eval := λ grd env, some env, Var := ℕ, is_bottom := λ var env, false } def ant_a := Ant.diverge ff ((Ant.rhs tt 1).branch (Ant.rhs ff 2)) def ant_b := Ant.diverge ff ((Ant.rhs tt 1).branch (Ant.rhs tt 2)) example : ant_a ⟶ ant_b ∧ (R ant_a).red = [1] ∧ (R ant_b).red = [2] := by finish [ant_a, ant_b, R, Ant.implies.rhs, Ant.implies.branch, Ant.implies.diverge]
a0cce9d64888bfd8f99cb6c39d33f2f5e94bb69a
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/rat/order.lean
95c3cf84861e21f16ccacfd14e1d309cf9ac691c
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
16,099
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Adds the ordering, and instantiates the rationals as an ordered field. -/ import data.int algebra.ordered_field algebra.group_power data.rat.basic open quot eq.ops /- the ordering on representations -/ namespace prerat section int_notation open int variables {a b : prerat} definition pos (a : prerat) : Prop := num a > 0 definition nonneg (a : prerat) : Prop := num a ≥ 0 theorem pos_of_int (a : ℤ) : pos (of_int a) ↔ (a > 0) := !iff.rfl theorem nonneg_of_int (a : ℤ) : nonneg (of_int a) ↔ (a ≥ 0) := !iff.rfl theorem pos_eq_pos_of_equiv {a b : prerat} (H1 : a ≡ b) : pos a = pos b := propext (iff.intro (num_pos_of_equiv H1) (num_pos_of_equiv H1⁻¹)) theorem nonneg_eq_nonneg_of_equiv (H : a ≡ b) : nonneg a = nonneg b := have H1 : (0 = num a) = (0 = num b), from propext (iff.intro (assume H2, eq.symm (num_eq_zero_of_equiv H H2⁻¹)) (assume H2, eq.symm (num_eq_zero_of_equiv H⁻¹ H2⁻¹))), calc nonneg a = (pos a ∨ 0 = num a) : propext !le_iff_lt_or_eq ... = (pos b ∨ 0 = num a) : pos_eq_pos_of_equiv H ... = (pos b ∨ 0 = num b) : H1 ... = nonneg b : propext !le_iff_lt_or_eq theorem nonneg_zero : nonneg zero := le.refl 0 theorem nonneg_add (H1 : nonneg a) (H2 : nonneg b) : nonneg (add a b) := show num a * denom b + num b * denom a ≥ 0, from add_nonneg (mul_nonneg H1 (le_of_lt (denom_pos b))) (mul_nonneg H2 (le_of_lt (denom_pos a))) theorem nonneg_antisymm (H1 : nonneg a) (H2 : nonneg (neg a)) : a ≡ zero := have H3 : num a = 0, from le.antisymm (nonpos_of_neg_nonneg H2) H1, equiv_zero_of_num_eq_zero H3 theorem nonneg_total (a : prerat) : nonneg a ∨ nonneg (neg a) := or.elim (le.total 0 (num a)) (suppose 0 ≤ num a, or.inl this) (suppose 0 ≥ num a, or.inr (neg_nonneg_of_nonpos this)) theorem nonneg_of_pos (H : pos a) : nonneg a := le_of_lt H theorem ne_zero_of_pos (H : pos a) : ¬ a ≡ zero := assume H', ne_of_gt H (num_eq_zero_of_equiv_zero H') theorem pos_of_nonneg_of_ne_zero (H1 : nonneg a) (H2 : ¬ a ≡ zero) : pos a := have num a ≠ 0, from suppose num a = 0, H2 (equiv_zero_of_num_eq_zero this), lt_of_le_of_ne H1 (ne.symm this) theorem nonneg_mul (H1 : nonneg a) (H2 : nonneg b) : nonneg (mul a b) := mul_nonneg H1 H2 theorem pos_mul (H1 : pos a) (H2 : pos b) : pos (mul a b) := mul_pos H1 H2 end int_notation end prerat local attribute prerat.setoid [instance] /- The ordering on the rationals. The definitions of pos and nonneg are kept private, because they are only meant for internal use. Users should use a > 0 and a ≥ 0 instead of pos and nonneg. -/ namespace rat open nat int variables {a b c : ℚ} /- transfer properties of pos and nonneg -/ private definition pos (a : ℚ) : Prop := quot.lift prerat.pos @prerat.pos_eq_pos_of_equiv a private definition nonneg (a : ℚ) : Prop := quot.lift prerat.nonneg @prerat.nonneg_eq_nonneg_of_equiv a private theorem pos_of_int (a : ℤ) : (a > 0) ↔ pos (of_int a) := prerat.pos_of_int a private theorem nonneg_of_int (a : ℤ) : (a ≥ 0) ↔ nonneg (of_int a) := prerat.nonneg_of_int a private theorem nonneg_zero : nonneg 0 := prerat.nonneg_zero private theorem nonneg_add : nonneg a → nonneg b → nonneg (a + b) := quot.induction_on₂ a b @prerat.nonneg_add private theorem nonneg_antisymm : nonneg a → nonneg (-a) → a = 0 := quot.induction_on a (take u, assume H1 H2, quot.sound (prerat.nonneg_antisymm H1 H2)) private theorem nonneg_total (a : ℚ) : nonneg a ∨ nonneg (-a) := quot.induction_on a @prerat.nonneg_total private theorem nonneg_of_pos : pos a → nonneg a := quot.induction_on a @prerat.nonneg_of_pos private theorem ne_zero_of_pos : pos a → a ≠ 0 := quot.induction_on a (take u, assume H1 H2, prerat.ne_zero_of_pos H1 (quot.exact H2)) private theorem pos_of_nonneg_of_ne_zero : nonneg a → ¬ a = 0 → pos a := quot.induction_on a (take u, assume h : nonneg ⟦u⟧, suppose ⟦u⟧ ≠ (rat.of_num 0), have ¬ (prerat.equiv u prerat.zero), from assume H, this (quot.sound H), prerat.pos_of_nonneg_of_ne_zero h this) private theorem nonneg_mul : nonneg a → nonneg b → nonneg (a * b) := quot.induction_on₂ a b @prerat.nonneg_mul private theorem pos_mul : pos a → pos b → pos (a * b) := quot.induction_on₂ a b @prerat.pos_mul private definition decidable_pos (a : ℚ) : decidable (pos a) := quot.rec_on_subsingleton a (take u, int.decidable_lt 0 (prerat.num u)) /- define order in terms of pos and nonneg -/ protected definition lt (a b : ℚ) : Prop := pos (b - a) protected definition le (a b : ℚ) : Prop := nonneg (b - a) definition rat_has_lt [reducible] [instance] [priority rat.prio] : has_lt rat := has_lt.mk rat.lt definition rat_has_le [reducible] [instance] [priority rat.prio] : has_le rat := has_le.mk rat.le protected lemma lt_def (a b : ℚ) : (a < b) = pos (b - a) := rfl protected lemma le_def (a b : ℚ) : (a ≤ b) = nonneg (b - a) := rfl theorem of_int_lt_of_int_iff (a b : ℤ) : of_int a < of_int b ↔ a < b := iff.symm (calc a < b ↔ b - a > 0 : iff.symm !sub_pos_iff_lt ... ↔ pos (of_int (b - a)) : iff.symm !pos_of_int ... ↔ pos (of_int b - of_int a) : !of_int_sub ▸ iff.rfl ... ↔ of_int a < of_int b : iff.rfl) theorem of_int_lt_of_int_of_lt {a b : ℤ} (H : a < b) : of_int a < of_int b := iff.mpr !of_int_lt_of_int_iff H theorem lt_of_of_int_lt_of_int {a b : ℤ} (H : of_int a < of_int b) : a < b := iff.mp !of_int_lt_of_int_iff H theorem of_int_le_of_int_iff (a b : ℤ) : of_int a ≤ of_int b ↔ (a ≤ b) := iff.symm (calc a ≤ b ↔ b - a ≥ 0 : iff.symm !sub_nonneg_iff_le ... ↔ nonneg (of_int (b - a)) : iff.symm !nonneg_of_int ... ↔ nonneg (of_int b - of_int a) : !of_int_sub ▸ iff.rfl ... ↔ of_int a ≤ of_int b : iff.rfl) theorem of_int_le_of_int_of_le {a b : ℤ} (H : a ≤ b) : of_int a ≤ of_int b := iff.mpr !of_int_le_of_int_iff H theorem le_of_of_int_le_of_int {a b : ℤ} (H : of_int a ≤ of_int b) : a ≤ b := iff.mp !of_int_le_of_int_iff H theorem of_nat_lt_of_nat_iff (a b : ℕ) : of_nat a < of_nat b ↔ a < b := by rewrite [*of_nat_eq, of_int_lt_of_int_iff, int.of_nat_lt_of_nat_iff] theorem of_nat_lt_of_nat_of_lt {a b : ℕ} (H : a < b) : of_nat a < of_nat b := iff.mpr !of_nat_lt_of_nat_iff H theorem lt_of_of_nat_lt_of_nat {a b : ℕ} (H : of_nat a < of_nat b) : a < b := iff.mp !of_nat_lt_of_nat_iff H theorem of_nat_le_of_nat_iff (a b : ℕ) : of_nat a ≤ of_nat b ↔ a ≤ b := by rewrite [*of_nat_eq, of_int_le_of_int_iff, int.of_nat_le_of_nat_iff] theorem of_nat_le_of_nat_of_le {a b : ℕ} (H : a ≤ b) : of_nat a ≤ of_nat b := iff.mpr !of_nat_le_of_nat_iff H theorem le_of_of_nat_le_of_nat {a b : ℕ} (H : of_nat a ≤ of_nat b) : a ≤ b := iff.mp !of_nat_le_of_nat_iff H theorem of_nat_nonneg (a : ℕ) : (of_nat a ≥ 0) := of_nat_le_of_nat_of_le !nat.zero_le protected theorem le_refl (a : ℚ) : a ≤ a := by rewrite [rat.le_def, sub_self]; apply nonneg_zero protected theorem le_trans (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := assert H3 : nonneg (c - b + (b - a)), from nonneg_add H2 H1, begin revert H3, rewrite [rat.sub.def, add.assoc, sub_eq_add_neg, neg_add_cancel_left], intro H3, apply H3 end protected theorem le_antisymm (H1 : a ≤ b) (H2 : b ≤ a) : a = b := have H3 : nonneg (-(a - b)), from !neg_sub⁻¹ ▸ H1, have H4 : a - b = 0, from nonneg_antisymm H2 H3, eq_of_sub_eq_zero H4 protected theorem le_total (a b : ℚ) : a ≤ b ∨ b ≤ a := or.elim (nonneg_total (b - a)) (assume H, or.inl H) (assume H, or.inr begin rewrite neg_sub at H, exact H end) protected theorem le_by_cases {P : Prop} (a b : ℚ) (H : a ≤ b → P) (H2 : b ≤ a → P) : P := or.elim (!rat.le_total) H H2 protected theorem lt_iff_le_and_ne (a b : ℚ) : a < b ↔ a ≤ b ∧ a ≠ b := iff.intro (assume H : a < b, have b - a ≠ 0, from ne_zero_of_pos H, have a ≠ b, from ne.symm (assume H', this (H' ▸ !sub_self)), and.intro (nonneg_of_pos H) this) (assume H : a ≤ b ∧ a ≠ b, obtain aleb aneb, from H, have b - a ≠ 0, from (assume H', aneb (eq_of_sub_eq_zero H')⁻¹), pos_of_nonneg_of_ne_zero aleb this) protected theorem le_iff_lt_or_eq (a b : ℚ) : a ≤ b ↔ a < b ∨ a = b := iff.intro (assume h : a ≤ b, decidable.by_cases (suppose a = b, or.inr this) (suppose a ≠ b, or.inl (iff.mpr !rat.lt_iff_le_and_ne (and.intro h this)))) (suppose a < b ∨ a = b, or.elim this (suppose a < b, and.left (iff.mp !rat.lt_iff_le_and_ne this)) (suppose a = b, this ▸ !rat.le_refl)) private theorem to_nonneg : a ≥ 0 → nonneg a := by intros; rewrite -sub_zero; eassumption protected theorem add_le_add_left (H : a ≤ b) (c : ℚ) : c + a ≤ c + b := have c + b - (c + a) = b - a, by rewrite [sub.def, neg_add, -add.assoc, add.comm c, add_neg_cancel_right], show nonneg (c + b - (c + a)), from this⁻¹ ▸ H protected theorem mul_nonneg (H1 : a ≥ (0 : ℚ)) (H2 : b ≥ (0 : ℚ)) : a * b ≥ (0 : ℚ) := assert nonneg (a * b), from nonneg_mul (to_nonneg H1) (to_nonneg H2), begin rewrite -sub_zero at this, exact this end private theorem to_pos : a > 0 → pos a := by intros; rewrite -sub_zero; eassumption protected theorem mul_pos (H1 : a > (0 : ℚ)) (H2 : b > (0 : ℚ)) : a * b > (0 : ℚ) := assert pos (a * b), from pos_mul (to_pos H1) (to_pos H2), begin rewrite -sub_zero at this, exact this end definition decidable_lt [instance] : decidable_rel rat.lt := take a b, decidable_pos (b - a) protected theorem le_of_lt (H : a < b) : a ≤ b := iff.mpr !rat.le_iff_lt_or_eq (or.inl H) protected theorem lt_irrefl (a : ℚ) : ¬ a < a := take Ha, let Hand := (iff.mp !rat.lt_iff_le_and_ne) Ha in (and.right Hand) rfl protected theorem not_le_of_gt (H : a < b) : ¬ b ≤ a := assume Hba, let Heq := rat.le_antisymm (rat.le_of_lt H) Hba in !rat.lt_irrefl (Heq ▸ H) protected theorem lt_of_lt_of_le (Hab : a < b) (Hbc : b ≤ c) : a < c := let Hab' := rat.le_of_lt Hab in let Hac := rat.le_trans Hab' Hbc in (iff.mpr !rat.lt_iff_le_and_ne) (and.intro Hac (assume Heq, rat.not_le_of_gt (Heq ▸ Hab) Hbc)) protected theorem lt_of_le_of_lt (Hab : a ≤ b) (Hbc : b < c) : a < c := let Hbc' := rat.le_of_lt Hbc in let Hac := rat.le_trans Hab Hbc' in (iff.mpr !rat.lt_iff_le_and_ne) (and.intro Hac (assume Heq, rat.not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab)) protected theorem zero_lt_one : (0 : ℚ) < 1 := trivial protected theorem add_lt_add_left (H : a < b) (c : ℚ) : c + a < c + b := let H' := rat.le_of_lt H in (iff.mpr (rat.lt_iff_le_and_ne _ _)) (and.intro (rat.add_le_add_left H' _) (take Heq, let Heq' := add_left_cancel Heq in !rat.lt_irrefl (Heq' ▸ H))) protected definition discrete_linear_ordered_field [reducible] [trans_instance] : discrete_linear_ordered_field rat := ⦃discrete_linear_ordered_field, rat.discrete_field, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := @rat.le_total, le_of_lt := @rat.le_of_lt, lt_irrefl := rat.lt_irrefl, lt_of_lt_of_le := @rat.lt_of_lt_of_le, lt_of_le_of_lt := @rat.lt_of_le_of_lt, le_iff_lt_or_eq := @rat.le_iff_lt_or_eq, add_le_add_left := @rat.add_le_add_left, mul_nonneg := @rat.mul_nonneg, mul_pos := @rat.mul_pos, decidable_lt := @decidable_lt, zero_lt_one := rat.zero_lt_one, add_lt_add_left := @rat.add_lt_add_left⦄ theorem of_nat_abs (a : ℤ) : abs (of_int a) = of_nat (int.nat_abs a) := assert ∀ n : ℕ, of_int (int.neg_succ_of_nat n) = - of_nat (nat.succ n), from λ n, rfl, int.induction_on a (take b, abs_of_nonneg !of_nat_nonneg) (take b, by rewrite [this, abs_neg, abs_of_nonneg !of_nat_nonneg]) 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 H' : ∀ ε, ε > 0 → x < ε, from take ε, suppose h₁ : ε > 0, have ε / 2 > 0, from div_pos_of_pos_of_pos h₁ two_pos, have x ≤ ε / 2, from H _ this, show x < ε, from lt_of_le_of_lt this (div_two_lt_of_pos h₁), eq_zero_of_nonneg_of_forall_lt xnonneg H' theorem eq_zero_of_forall_abs_le {x : ℚ} (H : ∀ ε, ε > 0 → abs x ≤ ε) : x = 0 := decidable.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 section open int theorem num_nonneg_of_nonneg {q : ℚ} (H : q ≥ 0) : num q ≥ 0 := have of_int (num q) ≥ of_int 0, begin rewrite [-mul_denom], apply rat.mul_nonneg H, rewrite [-of_int_zero, of_int_le_of_int_iff], exact int.le_of_lt !denom_pos end, show num q ≥ 0, from le_of_of_int_le_of_int this theorem num_pos_of_pos {q : ℚ} (H : q > 0) : num q > 0 := have of_int (num q) > of_int 0, begin rewrite [-mul_denom], apply rat.mul_pos H, rewrite [-of_int_zero, of_int_lt_of_int_iff], exact !denom_pos end, show num q > 0, from lt_of_of_int_lt_of_int this theorem num_neg_of_neg {q : ℚ} (H : q < 0) : num q < 0 := have of_int (num q) < of_int 0, begin rewrite [-mul_denom], apply mul_neg_of_neg_of_pos H, change of_int (denom q) > of_int 0, xrewrite [of_int_lt_of_int_iff], exact !denom_pos end, show num q < 0, from lt_of_of_int_lt_of_int this theorem num_nonpos_of_nonpos {q : ℚ} (H : q ≤ 0) : num q ≤ 0 := have of_int (num q) ≤ of_int 0, begin rewrite [-mul_denom], apply mul_nonpos_of_nonpos_of_nonneg H, change of_int (denom q) ≥ of_int 0, xrewrite [of_int_le_of_int_iff], exact int.le_of_lt !denom_pos end, show num q ≤ 0, from le_of_of_int_le_of_int this end definition ubound : ℚ → ℕ := λ a : ℚ, nat.succ (int.nat_abs (num a)) theorem ubound_ge (a : ℚ) : of_nat (ubound a) ≥ a := have h : abs a * abs (of_int (denom a)) = abs (of_int (num a)), from !abs_mul ▸ !mul_denom ▸ rfl, assert of_int (denom a) > 0, from of_int_lt_of_int_of_lt !denom_pos, have 1 ≤ abs (of_int (denom a)), begin rewrite (abs_of_pos this), apply of_int_le_of_int_of_le, apply denom_pos end, have abs a ≤ abs (of_int (num a)), from le_of_mul_le_of_ge_one (h ▸ !le.refl) !abs_nonneg this, calc a ≤ abs a : le_abs_self ... ≤ abs (of_int (num a)) : this ... ≤ abs (of_int (num a)) + 1 : le_add_of_nonneg_right trivial ... = of_nat (int.nat_abs (num a)) + 1 : of_nat_abs ... = of_nat (nat.succ (int.nat_abs (num a))) : of_nat_add theorem ubound_pos (a : ℚ) : ubound a > 0 := !nat.succ_pos open nat theorem binary_nat_bound (a : ℕ) : of_nat a ≤ 2^a := nat.induction_on a (zero_le_one) (take n : nat, assume Hn, calc of_nat (nat.succ n) = (of_nat n) + 1 : of_nat_add ... ≤ 2^n + 1 : add_le_add_right Hn ... ≤ 2^n + (2:rat)^n : add_le_add_left (pow_ge_one_of_ge_one two_ge_one _) ... = 2^(succ n) : pow_two_add) theorem binary_bound (a : ℚ) : ∃ n : ℕ, a ≤ 2^n := exists.intro (ubound a) (calc a ≤ of_nat (ubound a) : ubound_ge ... ≤ 2^(ubound a) : binary_nat_bound) end rat
c6b4b95899c6bae968231f122436c0f6d5f2a1d8
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/int/gcd.lean
043c7b7359b3ef39b6f771de22fb85cf8cf4f3dd
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
4,767
lean
/- Copyright (c) 2018 Guy Leroy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl Greatest common divisor (gcd) and least common multiple (lcm) for integers. This sets up ℤ to be a GCD domain, and introduces rules about `int.gcd`, as well as `int.lcm`. NOTE: If you add rules to this theory, check that the corresponding rules are available for `gcd_domain`. -/ import data.int.basic data.nat.prime /- Extended Euclidean algorithm -/ namespace nat def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0 s t r' s' t' := (r', s', t') | r@(succ _) s t r' s' t' := have r' % r < r, from mod_lt _ $ succ_pos _, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by simp [xgcd_aux] @[simp] theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [h, IH]; rw ← gcd_rec) theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) := by unfold gcd_a gcd_b; cases xgcd x y; refl section parameters (a b : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) := (r : ℤ) = a * s + b * t theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') → P (xgcd_aux r s t r' s' t') := gcd.induction r r' (by simp) $ λ x y h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *, rw [int.mod_def], generalize : (y / x : ℤ) = k, rw [p, p'], simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add] end theorem gcd_eq_gcd_ab : (gcd a b : ℤ) = a * gcd_a a b + b * gcd_b a b := by have := @xgcd_aux_P a b a b 1 0 0 1 (by simp [P]) (by simp [P]); rwa [xgcd_aux_val, xgcd_val] at this end end nat namespace int theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) := begin cases (nat.eq_zero_or_pos (nat_abs b)), {rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]}, calc nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one ... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h ... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ (dvd_refl _)) ... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b) ... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H, end theorem nat_abs_dvd_abs_iff {i j : ℤ} : i.nat_abs ∣ j.nat_abs ↔ i ∣ j := ⟨assume (H : i.nat_abs ∣ j.nat_abs), dvd_nat_abs.mp (nat_abs_dvd.mp (coe_nat_dvd.mpr H)), assume H : (i ∣ j), coe_nat_dvd.mp (dvd_nat_abs.mpr (nat_abs_dvd.mpr H))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n := have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm, have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn, have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs, by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn), let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in hsd.elim (λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end) (λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end) theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left k_non_zero H1⟩) theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j := by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H end int
1440999590c10d396b9cc4146c79a6f746073b1b
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/setoid/basic.lean
08d8613282bd080caa398358f5f1362816cfb946
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,385
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import order.galois_connection /-! # Equivalence relations This file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. ## Implementation notes The function `rel` and lemmas ending in ' make it easier to talk about different equivalence relations on the same type. The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `complete_lattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `filter.complete_lattice` in `order/filter/basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation -/ variables {α : Type*} {β : Type*} /-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/ def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r /-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/ lemma quotient.eq_rel {r : setoid α} {x y} : (quotient.mk' x : quotient r) = quotient.mk' y ↔ r.rel x y := quotient.eq namespace setoid @[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) : r = s := ext H lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b := ⟨λ h a b, h ▸ iff.rfl, ext'⟩ /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel := ⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩ theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl @[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x @[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h @[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z := λ _ _ _ hx, r.2.2.2 hx lemma comm' (s : setoid α) {x y} : s.rel x y ↔ s.rel y x := ⟨s.symm', s.symm'⟩ /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : setoid α := ⟨(=) on f, eq_equivalence.comap f⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r := ext' $ λ x y, quotient.eq lemma ker_apply_mk_out {f : α → β} (a : α) : f (by haveI := setoid.ker f; exact ⟦a⟧.out) = f a := @quotient.mk_out _ (setoid.ker f) a lemma ker_apply_mk_out' {f : α → β} (a : α) : f ((quotient.mk' a : quotient $ setoid.ker f).out') = f a := @quotient.mk_out' _ (setoid.ker f) a lemma ker_def {f : α → β} {x y : α} : (ker f).rel x y ↔ f x = f y := iff.rfl /-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) := { r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2, iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ } /-- The infimum of two equivalence relations. -/ instance : has_inf (setoid α) := ⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl theorem inf_iff_and {r s : setoid α} {x y} : (r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : has_Inf (setoid α) := ⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y, ⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr, λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } instance : partial_order (setoid α) := { le := (≤), lt := λ r s, r ≤ s ∧ ¬s ≤ r, le_refl := λ _ _ _, id, le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ } /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance complete_lattice : complete_lattice (setoid α) := { inf := has_inf.inf, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩, top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩, le_top := λ _ _ _ _, trivial, bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩, bot_le := λ r x y h, h ▸ r.2.1 x, .. complete_lattice_of_Inf (setoid α) $ assume s, ⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ } @[simp] lemma top_def : (⊤ : setoid α).rel = ⊤ := rfl @[simp] lemma bot_def : (⊥ : setoid α).rel = (=) := rfl lemma eq_top_iff {s : setoid α} : s = (⊤ : setoid α) ↔ ∀ x y : α, s.rel x y := by simp [eq_top_iff, setoid.le_def, setoid.top_def, pi.top_apply] /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqv_gen_eq (r : α → α → Prop) : eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} := le_antisymm (λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _) (λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H) (Inf_le $ λ _ _ h, eqv_gen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ lemma sup_eq_eqv_gen (r s : setoid α) : r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) := by rw sup_eq_eqv_gen; refl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ lemma Sup_eq_eqv_gen (S : set (setoid α)) : Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [upper_bounds, le_def, and_imp, exists_imp_distrib], ext, exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩ end /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) := begin rw [Sup_eq_eqv_gen, Sup_image], congr' with x y, simp only [supr_apply, supr_Prop_eq, exists_prop] end /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r := le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel /-- Equivalence closure is idempotent. -/ @[simp] lemma eqv_gen_idem (r : α → α → Prop) : eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r := eqv_gen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) : eqv_gen.setoid r ≤ s := by rw eqv_gen_eq; exact Inf_le h /-- Equivalence closure of binary relations is monotone. -/ theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : eqv_gen.setoid r ≤ eqv_gen.setoid s := eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel := { choice := λ r h, eqv_gen.setoid r, gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩, le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } open function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : injective f ↔ ker f = ⊥ := (@eq_bot_iff (setoid α) _ (ker f)).symm /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ lemma ker_iff_mem_preimage {f : α → β} {x y} : (ker f).rel x y ↔ x ∈ f ⁻¹' {f y} := iff.rfl /-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions `quotient r → β`. -/ def lift_equiv (r : setoid α) : {f : α → β // r ≤ ker f} ≃ (quotient r → β) := { to_fun := λ f, quotient.lift (f : α → β) f.2, inv_fun := λ f, ⟨f ∘ quotient.mk, λ x y h, by simp [ker_def, quotient.sound h]⟩, left_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ x, rfl, right_inv := λ f, funext $ λ x, quotient.induction_on' x $ λ x, rfl } /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β) (Hg : f = g ∘ quotient.mk) : quotient.lift f H = g := begin ext ⟨x⟩, erw [quotient.lift_mk f H, Hg], refl end /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ lemma ker_lift_injective (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) := λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y) (h : injective (quotient.lift f H)) : ker f = r := le_antisymm (λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk) H variables (r : setoid α) (f : α → β) /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotient_ker_equiv_range : quotient (ker f) ≃ set.range f := equiv.of_bijective (@quotient.lift _ (set.range f) (ker f) (λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.ext_val h) ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_mk; exact subtype.ext_iff_val.2 hz⟩⟩ /-- If `f` has a computable right-inverse, then the quotient by its kernel is equivalent to its domain. -/ @[simps] def quotient_ker_equiv_of_right_inverse (g : β → α) (hf : function.right_inverse g f) : quotient (ker f) ≃ β := { to_fun := λ a, quotient.lift_on' a f $ λ _ _, id, inv_fun := λ b, quotient.mk' (g b), left_inv := λ a, quotient.induction_on' a $ λ a, quotient.sound' $ by exact hf (f a), right_inv := hf } /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. If a specific right-inverse of `f` is known, `setoid.quotient_ker_equiv_of_right_inverse` can be definitionally more useful. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) : quotient (ker f) ≃ β := quotient_ker_equiv_of_right_inverse _ (function.surj_inv hf) (right_inverse_surj_inv hf) variables {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : setoid α) (f : α → β) : setoid β := eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) : setoid β := ⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b, ⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩, λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩, λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩, ⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩ /-- A special case of the equivalence closure of an equivalence relation r equalling r. -/ lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) : map r f = map_of_surjective r f h hf := by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. -/ def comap (f : α → β) (r : setoid β) : setoid α := ⟨r.rel on f, r.iseqv.comap _⟩ lemma comap_rel (f : α → β) (r : setoid β) (x y : α) : (comap f r).rel x y ↔ r.rel (f x) (f y) := iff.rfl /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) := ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl /-- The second isomorphism theorem for sets. -/ noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) : quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) := (quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f variables (r f) /-- The third isomorphism theorem for sets. -/ def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) : quotient (ker (quot.map_right h)) ≃ quotient s := { to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $ λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H, show @quot.mk _ _ _ = @quot.mk _ _ _, from H, inv_fun := λ x, quotient.lift_on' x (λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $ λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H, left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $ λ w, by show ⟦_⟧ = _; refl, right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl } variables {r f} open quotient /-- Given an equivalence relation `r` on `α`, the order-preserving bijection between the set of equivalence relations containing `r` and the equivalence relations on the quotient of `α` by `r`. -/ def correspondence (r : setoid α) : {s // r ≤ s} ≃o setoid (quotient r) := { to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep, inv_fun := λ s, ⟨comap quotient.mk' s, λ x y h, by rw [comap_rel, eq_rel.2 h]⟩, left_inv := λ s, subtype.ext_iff_val.2 $ ext' $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ s, let Hm : ker quotient.mk' ≤ comap quotient.mk' s := λ x y h, by rw [comap_rel, (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h)] in ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, rfl, rfl, hs⟩ in t.1.trans' (t.1.symm' $ t.2 $ eq_rel.1 hx) $ t.1.trans' ht $ t.2 $ eq_rel.1 hy, λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end setoid @[simp] lemma quotient.subsingleton_iff {s : setoid α} : subsingleton (quotient s) ↔ s = ⊤ := begin simp only [subsingleton_iff, eq_top_iff, setoid.le_def, setoid.top_def, pi.top_apply, forall_const], refine (surjective_quotient_mk _).forall.trans (forall_congr $ λ a, _), refine (surjective_quotient_mk _).forall.trans (forall_congr $ λ b, _), exact quotient.eq', end lemma quot.subsingleton_iff (r : α → α → Prop) : subsingleton (quot r) ↔ eqv_gen r = ⊤ := begin simp only [subsingleton_iff, _root_.eq_top_iff, pi.le_def, pi.top_apply, forall_const], refine (surjective_quot_mk _).forall.trans (forall_congr $ λ a, _), refine (surjective_quot_mk _).forall.trans (forall_congr $ λ b, _), rw quot.eq, simp only [forall_const, le_Prop_eq], end
1c2f2971f0891be62750b962e266822c6dde023f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/submonoid/membership.lean
66368bcde119fdfafe49eefaced607319f82d3cf
[ "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
11,145
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import group_theory.submonoid.operations import algebra.big_operators.basic import algebra.free_monoid /-! # Submonoids: membership criteria In this file we prove various facts about membership in a submonoid: * `list_prod_mem`, `multiset_prod_mem`, `prod_mem`: if each element of a collection belongs to a multiplicative submonoid, then so does their product; * `list_sum_mem`, `multiset_sum_mem`, `sum_mem`: if each element of a collection belongs to an additive submonoid, then so does their sum; * `pow_mem`, `nsmul_mem`: if `x ∈ S` where `S` is a multiplicative (resp., additive) submonoid and `n` is a natural number, then `x^n` (resp., `n •ℕ x`) belongs to `S`; * `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`, `coe_Sup_of_directed_on`: the supremum of a directed collection of submonoid is their union. * `sup_eq_range`, `mem_sup`: supremum of two submonoids `S`, `T` of a commutative monoid is the set of products; * `closure_singleton_eq`, `mem_closure_singleton`: the multiplicative (resp., additive) closure of `{x}` consists of powers (resp., natural multiples) of `x`. ## Tags submonoid, submonoids -/ open_locale big_operators variables {M : Type*} variables {A : Type*} namespace submonoid section assoc variables [monoid M] (S : submonoid M) @[simp, norm_cast] theorem coe_pow (x : S) (n : ℕ) : ↑(x ^ n) = (x ^ n : M) := S.subtype.map_pow x n @[simp, norm_cast] theorem coe_list_prod (l : list S) : (l.prod : M) = (l.map coe).prod := S.subtype.map_list_prod l @[simp, norm_cast] theorem coe_multiset_prod {M} [comm_monoid M] (S : submonoid M) (m : multiset S) : (m.prod : M) = (m.map coe).prod := S.subtype.map_multiset_prod m @[simp, norm_cast] theorem coe_finset_prod {ι M} [comm_monoid M] (S : submonoid M) (f : ι → S) (s : finset ι) : ↑(∏ i in s, f i) = (∏ i in s, f i : M) := S.subtype.map_prod f s /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem : ∀ {l : list M}, (∀x ∈ l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by rwa [list.prod_cons], have a ∈ S ∧ (∀ x ∈ l, x ∈ S), from list.forall_mem_cons.1 h, S.mul_mem this.1 (list_prod_mem this.2) /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) : ∏ c in t, f c ∈ S := S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi lemma pow_mem {x : M} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := by simpa only [coe_pow] using ((⟨x, hx⟩ : S) ^ n).coe_prop end assoc section non_assoc variables [mul_one_class M] (S : submonoid M) open set @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) {x : M} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _), { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) : ((⨆ i, S i : submonoid M) : set M) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end @[to_additive] lemma coe_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set M) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] @[to_additive] lemma mem_sup_left {S T : submonoid M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : submonoid M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → submonoid M} (i : ι) : ∀ {x : M}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (submonoid M)} {s : submonoid M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs end non_assoc end submonoid namespace free_monoid variables {α : Type*} open submonoid @[to_additive] theorem closure_range_of : closure (set.range $ @of α) = ⊤ := eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs, mul_mem _ (subset_closure $ set.mem_range_self _) hxs end free_monoid namespace submonoid variables [monoid M] open monoid_hom lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, trivial, pow_one x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _ /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y := by rw [closure_singleton_eq, mem_mrange]; refl lemma mem_closure_singleton_self {y : M} : y ∈ closure ({y} : set M) := mem_closure_singleton.2 ⟨1, pow_one y⟩ lemma closure_singleton_one : closure ({1} : set M) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift (coe : s → M)).mrange := by rw [mrange, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp, free_monoid.lift_comp_of, subtype.range_coe] @[to_additive] lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) : ∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x := begin rw [closure_eq_mrange, mem_mrange] at hx, rcases hx with ⟨l, hx⟩, exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩ end /-- The submonoid generated by an element. -/ def powers (n : M) : submonoid M := submonoid.copy (powers_hom M n).mrange (set.range ((^) n : ℕ → M)) $ set.ext (λ n, exists_congr $ λ i, by simp; refl) @[simp] lemma mem_powers (n : M) : n ∈ powers n := ⟨1, pow_one _⟩ lemma powers_eq_closure (n : M) : powers n = closure {n} := by { ext, exact mem_closure_singleton.symm } lemma powers_subset {n : M} {P : submonoid M} (h : n ∈ P) : powers n ≤ P := λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.pow_mem h i end end submonoid namespace submonoid variables {N : Type*} [comm_monoid N] open monoid_hom @[to_additive] lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange := by rw [mrange, ← mrange_inl_sup_mrange_inr, map_sup, map_mrange, coprod_comp_inl, map_mrange, coprod_comp_inr, range_subtype, range_subtype] @[to_additive] lemma mem_sup {s t : submonoid N} {x : N} : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, set_like.exists, coe_subtype, subtype.coe_mk] end submonoid namespace add_submonoid variables [add_monoid A] open set lemma nsmul_mem (S : add_submonoid A) {x : A} (hx : x ∈ S) : ∀ n : ℕ, n •ℕ x ∈ S | 0 := S.zero_mem | (n+1) := S.add_mem hx (nsmul_mem n) lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, trivial, one_nsmul x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ nsmul_mem _ (subset_closure $ set.mem_singleton _) _ /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, n •ℕ x = y := by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] /-- The additive submonoid generated by an element. -/ def multiples (x : A) : add_submonoid A := add_submonoid.copy (multiples_hom A x).mrange (set.range (λ i, nsmul i x : ℕ → A)) $ set.ext (λ n, exists_congr $ λ i, by simp; refl) @[simp] lemma mem_multiples (x : A) : x ∈ multiples x := ⟨1, one_nsmul _⟩ lemma multiples_eq_closure (x : A) : multiples x = closure {x} := by { ext, exact mem_closure_singleton.symm } lemma multiples_subset {x : A} {P : add_submonoid A} (h : x ∈ P) : multiples x ≤ P := λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.nsmul_mem h i end attribute [to_additive add_submonoid.multiples] submonoid.powers attribute [to_additive add_submonoid.mem_multiples] submonoid.mem_powers attribute [to_additive add_submonoid.multiples_eq_closure] submonoid.powers_eq_closure attribute [to_additive add_submonoid.multiples_subset] submonoid.powers_subset end add_submonoid section mul_add lemma of_mul_image_powers_eq_multiples_of_mul [monoid M] {x : M} : additive.of_mul '' ((submonoid.powers x) : set M) = add_submonoid.multiples (additive.of_mul x) := begin ext, split, { rintros ⟨y, ⟨n, hy1⟩, hy2⟩, use n, simpa [← of_mul_pow, hy1] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_pow } end lemma of_add_image_multiples_eq_powers_of_add [add_monoid A] {x : A} : multiplicative.of_add '' ((add_submonoid.multiples x) : set A) = submonoid.powers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_powers_eq_multiples_of_mul, end end mul_add
0f7d6a9ff88d955664dbca9e70539b47df058ac8
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/continuous_on.lean
492859e552e2212640eae5efaa895fcdad6dcc69
[ "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
54,387
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions * `nhds_within` of `nhds` * `continuous_on` of `continuous` * `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. -/ open set filter function open_locale topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] @[simp] lemma nhds_bind_nhds_within {a : α} {s : set α} : (𝓝 a).bind (λ x, 𝓝[s] x) = 𝓝[s] a := bind_inf_principal.trans $ congr_arg2 _ nhds_bind_nhds rfl @[simp] lemma eventually_nhds_nhds_within {a : α} {s : set α} {p : α → Prop} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := filter.ext_iff.1 nhds_bind_nhds_within {x | p x} lemma eventually_nhds_within_iff {a : α} {s : set α} {p : α → Prop} : (∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x := eventually_inf_principal @[simp] lemma eventually_nhds_within_nhds_within {a : α} {s : set α} {p : α → Prop} : (∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := begin refine ⟨λ h, _, λ h, (eventually_nhds_nhds_within.2 h).filter_mono inf_le_left⟩, simp only [eventually_nhds_within_iff] at h ⊢, exact h.mono (λ x hx hxs, (hx hxs).self_of_nhds hxs) end theorem nhds_within_eq (a : α) (s : set α) : 𝓝[s] a = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (t ∩ s) := ((nhds_basis_opens a).inf_principal s).eq_binfi theorem nhds_within_univ (a : α) : 𝓝[set.univ] a = 𝓝 a := by rw [nhds_within, principal_univ, inf_top_eq] lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s) (t : set α) : (𝓝[t] a).has_basis p (λ i, s i ∩ t) := h.inf_principal t lemma nhds_within_basis_open (a : α) (t : set α) : (𝓝[t] a).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ 𝓝[s] a ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := (nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff lemma diff_mem_nhds_within_compl {x : α} {s : set α} (hs : s ∈ 𝓝 x) (t : set α) : s \ t ∈ 𝓝[tᶜ] x := diff_mem_inf_principal_compl hs t lemma diff_mem_nhds_within_diff {x : α} {s t : set α} (hs : s ∈ 𝓝[t] x) (t' : set α) : s \ t' ∈ 𝓝[t \ t'] x := begin rw [nhds_within, diff_eq, diff_eq, ← inf_principal, ← inf_assoc], exact inter_mem_inf hs (mem_principal_self _) end lemma nhds_of_nhds_within_of_nhds {s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) : (t ∈ 𝓝 a) := begin rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩, exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw, end lemma mem_nhds_within_iff_eventually {s t : set α} {x : α} : t ∈ 𝓝[s] x ↔ ∀ᶠ y in 𝓝 x, y ∈ s → y ∈ t := begin rw [mem_nhds_within_iff_exists_mem_nhds_inter], split, { rintro ⟨u, hu, hut⟩, exact eventually_of_mem hu (λ x hxu hxs, hut ⟨hxu, hxs⟩) }, { refine λ h, ⟨_, h, λ y hy, hy.1 hy.2⟩ } end lemma mem_nhds_within_iff_eventually_eq {s t : set α} {x : α} : t ∈ 𝓝[s] x ↔ s =ᶠ[𝓝 x] (s ∩ t : set α) := by simp_rw [mem_nhds_within_iff_eventually, eventually_eq_set, mem_inter_iff, iff_self_and] lemma nhds_within_eq_iff_eventually_eq {s t : set α} {x : α} : 𝓝[s] x = 𝓝[t] x ↔ s =ᶠ[𝓝 x] t := begin simp_rw [filter.ext_iff, mem_nhds_within_iff_eventually, eventually_eq_set], split, { intro h, filter_upwards [(h t).mpr (eventually_of_forall $ λ x, id), (h s).mp (eventually_of_forall $ λ x, id)], exact λ x, iff.intro, }, { refine λ h u, eventually_congr (h.mono $ λ x h, _), rw [h] } end lemma nhds_within_le_iff {s t : set α} {x : α} : 𝓝[s] x ≤ 𝓝[t] x ↔ t ∈ 𝓝[s] x := begin simp_rw [filter.le_def, mem_nhds_within_iff_eventually], split, { exact λ h, (h t $ eventually_of_forall (λ x, id)).mono (λ x, id) }, { exact λ h u hu, (h.and hu).mono (λ x hx h, hx.2 $ hx.1 h) } end lemma preimage_nhds_within_coinduced' {π : α → β} {s : set β} {t : set α} {a : α} (h : a ∈ t) (ht : is_open t) (hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) : π ⁻¹' s ∈ 𝓝[t] a := begin letI := topological_space.coinduced (λ x : t, π x) subtype.topological_space, rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩, refine mem_nhds_within_iff_exists_mem_nhds_inter.mpr ⟨π ⁻¹' V, mem_nhds_iff.mpr ⟨t ∩ π ⁻¹' V, inter_subset_right t (π ⁻¹' V), _, mem_sep h mem_V⟩, subset.trans (inter_subset_left _ _) (preimage_mono hVs)⟩, obtain ⟨u, hu1, hu2⟩ := is_open_induced_iff.mp (is_open_coinduced.1 V_op), rw [preimage_comp] at hu2, rw [set.inter_comm, ←(subtype.preimage_coe_eq_preimage_coe_iff.mp hu2)], exact hu1.inter ht, end lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ 𝓝[t] a := mem_inf_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ 𝓝[s] a := mem_inf_of_right (mem_principal_self s) theorem eventually_mem_nhds_within {a : α} {s : set α} : ∀ᶠ x in 𝓝[s] a, x ∈ s := self_mem_nhds_within theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ 𝓝[s] a := inter_mem self_mem_nhds_within (mem_inf_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : 𝓝[s] a ≤ 𝓝[t] a := inf_le_inf_left _ (principal_mono.mpr h) lemma pure_le_nhds_within {a : α} {s : set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a := le_inf (pure_le_nhds a) (le_principal_iff.2 ha) lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) : a ∈ t := pure_le_nhds_within ha ht lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α} (h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h lemma tendsto_const_nhds_within {l : filter β} {s : set α} {a : α} (ha : a ∈ s) : tendsto (λ x : β, a) l (𝓝[s] a) := tendsto_const_pure.mono_right $ pure_le_nhds_within ha theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝[s] a) : 𝓝[s] a = 𝓝[s ∩ t] a := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhds_within h))) (inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : 𝓝[s] a = 𝓝[s ∩ t] a := nhds_within_restrict'' s $ mem_inf_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : 𝓝[s] a = 𝓝[s ∩ t] a := nhds_within_restrict' s (is_open.mem_nhds h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) : 𝓝[t] a ≤ 𝓝[s] a := nhds_within_le_iff.mpr h theorem nhds_within_le_nhds {a : α} {s : set α} : 𝓝[s] a ≤ 𝓝 a := by { rw ← nhds_within_univ, apply nhds_within_le_of_mem, exact univ_mem } lemma nhds_within_eq_nhds_within' {a : α} {s t u : set α} (hs : s ∈ 𝓝 a) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhds_within_restrict' t hs, nhds_within_restrict' u hs, h₂] theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem is_open.nhds_within_eq {a : α} {s : set α} (h : is_open s) (ha : a ∈ s) : 𝓝[s] a = 𝓝 a := inf_eq_left.2 $ le_principal_iff.2 $ is_open.mem_nhds h ha lemma preimage_nhds_within_coinduced {π : α → β} {s : set β} {t : set α} {a : α} (h : a ∈ t) (ht : is_open t) (hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) : π ⁻¹' s ∈ 𝓝 a := by { rw ← ht.nhds_within_eq h, exact preimage_nhds_within_coinduced' h ht hs } @[simp] theorem nhds_within_empty (a : α) : 𝓝[∅] a = ⊥ := by rw [nhds_within, principal_empty, inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : 𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a := by { delta nhds_within, rw [←inf_sup_left, sup_principal] } theorem nhds_within_inter (a : α) (s t : set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a := by { delta nhds_within, rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] } theorem nhds_within_inter' (a : α) (s t : set α) : 𝓝[s ∩ t] a = (𝓝[s] a) ⊓ 𝓟 t := by { delta nhds_within, rw [←inf_principal, inf_assoc] } theorem nhds_within_inter_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) : 𝓝[s ∩ t] a = 𝓝[t] a := by { rw [nhds_within_inter, inf_eq_right], exact nhds_within_le_of_mem h } @[simp] theorem nhds_within_singleton (a : α) : 𝓝[{a}] a = pure a := by rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)] @[simp] theorem nhds_within_insert (a : α) (s : set α) : 𝓝[insert a s] a = pure a ⊔ 𝓝[s] a := by rw [← singleton_union, nhds_within_union, nhds_within_singleton] lemma mem_nhds_within_insert {a : α} {s t : set α} : t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a := by simp lemma insert_mem_nhds_within_insert {a : α} {s t : set α} (h : t ∈ 𝓝[s] a) : insert a t ∈ 𝓝[insert a s] a := by simp [mem_of_superset h] lemma insert_mem_nhds_iff {a : α} {s : set α} : insert a s ∈ 𝓝 a ↔ s ∈ 𝓝[≠] a := by simp only [nhds_within, mem_inf_principal, mem_compl_iff, mem_singleton_iff, or_iff_not_imp_left, insert_def] @[simp] theorem nhds_within_compl_singleton_sup_pure (a : α) : 𝓝[≠] a ⊔ pure a = 𝓝 a := by rw [← nhds_within_singleton, ← nhds_within_union, compl_union_self, nhds_within_univ] lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : 𝓝[s ×ˢ t] (a, b) = 𝓝[s] a ×ᶠ 𝓝[t] b := by { delta nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } lemma nhds_within_prod {α : Type*} [topological_space α] {β : Type*} [topological_space β] {s u : set α} {t v : set β} {a : α} {b : β} (hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) : (u ×ˢ v) ∈ 𝓝[s ×ˢ t] (a, b) := by { rw nhds_within_prod_eq, exact prod_mem_prod hu hv, } lemma nhds_within_pi_eq' {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : I.finite) (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi I s] x = ⨅ i, comap (λ x, x i) (𝓝 (x i) ⊓ ⨅ (hi : i ∈ I), 𝓟 (s i)) := by simp only [nhds_within, nhds_pi, filter.pi, comap_inf, comap_infi, pi_def, comap_principal, ← infi_principal_finite hI, ← infi_inf_eq] lemma nhds_within_pi_eq {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : I.finite) (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi I s] x = (⨅ i ∈ I, comap (λ x, x i) (𝓝[s i] (x i))) ⊓ ⨅ (i ∉ I), comap (λ x, x i) (𝓝 (x i)) := begin simp only [nhds_within, nhds_pi, filter.pi, pi_def, ← infi_principal_finite hI, comap_inf, comap_principal, eval], rw [infi_split _ (λ i, i ∈ I), inf_right_comm], simp only [infi_inf_eq] end lemma nhds_within_pi_univ_eq {ι : Type*} {α : ι → Type*} [finite ι] [Π i, topological_space (α i)] (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi univ s] x = ⨅ i, comap (λ x, x i) 𝓝[s i] (x i) := by simpa [nhds_within] using nhds_within_pi_eq finite_univ s x lemma nhds_within_pi_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : 𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] (x i) = ⊥ := by simp only [nhds_within, nhds_pi, pi_inf_principal_pi_eq_bot] lemma nhds_within_pi_ne_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : (𝓝[pi I s] x).ne_bot ↔ ∀ i ∈ I, (𝓝[s i] (x i)).ne_bot := by simp [ne_bot_iff, nhds_within_pi_eq_bot] theorem filter.tendsto.piecewise_nhds_within {f g : α → β} {t : set α} [∀ x, decidable (x ∈ t)] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (𝓝[s ∩ t] a) l) (h₁ : tendsto g (𝓝[s ∩ tᶜ] a) l) : tendsto (piecewise t f g) (𝓝[s] a) l := by apply tendsto.piecewise; rwa ← nhds_within_inter' theorem filter.tendsto.if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (𝓝[s ∩ {x | p x}] a) l) (h₁ : tendsto g (𝓝[s ∩ {x | ¬ p x}] a) l) : tendsto (λ x, if p x then f x else g x) (𝓝[s] a) l := h₀.piecewise_nhds_within h₁ lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (𝓝[s] a) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (f '' (t ∩ s)) := ((nhds_within_basis_open a s).map f).eq_binfi theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (𝓝[t] a) l) : tendsto f (𝓝[s] a) l := h.mono_left $ nhds_within_mono a hst theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (𝓝[s] a)) : tendsto f l (𝓝[t] a) := h.mono_right (nhds_within_mono a hst) theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (𝓝[s] a) l := h.mono_left inf_le_left theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : 𝓟 t = comap coe (𝓟 ((coe : s → α) '' t)) := by rw [comap_principal, set.preimage_image_eq _ subtype.coe_injective] lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : ne_bot (𝓝[s] x) := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : ne_bot $ 𝓝[s] x) : x ∈ s := by simpa only [hs.closure_eq] using mem_closure_iff_nhds_within_ne_bot.2 hx lemma dense_range.nhds_within_ne_bot {ι : Type*} {f : ι → α} (h : dense_range f) (x : α) : ne_bot (𝓝[range f] x) := mem_closure_iff_cluster_pt.1 (h x) lemma mem_closure_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) := by simp only [mem_closure_iff_nhds_within_ne_bot, nhds_within_pi_ne_bot] lemma closure_pi_set {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] (I : set ι) (s : Π i, set (α i)) : closure (pi I s) = pi I (λ i, closure (s i)) := set.ext $ λ x, mem_closure_pi lemma dense_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {s : Π i, set (α i)} (I : set ι) (hs : ∀ i ∈ I, dense (s i)) : dense (pi I s) := by simp only [dense_iff_closure_eq, closure_pi_set, pi_congr rfl (λ i hi, (hs i hi).closure_eq), pi_univ] lemma eventually_eq_nhds_within_iff {f g : α → β} {s : set α} {a : α} : (f =ᶠ[𝓝[s] a] g) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x := mem_inf_principal lemma eventually_eq_nhds_within_of_eq_on {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) : f =ᶠ[𝓝[s] a] g := mem_inf_of_right h lemma set.eq_on.eventually_eq_nhds_within {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) : f =ᶠ[𝓝[s] a] g := eventually_eq_nhds_within_of_eq_on h lemma tendsto_nhds_within_congr {f g : α → β} {s : set α} {a : α} {l : filter β} (hfg : ∀ x ∈ s, f x = g x) (hf : tendsto f (𝓝[s] a) l) : tendsto g (𝓝[s] a) l := (tendsto_congr' $ eventually_eq_nhds_within_of_eq_on hfg).1 hf lemma eventually_nhds_within_of_forall {s : set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_inf_of_right h lemma tendsto_nhds_within_of_tendsto_nhds_of_eventually_within {a : α} {l : filter β} {s : set α} (f : β → α) (h1 : tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) : tendsto f l (𝓝[s] a) := tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩ @[simp] lemma tendsto_nhds_within_range {a : α} {l : filter β} {f : β → α} : tendsto f l (𝓝[range f] a) ↔ tendsto f l (𝓝 a) := ⟨λ h, h.mono_right inf_le_left, λ h, tendsto_inf.2 ⟨h, tendsto_principal.2 $ eventually_of_forall mem_range_self⟩⟩ lemma filter.eventually_eq.eq_of_nhds_within {s : set α} {f g : α → β} {a : α} (h : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : f a = g a := h.self_of_nhds_within hmem lemma eventually_nhds_within_of_eventually_nhds {α : Type*} [topological_space α] {s : set α} {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_nhds_within_of_mem_nhds h /-! ### `nhds_within` and subtypes -/ theorem mem_nhds_within_subtype {s : set α} {a : {x // x ∈ s}} {t u : set {x // x ∈ s}} : t ∈ 𝓝[u] a ↔ t ∈ comap (coe : s → α) (𝓝[coe '' u] a) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : 𝓝[t] a = comap (coe : s → α) (𝓝[coe '' t] a) := filter.ext $ λ u, mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_coe {s : set α} {a : α} (h : a ∈ s) : 𝓝[s] a = map (coe : s → α) (𝓝 ⟨a, h⟩) := by simpa only [subtype.range_coe] using (embedding_subtype_coe.map_nhds_eq ⟨a, h⟩).symm theorem mem_nhds_subtype_iff_nhds_within {s : set α} {a : s} {t : set s} : t ∈ 𝓝 a ↔ coe '' t ∈ 𝓝[s] (a : α) := by rw [nhds_within_eq_map_subtype_coe a.coe_prop, mem_map, preimage_image_eq _ subtype.coe_injective, subtype.coe_eta] theorem preimage_coe_mem_nhds_subtype {s t : set α} {a : s} : coe ⁻¹' t ∈ 𝓝 a ↔ t ∈ 𝓝[s] ↑a := by simp only [mem_nhds_subtype_iff_nhds_within, subtype.image_preimage_coe, inter_mem_iff, self_mem_nhds_within, and_true] theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (𝓝[s] a) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by simp only [tendsto, nhds_within_eq_map_subtype_coe h, filter.map_map, restrict] variables [topological_space β] [topological_space γ] [topological_space δ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (𝓝[s] x) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (𝓝[s] x) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : maps_to f s t) : tendsto f (𝓝[s] x) (𝓝[t] (f x)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_of_right $ mem_principal.2 $ ht⟩ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (𝓝[s] x) (𝓝[f '' s] (f x)) := h.tendsto_nhds_within (maps_to_image _ _) lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} {x : α} {y : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g t y) : continuous_within_at (prod.map f g) (s ×ˢ t) (x, y) := begin unfold continuous_within_at at *, rw [nhds_within_prod_eq, prod.map, nhds_prod_eq], exact hf.prod_map hg, end lemma continuous_within_at_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] {f : α → Π i, π i} {s : set α} {x : α} : continuous_within_at f s x ↔ ∀ i, continuous_within_at (λ y, f y i) s x := tendsto_pi_nhds lemma continuous_on_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] {f : α → Π i, π i} {s : set α} : continuous_on f s ↔ ∀ i, continuous_on (λ y, f y i) s := ⟨λ h i x hx, tendsto_pi_nhds.1 (h x hx) i, λ h x hx, tendsto_pi_nhds.2 (λ i, h i x hx)⟩ lemma continuous_within_at.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {a : α} {s : set α} (hf : continuous_within_at f s a) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_within_at g s a) : continuous_within_at (λ a, i.insert_nth (f a) (g a)) s a := hf.fin_insert_nth i hg lemma continuous_on.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {s : set α} (hf : continuous_on f s) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_on g s) : continuous_on (λ a, i.insert_nth (f a) (g a)) s := λ a ha, (hf a ha).fin_insert_nth i (hg a ha) theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (s.restrict f) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous_def]; simp only [this] /-- If a function is continuous on a set for some topologies, then it is continuous on the same set with respect to any finer topology on the source space. -/ lemma continuous_on.mono_dom {α β : Type*} {t₁ t₂ : topological_space α} {t₃ : topological_space β} (h₁ : t₂ ≤ t₁) {s : set α} {f : α → β} (h₂ : @continuous_on α β t₁ t₃ f s) : @continuous_on α β t₂ t₃ f s := begin rw continuous_on_iff' at h₂ ⊢, assume t ht, rcases h₂ t ht with ⟨u, hu, h'u⟩, exact ⟨u, h₁ u hu, h'u⟩ end /-- If a function is continuous on a set for some topologies, then it is continuous on the same set with respect to any coarser topology on the target space. -/ lemma continuous_on.mono_rng {α β : Type*} {t₁ : topological_space α} {t₂ t₃ : topological_space β} (h₁ : t₂ ≤ t₃) {s : set α} {f : α → β} (h₂ : @continuous_on α β t₁ t₂ f s) : @continuous_on α β t₁ t₃ f s := begin rw continuous_on_iff' at h₂ ⊢, assume t ht, exact h₂ t (h₁ t ht) end theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff, eq_comm] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} (hf : continuous_on f s) (hg : continuous_on g t) : continuous_on (prod.map f g) (s ×ˢ t) := λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy) lemma continuous_on_empty (f : α → β) : continuous_on f ∅ := λ x, false.elim lemma continuous_on_singleton (f : α → β) (a : α) : continuous_on f {a} := forall_eq.2 $ by simpa only [continuous_within_at, nhds_within_singleton, tendsto_pure_left] using λ s, mem_of_mem_nhds lemma set.subsingleton.continuous_on {s : set α} (hs : s.subsingleton) (f : α → β) : continuous_on f s := hs.induction_on (continuous_on_empty f) (continuous_on_singleton f) theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : 𝓝[s] x ≤ comap f (𝓝[f '' s] (f x)) := ctsf.tendsto_nhds_within_image.le_comap @[simp] lemma comap_nhds_within_range {α} (f : α → β) (y : β) : comap f (𝓝[range f] y) = comap f (𝓝 y) := comap_inf_principal_range theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := h.mono_left (nhds_within_mono x hs) lemma continuous_within_at.mono_of_mem {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : t ∈ 𝓝[s] x) : continuous_within_at f s x := h.mono_left (nhds_within_le_of_mem hs) lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝[s] x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at_union {f : α → β} {s t : set α} {x : α} : continuous_within_at f (s ∪ t) x ↔ continuous_within_at f s x ∧ continuous_within_at f t x := by simp only [continuous_within_at, nhds_within_union, tendsto_sup] lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := continuous_within_at_union.2 ⟨hs, ht⟩ lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := by haveI := (mem_closure_iff_nhds_within_ne_bot.1 hx); exact (mem_closure_of_tendsto h $ mem_of_superset self_mem_nhds_within (subset_preimage_image f s)) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : maps_to f s A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma set.maps_to.closure_of_continuous_within_at {f : α → β} {s : set α} {t : set β} (h : maps_to f s t) (hc : ∀ x ∈ closure s, continuous_within_at f s x) : maps_to f (closure s) (closure t) := λ x hx, (hc x hx).mem_closure hx h lemma set.maps_to.closure_of_continuous_on {f : α → β} {s : set α} {t : set β} (h : maps_to f s t) (hc : continuous_on f (closure s)) : maps_to f (closure s) (closure t) := h.closure_of_continuous_within_at $ λ x hx, (hc x hx).mono subset_closure lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := maps_to'.1 $ (maps_to_image f s).closure_of_continuous_within_at hf lemma continuous_on.image_closure {f : α → β} {s : set α} (hf : continuous_on f (closure s)) : f '' (closure s) ⊆ closure (f '' s) := continuous_within_at.image_closure $ λ x hx, (hf x hx).mono subset_closure @[simp] lemma continuous_within_at_singleton {f : α → β} {x : α} : continuous_within_at f {x} x := by simp only [continuous_within_at, nhds_within_singleton, tendsto_pure_nhds] @[simp] lemma continuous_within_at_insert_self {f : α → β} {x : α} {s : set α} : continuous_within_at f (insert x s) x ↔ continuous_within_at f s x := by simp only [← singleton_union, continuous_within_at_union, continuous_within_at_singleton, true_and] alias continuous_within_at_insert_self ↔ _ continuous_within_at.insert_self lemma continuous_within_at.diff_iff {f : α → β} {s t : set α} {x : α} (ht : continuous_within_at f t x) : continuous_within_at f (s \ t) x ↔ continuous_within_at f s x := ⟨λ h, (h.union ht).mono $ by simp only [diff_union_self, subset_union_left], λ h, h.mono (diff_subset _ _)⟩ @[simp] lemma continuous_within_at_diff_self {f : α → β} {s : set α} {x : α} : continuous_within_at f (s \ {x}) x ↔ continuous_within_at f s x := continuous_within_at_singleton.diff_iff @[simp] lemma continuous_within_at_compl_self {f : α → β} {a : α} : continuous_within_at f {a}ᶜ a ↔ continuous_at f a := by rw [compl_eq_univ_diff, continuous_within_at_diff_self, continuous_within_at_univ] @[simp] lemma continuous_within_at_update_same [decidable_eq α] {f : α → β} {s : set α} {x : α} {y : β} : continuous_within_at (update f x y) s x ↔ tendsto f (𝓝[s \ {x}] x) (𝓝 y) := calc continuous_within_at (update f x y) s x ↔ tendsto (update f x y) (𝓝[s \ {x}] x) (𝓝 y) : by rw [← continuous_within_at_diff_self, continuous_within_at, function.update_same] ... ↔ tendsto f (𝓝[s \ {x}] x) (𝓝 y) : tendsto_congr' $ eventually_nhds_within_iff.2 $ eventually_of_forall $ λ z hz, update_noteq hz.2 _ _ @[simp] lemma continuous_at_update_same [decidable_eq α] {f : α → β} {x : α} {y : β} : continuous_at (function.update f x y) x ↔ tendsto f (𝓝[≠] x) (𝓝 y) := by rw [← continuous_within_at_univ, continuous_within_at_update_same, compl_eq_univ_diff] theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin refine continuous_on_iff'.2 (λ t ht, ⟨f '' (t ∩ s), _, _⟩), { rw ← image_restrict, exact h _ (ht.preimage continuous_subtype_coe) }, { rw [inter_eq_self_of_subset_left (image_subset f (inter_subset_right t s)), hleft.image_inter'] }, end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' hx at A, exact A.congr' h'.eventually_eq_nhds_within.symm end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : eq_on g f s) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_on_congr {f g : α → β} {s : set α} (h' : eq_on g f s) : continuous_on g s ↔ continuous_on f s := ⟨λ h, continuous_on.congr h h'.symm, λ h, h.congr h'⟩ lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at_iff_continuous_at {f : α → β} {s : set α} {x : α} (h : s ∈ 𝓝 x) : continuous_within_at f s x ↔ continuous_at f x := by rw [← univ_inter s, continuous_within_at_inter h, continuous_within_at_univ] lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := (continuous_within_at_iff_continuous_at hs).mp h lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x := (h x (mem_of_mem_nhds hx)).continuous_at hx lemma continuous_at.continuous_on {f : α → β} {s : set α} (hcont : ∀ x ∈ s, continuous_at f x) : continuous_on f s := λ x hx, (hcont x hx).continuous_within_at lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : maps_to f s t) : continuous_within_at (g ∘ f) s x := hg.tendsto.comp (hf.tendsto_nhds_within h) lemma continuous_within_at.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma continuous_at.comp_continuous_within_at {g : β → γ} {f : α → β} {s : set α} {x : α} (hg : continuous_at g (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) s x := hg.continuous_within_at.comp hf (maps_to_univ _ _) lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : maps_to f s t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, (hf x (h hx)).mono_left (nhds_within_mono _ h) lemma antitone_continuous_on {f : α → β} : antitone (continuous_on f) := λ s t hst hf, hf.mono hst lemma continuous_on.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) : continuous_on (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := h.continuous_at.continuous_within_at lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf (maps_to_univ _ _) lemma continuous_on.comp_continuous {g : β → γ} {f : α → β} {s : set β} (hg : continuous_on g s) (hf : continuous f) (hs : ∀ x, f x ∈ s) : continuous (g ∘ f) := begin rw continuous_iff_continuous_on_univ at *, exact hg.comp hf (λ x _, hs x), end lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h ht lemma set.left_inv_on.map_nhds_within_eq {f : α → β} {g : β → α} {x : β} {s : set β} (h : left_inv_on f g s) (hx : f (g x) = x) (hf : continuous_within_at f (g '' s) (g x)) (hg : continuous_within_at g s x) : map g (𝓝[s] x) = 𝓝[g '' s] (g x) := begin apply le_antisymm, { exact hg.tendsto_nhds_within (maps_to_image _ _) }, { have A : g ∘ f =ᶠ[𝓝[g '' s] (g x)] id, from h.right_inv_on_image.eq_on.eventually_eq_of_mem self_mem_nhds_within, refine le_map_of_right_inverse A _, simpa only [hx] using hf.tendsto_nhds_within (h.maps_to (surj_on_image _ _)) } end lemma function.left_inverse.map_nhds_eq {f : α → β} {g : β → α} {x : β} (h : function.left_inverse f g) (hf : continuous_within_at f (range g) (g x)) (hg : continuous_at g x) : map g (𝓝 x) = 𝓝[range g] (g x) := by simpa only [nhds_within_univ, image_univ] using (h.left_inv_on univ).map_nhds_within_eq (h x) (by rwa image_univ) hg.continuous_within_at lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝[f '' s] (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h.tendsto_nhds_within (maps_to_image _ _) ht lemma filter.eventually_eq.congr_continuous_within_at {f g : α → β} {s : set α} {x : α} (h : f =ᶠ[𝓝[s] x] g) (hx : f x = g x) : continuous_within_at f s x ↔ continuous_within_at g s x := by rw [continuous_within_at, hx, tendsto_congr' h, continuous_within_at] lemma continuous_within_at.congr_of_eventually_eq {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : continuous_within_at f₁ s x := (h₁.congr_continuous_within_at hx).2 h lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_eventually_eq (mem_of_superset self_mem_nhds_within h₁) hx lemma continuous_within_at.congr_mono {f g : α → β} {s s₁ : set α} {x : α} (h : continuous_within_at f s x) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x): continuous_within_at g s₁ x := (h.mono h₁).congr h' hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open.inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.is_open_preimage {f : α → β} {s : set α} {t : set β} (h : continuous_on f s) (hs : is_open s) (hp : f ⁻¹' t ⊆ s) (ht : is_open t) : is_open (f ⁻¹' t) := begin convert (continuous_on_open_iff hs).mp h t ht, rw [inter_comm, inter_eq_self_of_subset_left hp], end lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed.inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) : interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) (hf.preimage_open_of_open hs is_open_interior) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, hs.interior_eq] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by rw [preimage_inter, inter_assoc, inter_left_comm _ s, ← inter_assoc s s, inter_self], rw this, exact hu.inter hv }, { rw [preimage_sUnion, inter_Union₂], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := hf.prod_mk_nhds hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx) lemma inducing.continuous_within_at_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} {x : α} : continuous_within_at f s x ↔ continuous_within_at (g ∘ f) s x := by simp_rw [continuous_within_at, inducing.tendsto_nhds_iff hg] lemma inducing.continuous_on_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := by simp_rw [continuous_on, hg.continuous_within_at_iff] lemma embedding.continuous_on_iff {f : α → β} {g : β → γ} (hg : embedding g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := inducing.continuous_on_iff hg.1 lemma embedding.map_nhds_within_eq {f : α → β} (hf : embedding f) (s : set α) (x : α) : map f (𝓝[s] x) = 𝓝[f '' s] (f x) := by rw [nhds_within, map_inf hf.inj, hf.map_nhds_eq, map_principal, ← nhds_within_inter', inter_eq_self_of_subset_right (image_subset_range _ _)] lemma open_embedding.map_nhds_within_preimage_eq {f : α → β} (hf : open_embedding f) (s : set β) (x : α) : map f (𝓝[f ⁻¹' s] x) = 𝓝[s] (f x) := begin rw [hf.to_embedding.map_nhds_within_eq, image_preimage_eq_inter_range], apply nhds_within_eq_nhds_within (mem_range_self _) hf.open_range, rw [inter_assoc, inter_self] end lemma continuous_within_at_of_not_mem_closure {f : α → β} {s : set α} {x : α} : x ∉ closure s → continuous_within_at f s x := begin intros hx, rw [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, not_not] at hx, rw [continuous_within_at, hx], exact tendsto_bot, end lemma continuous_on.piecewise' {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)] (hpf : ∀ a ∈ s ∩ frontier t, tendsto f (𝓝[s ∩ t] a) (𝓝 (piecewise t f g a))) (hpg : ∀ a ∈ s ∩ frontier t, tendsto g (𝓝[s ∩ tᶜ] a) (𝓝 (piecewise t f g a))) (hf : continuous_on f $ s ∩ t) (hg : continuous_on g $ s ∩ tᶜ) : continuous_on (piecewise t f g) s := begin intros x hx, by_cases hx' : x ∈ frontier t, { exact (hpf x ⟨hx, hx'⟩).piecewise_nhds_within (hpg x ⟨hx, hx'⟩) }, { rw [← inter_univ s, ← union_compl_self t, inter_union_distrib_left] at hx ⊢, cases hx, { apply continuous_within_at.union, { exact (hf x hx).congr (λ y hy, piecewise_eq_of_mem _ _ _ hy.2) (piecewise_eq_of_mem _ _ _ hx.2) }, { have : x ∉ closure tᶜ, from λ h, hx' ⟨subset_closure hx.2, by rwa closure_compl at h⟩, exact continuous_within_at_of_not_mem_closure (λ h, this (closure_inter_subset_inter_closure _ _ h).2) } }, { apply continuous_within_at.union, { have : x ∉ closure t, from (λ h, hx' ⟨h, (λ (h' : x ∈ interior t), hx.2 (interior_subset h'))⟩), exact continuous_within_at_of_not_mem_closure (λ h, this (closure_inter_subset_inter_closure _ _ h).2) }, { exact (hg x hx).congr (λ y hy, piecewise_eq_of_not_mem _ _ _ hy.2) (piecewise_eq_of_not_mem _ _ _ hx.2) } } } end lemma continuous_on.if' {s : set α} {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hpf : ∀ a ∈ s ∩ frontier {a | p a}, tendsto f (𝓝[s ∩ {a | p a}] a) (𝓝 $ if p a then f a else g a)) (hpg : ∀ a ∈ s ∩ frontier {a | p a}, tendsto g (𝓝[s ∩ {a | ¬p a}] a) (𝓝 $ if p a then f a else g a)) (hf : continuous_on f $ s ∩ {a | p a}) (hg : continuous_on g $ s ∩ {a | ¬p a}) : continuous_on (λ a, if p a then f a else g a) s := hf.piecewise' hpf hpg hg lemma continuous_on.if {α β : Type*} [topological_space α] [topological_space β] {p : α → Prop} [∀ a, decidable (p a)] {s : set α} {f g : α → β} (hp : ∀ a ∈ s ∩ frontier {a | p a}, f a = g a) (hf : continuous_on f $ s ∩ closure {a | p a}) (hg : continuous_on g $ s ∩ closure {a | ¬ p a}) : continuous_on (λa, if p a then f a else g a) s := begin apply continuous_on.if', { rintros a ha, simp only [← hp a ha, if_t_t], apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure), exact hf a ⟨ha.1, ha.2.1⟩ }, { rintros a ha, simp only [hp a ha, if_t_t], apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure), rcases ha with ⟨has, ⟨_, ha⟩⟩, rw [← mem_compl_iff, ← closure_compl] at ha, apply hg a ⟨has, ha⟩ }, { exact hf.mono (inter_subset_inter_right s subset_closure) }, { exact hg.mono (inter_subset_inter_right s subset_closure) } end lemma continuous_on.piecewise {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)] (ht : ∀ a ∈ s ∩ frontier t, f a = g a) (hf : continuous_on f $ s ∩ closure t) (hg : continuous_on g $ s ∩ closure tᶜ) : continuous_on (piecewise t f g) s := hf.if ht hg lemma continuous_if' {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hpf : ∀ a ∈ frontier {x | p x}, tendsto f (𝓝[{x | p x}] a) (𝓝 $ ite (p a) (f a) (g a))) (hpg : ∀ a ∈ frontier {x | p x}, tendsto g (𝓝[{x | ¬p x}] a) (𝓝 $ ite (p a) (f a) (g a))) (hf : continuous_on f {x | p x}) (hg : continuous_on g {x | ¬p x}) : continuous (λ a, ite (p a) (f a) (g a)) := begin rw continuous_iff_continuous_on_univ, apply continuous_on.if'; simp *; assumption end lemma continuous_if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous_on f (closure {x | p x})) (hg : continuous_on g (closure {x | ¬p x})) : continuous (λ a, if p a then f a else g a) := begin rw continuous_iff_continuous_on_univ, apply continuous_on.if; simp; assumption end lemma continuous.if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λ a, if p a then f a else g a) := continuous_if hp hf.continuous_on hg.continuous_on lemma continuous_if_const (p : Prop) {f g : α → β} [decidable p] (hf : p → continuous f) (hg : ¬ p → continuous g) : continuous (λ a, if p then f a else g a) := by { split_ifs, exact hf h, exact hg h } lemma continuous.if_const (p : Prop) {f g : α → β} [decidable p] (hf : continuous f) (hg : continuous g) : continuous (λ a, if p then f a else g a) := continuous_if_const p (λ _, hf) (λ _, hg) lemma continuous_piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous_on f (closure s)) (hg : continuous_on g (closure sᶜ)) : continuous (piecewise s f g) := continuous_if hs hf hg lemma continuous.piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (piecewise s f g) := hf.if hs hg lemma is_open.ite' {s s' t : set α} (hs : is_open s) (hs' : is_open s') (ht : ∀ x ∈ frontier t, x ∈ s ↔ x ∈ s') : is_open (t.ite s s') := begin classical, simp only [is_open_iff_continuous_mem, set.ite] at *, convert continuous_piecewise (λ x hx, propext (ht x hx)) hs.continuous_on hs'.continuous_on, ext x, by_cases hx : x ∈ t; simp [hx] end lemma is_open.ite {s s' t : set α} (hs : is_open s) (hs' : is_open s') (ht : s ∩ frontier t = s' ∩ frontier t) : is_open (t.ite s s') := hs.ite' hs' $ λ x hx, by simpa [hx] using ext_iff.1 ht x lemma ite_inter_closure_eq_of_inter_frontier_eq {s s' t : set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure t = s ∩ closure t := by rw [closure_eq_self_union_frontier, inter_union_distrib_left, inter_union_distrib_left, ite_inter_self, ite_inter_of_inter_eq _ ht] lemma ite_inter_closure_compl_eq_of_inter_frontier_eq {s s' t : set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure tᶜ = s' ∩ closure tᶜ := by { rw [← ite_compl, ite_inter_closure_eq_of_inter_frontier_eq], rwa [frontier_compl, eq_comm] } lemma continuous_on_piecewise_ite' {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)] (h : continuous_on f (s ∩ closure t)) (h' : continuous_on f' (s' ∩ closure tᶜ)) (H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) : continuous_on (t.piecewise f f') (t.ite s s') := begin apply continuous_on.piecewise, { rwa ite_inter_of_inter_eq _ H }, { rwa ite_inter_closure_eq_of_inter_frontier_eq H }, { rwa ite_inter_closure_compl_eq_of_inter_frontier_eq H } end lemma continuous_on_piecewise_ite {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)] (h : continuous_on f s) (h' : continuous_on f' s') (H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) : continuous_on (t.piecewise f f') (t.ite s s') := continuous_on_piecewise_ite' (h.mono (inter_subset_left _ _)) (h'.mono (inter_subset_left _ _)) H Heq lemma frontier_inter_open_inter {s t : set α} (ht : is_open t) : frontier (s ∩ t) ∩ t = frontier s ∩ t := by simp only [← subtype.preimage_coe_eq_preimage_coe_iff, ht.is_open_map_subtype_coe.preimage_frontier_eq_frontier_preimage continuous_subtype_coe, subtype.preimage_coe_inter_self] lemma continuous_on_fst {s : set (α × β)} : continuous_on prod.fst s := continuous_fst.continuous_on lemma continuous_within_at_fst {s : set (α × β)} {p : α × β} : continuous_within_at prod.fst s p := continuous_fst.continuous_within_at lemma continuous_on.fst {f : α → β × γ} {s : set α} (hf : continuous_on f s) : continuous_on (λ x, (f x).1) s := continuous_fst.comp_continuous_on hf lemma continuous_within_at.fst {f : α → β × γ} {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).fst) s a := continuous_at_fst.comp_continuous_within_at h lemma continuous_on_snd {s : set (α × β)} : continuous_on prod.snd s := continuous_snd.continuous_on lemma continuous_within_at_snd {s : set (α × β)} {p : α × β} : continuous_within_at prod.snd s p := continuous_snd.continuous_within_at lemma continuous_on.snd {f : α → β × γ} {s : set α} (hf : continuous_on f s) : continuous_on (λ x, (f x).2) s := continuous_snd.comp_continuous_on hf lemma continuous_within_at.snd {f : α → β × γ} {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).snd) s a := continuous_at_snd.comp_continuous_within_at h lemma continuous_within_at_prod_iff {f : α → β × γ} {s : set α} {x : α} : continuous_within_at f s x ↔ continuous_within_at (prod.fst ∘ f) s x ∧ continuous_within_at (prod.snd ∘ f) s x := ⟨λ h, ⟨h.fst, h.snd⟩, by { rintro ⟨h1, h2⟩, convert h1.prod h2, ext, refl, refl }⟩
6b23819c29634db3545c59c9b2f413e7110462d8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/power_series/well_known.lean
12f8be453a4fd37f67bc604b11f89515349b0032
[ "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
4,968
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import ring_theory.power_series.basic import data.nat.parity import algebra.big_operators.nat_antidiagonal /-! # Definition of well-known power series In this file we define the following power series: * `power_series.inv_units_sub`: given `u : Rˣ`, this is the series for `1 / (u - x)`. It is given by `∑ n, x ^ n /ₚ u ^ (n + 1)`. * `power_series.sin`, `power_series.cos`, `power_series.exp` : power series for sin, cosine, and exponential functions. -/ namespace power_series section ring variables {R S : Type*} [ring R] [ring S] /-- The power series for `1 / (u - x)`. -/ def inv_units_sub (u : Rˣ) : power_series R := mk $ λ n, 1 /ₚ u ^ (n + 1) @[simp] lemma coeff_inv_units_sub (u : Rˣ) (n : ℕ) : coeff R n (inv_units_sub u) = 1 /ₚ u ^ (n + 1) := coeff_mk _ _ @[simp] lemma constant_coeff_inv_units_sub (u : Rˣ) : constant_coeff R (inv_units_sub u) = 1 /ₚ u := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_units_sub, zero_add, pow_one] @[simp] lemma inv_units_sub_mul_X (u : Rˣ) : inv_units_sub u * X = inv_units_sub u * C R u - 1 := begin ext (_|n), { simp }, { simp [n.succ_ne_zero, pow_succ] } end @[simp] lemma inv_units_sub_mul_sub (u : Rˣ) : inv_units_sub u * (C R u - X) = 1 := by simp [mul_sub, sub_sub_cancel] lemma map_inv_units_sub (f : R →+* S) (u : Rˣ) : map f (inv_units_sub u) = inv_units_sub (units.map (f : R →* S) u) := by { ext, simp [← map_pow] } end ring section field variables (A A' : Type*) [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A'] open_locale nat /-- Power series for the exponential function at zero. -/ def exp : power_series A := mk $ λ n, algebra_map ℚ A (1 / n!) /-- Power series for the sine function at zero. -/ def sin : power_series A := mk $ λ n, if even n then 0 else algebra_map ℚ A ((-1) ^ (n / 2) / n!) /-- Power series for the cosine function at zero. -/ def cos : power_series A := mk $ λ n, if even n then algebra_map ℚ A ((-1) ^ (n / 2) / n!) else 0 variables {A A'} (n : ℕ) (f : A →+* A') @[simp] lemma coeff_exp : coeff A n (exp A) = algebra_map ℚ A (1 / n!) := coeff_mk _ _ @[simp] lemma constant_coeff_exp : constant_coeff A (exp A) = 1 := by { rw [← coeff_zero_eq_constant_coeff_apply, coeff_exp], simp } @[simp] lemma map_exp : map (f : A →+* A') (exp A) = exp A' := by { ext, simp } @[simp] lemma map_sin : map f (sin A) = sin A' := by { ext, simp [sin, apply_ite f] } @[simp] lemma map_cos : map f (cos A) = cos A' := by { ext, simp [cos, apply_ite f] } end field open ring_hom open finset nat variables {A : Type*} [comm_ring A] /-- Shows that $e^{aX} * e^{bX} = e^{(a + b)X}$ -/ theorem exp_mul_exp_eq_exp_add [algebra ℚ A] (a b : A) : rescale a (exp A) * rescale b (exp A) = rescale (a + b) (exp A) := begin ext, simp only [coeff_mul, exp, rescale, coeff_mk, coe_mk, factorial, nat.sum_antidiagonal_eq_sum_range_succ_mk, add_pow, sum_mul], apply sum_congr rfl, rintros x hx, suffices : a^x * b^(n - x) * (algebra_map ℚ A (1 / ↑(x.factorial)) * algebra_map ℚ A (1 / ↑((n - x).factorial))) = a^x * b^(n - x) * ((↑(n.choose x) * (algebra_map ℚ A) (1 / ↑(n.factorial)))), { convert this using 1; ring }, congr' 1, rw [←map_nat_cast (algebra_map ℚ A) (n.choose x), ←map_mul, ←map_mul], refine ring_hom.congr_arg _ _, rw [mul_one_div ↑(n.choose x) _, one_div_mul_one_div], symmetry, rw [div_eq_iff, div_mul_eq_mul_div, one_mul, choose_eq_factorial_div_factorial], norm_cast, rw cast_dvd_char_zero, { apply factorial_mul_factorial_dvd_factorial (mem_range_succ_iff.1 hx), }, { apply mem_range_succ_iff.1 hx, }, { rintros h, apply factorial_ne_zero n, rw cast_eq_zero.1 h, }, end /-- Shows that $e^{x} * e^{-x} = 1$ -/ theorem exp_mul_exp_neg_eq_one [algebra ℚ A] : exp A * eval_neg_hom (exp A) = 1 := by convert exp_mul_exp_eq_exp_add (1 : A) (-1); simp /-- Shows that $(e^{X})^k = e^{kX}$. -/ theorem exp_pow_eq_rescale_exp [algebra ℚ A] (k : ℕ) : (exp A)^k = rescale (k : A) (exp A) := begin induction k with k h, { simp only [rescale_zero, constant_coeff_exp, function.comp_app, map_one, cast_zero, pow_zero, coe_comp], }, simpa only [succ_eq_add_one, cast_add, ←exp_mul_exp_eq_exp_add (k : A), ←h, cast_one, id_apply, rescale_one] using pow_succ' (exp A) k, end /-- Shows that $\sum_{k = 0}^{n - 1} (e^{X})^k = \sum_{p = 0}^{\infty} \sum_{k = 0}^{n - 1} \frac{k^p}{p!}X^p$. -/ theorem exp_pow_sum [algebra ℚ A] (n : ℕ) : (finset.range n).sum (λ k, (exp A)^k) = power_series.mk (λ p, (finset.range n).sum (λ k, k^p * algebra_map ℚ A p.factorial⁻¹)) := begin simp only [exp_pow_eq_rescale_exp, rescale], ext, simp only [one_div, coeff_mk, coe_mk, coeff_exp, factorial, linear_map.map_sum], end end power_series
09fb749666e91932b06d021d96046405e96f20dc
e8aa886451ad759d8f2621790f1748a9c7d9e820
/src/analysis/analytic/basic.lean
1f1ff736923d8e723524170a7a6cc2f32f52873b
[ "Apache-2.0" ]
permissive
siegelzero/mathlib
04c39faa5d6c1d7799adff1f5cf0710c59def716
64fa9a2062bc18cdfac3b1bf03a1f714cb434f86
refs/heads/master
1,649,847,954,618
1,586,747,318,000
1,586,747,318,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,623
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.times_cont_diff tactic.omega analysis.complex.exponential analysis.specific_limits /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ennreal` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.bound_of_lt_radius`, `p.geometric_bound_of_lt_radius`: relating the value of the radius with the growth of `∥p n∥ * r^n`. * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical open filter /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ pₙ yⁿ` converges for all `∥y∥ < r`. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ennreal := liminf at_top (λ n, 1/((nnnorm (p n)) ^ (1 / (n : ℝ)) : nnreal)) /--If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (p : formal_multilinear_series 𝕜 E F) (C : nnreal) {r : nnreal} (h : ∀ (n : ℕ), nnnorm (p n) * r^n ≤ C) : (r : ennreal) ≤ p.radius := begin have L : tendsto (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) at_top (𝓝 ((r : ennreal) / ((C + 1)^(0 : ℝ) : nnreal))), { apply ennreal.tendsto.div tendsto_const_nhds, { simp }, { rw ennreal.tendsto_coe, apply tendsto_const_nhds.nnrpow (tendsto_const_div_at_top_nhds_0_nat 1), simp }, { simp } }, have A : ∀ n : ℕ , 0 < n → (r : ennreal) ≤ ((C + 1)^(1/(n : ℝ)) : nnreal) * (1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal)), { assume n npos, simp only [one_div_eq_inv, mul_assoc, mul_one, eq.symm ennreal.mul_div_assoc], rw [ennreal.le_div_iff_mul_le _ _, ← nnreal.pow_nat_rpow_nat_inv r npos, ← ennreal.coe_mul, ennreal.coe_le_coe, ← nnreal.mul_rpow, mul_comm], { exact nnreal.rpow_le_rpow (le_trans (h n) (le_add_right (le_refl _))) (by simp) }, { simp }, { simp } }, have B : ∀ᶠ (n : ℕ) in at_top, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal) ≤ 1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal), { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, rw [ennreal.div_le_iff_le_mul, mul_comm], { apply A n hn }, { simp }, { simp } }, have D : liminf at_top (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) ≤ p.radius := liminf_le_liminf B, rw liminf_eq_of_tendsto filter.at_top_ne_bot L at D, simpa using D end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal} (h : (r : ennreal) < p.radius) : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C := begin obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ n, n ≥ N → (r : ennreal) < 1 / ↑(nnnorm (p n) ^ (1 / (n : ℝ))) := eventually.exists_forall_of_at_top (eventually_lt_of_lt_liminf h), obtain ⟨D, hD⟩ : ∃D, ∀ x ∈ (↑((finset.range N.succ).image (λ i, nnnorm (p i) * r^i))), x ≤ D := finset.bdd_above _, refine ⟨max D 1, λ n, _⟩, cases le_or_lt n N with hn hn, { refine le_trans _ (le_max_left D 1), apply hD, have : n ∈ finset.range N.succ := list.mem_range.mpr (nat.lt_succ_iff.mpr hn), exact finset.mem_image_of_mem _ this }, { by_cases hpn : nnnorm (p n) = 0, { simp [hpn] }, have A : nnnorm (p n) ^ (1 / (n : ℝ)) ≠ 0, by simp [nnreal.rpow_eq_zero_iff, hpn], have B : r < (nnnorm (p n) ^ (1 / (n : ℝ)))⁻¹, { have := hN n (le_of_lt hn), rwa [ennreal.div_def, ← ennreal.coe_inv A, one_mul, ennreal.coe_lt_coe] at this }, rw [nnreal.lt_inv_iff_mul_lt A, mul_comm] at B, have : (nnnorm (p n) ^ (1 / (n : ℝ)) * r) ^ n ≤ 1 := pow_le_one n (zero_le (nnnorm (p n) ^ (1 / ↑n) * r)) (le_of_lt B), rw [mul_pow, one_div_eq_inv, nnreal.rpow_nat_inv_pow_nat _ (lt_of_le_of_lt (zero_le _) hn)] at this, exact le_trans this (le_max_right _ _) }, end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially. -/ lemma geometric_bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal} (h : (r : ennreal) < p.radius) : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r^n ≤ C * a^n := begin obtain ⟨t, rt, tp⟩ : ∃ (t : nnreal), (r : ennreal) < t ∧ (t : ennreal) < p.radius := ennreal.lt_iff_exists_nnreal_btwn.1 h, rw ennreal.coe_lt_coe at rt, have tpos : t ≠ 0 := ne_of_gt (lt_of_le_of_lt (zero_le _) rt), obtain ⟨C, hC⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * t^n ≤ C := p.bound_of_lt_radius tp, refine ⟨r / t, C, nnreal.div_lt_one_of_lt rt, λ n, _⟩, calc nnnorm (p n) * r ^ n = (nnnorm (p n) * t ^ n) * (r / t) ^ n : by { field_simp [tpos], ac_refl } ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (zero_le _) end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine le_of_forall_ge_of_dense (λ r hr, _), cases r, { simpa using hr }, obtain ⟨Cp, hCp⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C := p.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_left _ _)), obtain ⟨Cq, hCq⟩ : ∃ (C : nnreal), ∀ n, nnnorm (q n) * r^n ≤ C := q.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_right _ _)), have : ∀ n, nnnorm ((p + q) n) * r^n ≤ Cp + Cq, { assume n, calc nnnorm (p n + q n) * r ^ n ≤ (nnnorm (p n) + nnnorm (q n)) * r ^ n : mul_le_mul_of_nonneg_right (norm_add_le (p n) (q n)) (zero_le (r ^ n)) ... ≤ Cp + Cq : by { rw add_mul, exact add_le_add (hCp n) (hCq n) } }, exact (p + q).le_radius_of_bound _ this end lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [formal_multilinear_series.radius, nnnorm_neg] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := tsum (λn:ℕ, p n (λ(i : fin n), x)) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := (finset.range n).sum (λ k, p k (λ(i : fin k), x)) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := continuous_finset_sum (finset.range n) $ λ k hk, (p k).cont.comp (continuous_pi (λ i, continuous_id)) end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ennreal} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑ pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ennreal) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑ pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases hf with ⟨rf, hrf⟩, rcases hg with ⟨rg, hrg⟩, have P : 0 < min rf rg, by simp [hrf.r_pos, hrg.r_pos], exact ⟨min rf rg, (hrf.mono P (min_le_left _ _)).add (hrg.mono P (min_le_right _ _))⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0), by { ext i, apply fin_zero_elim i }, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := bot_lt_iff_ne_bot.mpr hi, apply continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i), refl }, have A := has_sum_unique (hf.has_sum zero_mem) (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : ∃ (a C : nnreal), a < 1 ∧ (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r' ^n ≤ C * a^n := p.geometric_bound_of_lt_radius (lt_of_lt_of_le h hf.r_le), refine ⟨a, C / (1 - a), ha, λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have : y ∈ emetric.ball (0 : E) r, { rw [emetric.mem_ball, edist_eq_coe_nnnorm], apply lt_trans _ h, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe], exact yr' }, simp only [nnreal.coe_sub (le_of_lt ha), nnreal.coe_sub, nnreal.coe_div, nnreal.coe_one], rw [← dist_eq_norm, dist_comm, dist_eq_norm, ← mul_div_right_comm], apply norm_sub_le_of_geometric_bound_of_has_sum ha _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (finset.univ.prod (λ i : fin n, ∥y∥)) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≤ nnnorm (p n) * r' ^ n : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left (nnreal.coe_nonneg _) (le_of_lt yr') _) (nnreal.coe_nonneg _) ... ≤ C * a ^ n : by exact_mod_cast hC n, end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin rcases hf.uniform_geometric_approx h with ⟨a, C, ha, hC⟩, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 (a.2) ha), rw mul_zero at L, apply ((tendsto_order.1 L).2 ε εpos).mono (λ n hn, _), assume y hy, rw dist_eq_norm, exact lt_of_le_of_lt (hC y hy n) hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := mem_nhds_sets emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { ext z, simp }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := begin apply hf.tendsto_locally_uniformly_on'.continuous_on _ at_top_ne_bot, exact λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on end lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, begin rw zero_add, replace hy : (nnnorm y : ennreal) < p.radius, by { convert hy, exact (edist_eq_coe_nnnorm _).symm }, obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm y)^n ≤ C * a^n := p.geometric_bound_of_lt_radius hy, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric a.2 ha).mul_left _) (λ n, _)).has_sum, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (finset.univ.prod (λ i : fin n, ∥y∥)) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≤ C * a ^ n : by exact_mod_cast hC n end } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := begin have A := h.has_sum hy, have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le), simpa using has_sum_unique A B end /-- The sum of a converging power series is continuous in its disk of convergence. -/ lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin by_cases h : 0 < p.radius, { exact (p.has_fpower_series_on_ball h).continuous_on }, { simp at h, simp [h, continuous_on_empty] } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \choose n k p_n y^{n-k} z^k = \sum_{k} (\sum_{n} \choose n k p_n y^{n-k}) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to `\sum_{n} \choose n k p_n y^{n-k}`. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r : nnreal} /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda, as this leads to a bad definition with auxiliary `_match` statements, but we will try to use pattern matching in lambdas as much as possible in the proofs below to increase readability. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, tsum (λi, (p i.1).restr i.2.1 i.2.2 x : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, first version. -/ -- Note here and below it is necessary to use `@` and provide implicit arguments using `_`, -- so that it is possible to use pattern matching in the lambda. -- Overall this seems a good trade-off in readability. lemma change_origin_summable_aux1 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) := begin obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm x + r) ^ n ≤ C * a^n := p.geometric_bound_of_lt_radius h, let Bnnnorm : (Σ (n : ℕ), finset (fin n)) → nnreal := λ ⟨n, s⟩, nnnorm (p n) * (nnnorm x) ^ (n - s.card) * r ^ s.card, have : ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) = (λ b, (Bnnnorm b : ℝ)), by { ext b, rcases b with ⟨n, s⟩, simp [Bnnnorm, nnreal.coe_pow, coe_nnnorm] }, rw [this, nnreal.summable_coe, ← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (∑ b, ↑(Bnnnorm b)) = (∑ n, (∑ s, ↑(Bnnnorm ⟨n, s⟩))) : by exact ennreal.tsum_sigma' _ ... ≤ (∑ n, (((nnnorm (p n) * (nnnorm x + r)^n) : nnreal) : ennreal)) : begin refine ennreal.tsum_le_tsum (λ n, _), rw [tsum_fintype, ← ennreal.coe_finset_sum, ennreal.coe_le_coe], apply le_of_eq, calc finset.univ.sum (λ (s : finset (fin n)), Bnnnorm ⟨n, s⟩) = finset.univ.sum (λ (s : finset (fin n)), nnnorm (p n) * ((nnnorm x) ^ (n - s.card) * r ^ s.card)) : by simp [← mul_assoc] ... = nnnorm (p n) * (nnnorm x + r) ^ n : by { rw [add_comm, ← finset.mul_sum, ← fin.sum_pow_mul_eq_add_pow], congr, ext s, ring } end ... ≤ (∑ (n : ℕ), (C * a ^ n : ennreal)) : tsum_le_tsum (λ n, by exact_mod_cast hC n) ennreal.summable ennreal.summable ... < ⊤ : by simp [ennreal.mul_eq_top, ha, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.lt_top_iff_ne_top] end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, second version. -/ lemma change_origin_summable_aux2 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * ↑r ^ k) : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin let γ : ℕ → Type* := λ k, (Σ (n : ℕ), {s : finset (fin n) // s.card = k}), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h, let Anorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥(p n).restr s rfl x∥ * r ^ s.card, have SAnorm : summable Anorm, { refine summable_of_norm_bounded _ SBnorm (λ i, _), rcases i with ⟨n, s⟩, suffices H : ∥(p n).restr s rfl x∥ * (r : ℝ) ^ s.card ≤ (∥p n∥ * ∥x∥ ^ (n - finset.card s) * r ^ s.card), { have : ∥(r: ℝ)∥ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)], simpa [Anorm, Bnorm, this] using H }, exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x) (pow_nonneg (nnreal.coe_nonneg _) _) }, let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, rw ← e.summable_iff, convert SAnorm, ext i, rcases i with ⟨n, s⟩, refl end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, third version. -/ lemma change_origin_summable_aux3 (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) : @summable ℝ _ _ _ (λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin obtain ⟨r, rpos, hr⟩ : ∃ (r : nnreal), 0 < r ∧ ((nnnorm x + r) : ennreal) < p.radius := ennreal.lt_iff_exists_add_pos_lt.mp h, have S : @summable ℝ _ _ _ ((λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ), { let j : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩, have j_inj : function.injective j, by tidy, convert summable.summable_comp_of_injective (p.change_origin_summable_aux2 hr) j_inj, tidy }, have : (r : ℝ)^k ≠ 0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos], apply (summable_mul_right_iff this).2, convert S, tidy end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - nnnorm x ≤ (p.change_origin x).radius := begin by_cases h : p.radius ≤ nnnorm x, { have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h, rw this, exact zero_le _ }, replace h : (nnnorm x : ennreal) < p.radius, by simpa using h, refine le_of_forall_ge_of_dense (λ r hr, _), cases r, { simpa using hr }, rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ := λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, have SA : summable A := p.change_origin_summable_aux2 hr, have A_nonneg : ∀ i, 0 ≤ A i, { rintros ⟨k, n, s, hs⟩, change 0 ≤ ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, refine mul_nonneg' (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) }, have tsum_nonneg : 0 ≤ tsum A := tsum_nonneg A_nonneg, apply le_radius_of_bound _ (nnreal.of_real (tsum A)) (λ k, _), rw [← nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_pow, coe_nnnorm, nnreal.coe_of_real _ tsum_nonneg], let j : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩, have j_inj : function.injective j, by tidy, calc ∥change_origin p x k∥ * ↑r ^ k = ∥@tsum (E [×k]→L[𝕜] F) _ _ _ (λ i, (p i.1).restr i.2.1 i.2.2 x : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F))∥ * ↑r ^ k : rfl ... ≤ tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) * ↑r ^ k : begin apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _), apply norm_tsum_le_tsum_norm, convert p.change_origin_summable_aux3 k h, ext a, tidy end ... = tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ * ↑r ^ k : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) : by { rw tsum_mul_right, convert p.change_origin_summable_aux3 k h, tidy } ... = tsum (A ∘ j) : by { congr, tidy } ... ≤ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg j_inj end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variable [complete_space F] /-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/ lemma change_origin_has_sum (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) : @has_sum (E [×k]→L[𝕜] F) _ _ _ ((λ i, (p i.1).restr i.2.1 i.2.2 x) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) (p.change_origin x k) := begin apply summable.has_sum, apply summable_of_summable_norm, convert p.change_origin_summable_aux3 k h, tidy end /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (nnnorm x + nnnorm y : ennreal) < p.radius) : has_sum ((λk:ℕ, p.change_origin x k (λ (i : fin k), y))) (p.sum (x + y)) := begin /- The series on the left is a series of series. If we order the terms differently, we get back to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below, the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a series of terms `B`, and we show that they correspond to each other by reordering to conclude the proof. -/ have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, -- `A` is the terms of the series whose sum gives the series for `p.change_origin` let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // s.card = k}) → F := λ ⟨k, n, s, hs⟩, (p n).restr s hs x (λ(i : fin k), y), -- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity. let B : (Σ (n : ℕ), finset (fin n)) → F := λ ⟨n, s⟩, (p n).restr s rfl x (λ (i : fin s.card), y), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * ∥y∥ ^ s.card, have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h, have SB : summable B, { refine summable_of_norm_bounded _ SBnorm _, rintros ⟨n, s⟩, calc ∥(p n).restr s rfl x (λ (i : fin s.card), y)∥ ≤ ∥(p n).restr s rfl x∥ * ∥y∥ ^ s.card : begin convert ((p n).restr s rfl x).le_op_norm (λ (i : fin s.card), y), simp [(finset.prod_const (∥y∥))], end ... ≤ (∥p n∥ * ∥x∥ ^ (n - s.card)) * ∥y∥ ^ s.card : mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) }, -- Check that indeed the sum of `B` is `p (x + y)`. have has_sum_B : has_sum B (p.sum (x + y)), { have K1 : ∀ n, has_sum (λ (s : finset (fin n)), B ⟨n, s⟩) (p n (λ (i : fin n), x + y)), { assume n, have : (p n) (λ (i : fin n), y + x) = finset.univ.sum (λ (s : finset (fin n)), p n (finset.piecewise s (λ (i : fin n), y) (λ (i : fin n), x))) := (p n).map_add_univ (λ i, y) (λ i, x), simp [add_comm y x] at this, rw this, exact has_sum_fintype _ }, have K2 : has_sum (λ (n : ℕ), (p n) (λ (i : fin n), x + y)) (p.sum (x + y)), { have : x + y ∈ emetric.ball (0 : E) p.radius, { apply lt_of_le_of_lt _ h, rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le x y }, simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this }, exact has_sum.sigma_of_has_sum K2 K1 SB }, -- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to -- reordering have has_sum_A : has_sum A (p.sum (x + y)), { let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, have : A ∘ e = B, by { ext x, cases x, refl }, rw ← e.has_sum_iff, convert has_sum_B }, -- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series -- defining `p.change_origin`, by definition have J : ∀k, has_sum (λ c, A ⟨k, c⟩) (p.change_origin x k (λ(i : fin k), y)), { assume k, have : (nnnorm x : ennreal) < radius p := lt_of_le_of_lt (le_add_right (le_refl _)) h, convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this) (λ(i : fin k), y), ext i, tidy }, exact has_sum_A.sigma J end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ennreal} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ennreal) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := begin assume z hz, have A : (nnnorm y : ennreal) + nnnorm z < r, { have : edist z 0 < r - ↑(nnnorm y) := hz, rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this }, convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le), have : y + z ∈ emetric.ball (0 : E) r := calc edist (y + z) 0 ≤ ↑(nnnorm y) + ↑(nnnorm z) : by { rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le y z } ... < r : A, simpa using hf.sum this end } lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (nnnorm (y - x) : ennreal) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_forall_mem_open, assume x hx, rcases hx with ⟨p, r, hr⟩, refine ⟨emetric.ball x r, λ y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩, simp only [edist_self, emetric.mem_ball, hr.r_pos] end variables {𝕜 f} end
9a282832a843ec664317fe4adb138216816216ff
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/semigroup.lean
6a4a57e05d025e737fdb4cc78f11c75fe26a6340
[ "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,878
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import topology.separation /-! # Idempotents in topological semigroups This file provides a sufficient condition for a semigroup `M` to contain an idempotent (i.e. an element `m` such that `m * m = m `), namely that `M` is a nonempty compact Hausdorff space where right-multiplication by constants is continuous. We also state a corresponding lemma guaranteeing that a subset of `M` contains an idempotent. -/ /-- Any nonempty compact Hausdorff semigroup where right-multiplication is continuous contains an idempotent, i.e. an `m` such that `m * m = m`. -/ @[to_additive "Any nonempty compact Hausdorff additive semigroup where right-addition is continuous contains an idempotent, i.e. an `m` such that `m + m = m`"] lemma exists_idempotent_of_compact_t2_of_continuous_mul_left {M} [nonempty M] [semigroup M] [topological_space M] [compact_space M] [t2_space M] (continuous_mul_left : ∀ r : M, continuous (* r)) : ∃ m : M, m * m = m := begin /- We apply Zorn's lemma to the poset of nonempty closed subsemigroups of `M`. It will turn out that any minimal element is `{m}` for an idempotent `m : M`. -/ let S : set (set M) := { N : set M | is_closed N ∧ N.nonempty ∧ ∀ m m' ∈ N, m * m' ∈ N }, suffices : ∃ N ∈ S, ∀ N' ∈ S, N' ⊆ N → N' = N, { rcases this with ⟨N, ⟨N_closed, ⟨m, hm⟩, N_mul⟩, N_minimal⟩, use m, /- We now have an element `m : M` of a minimal subsemigroup `N`, and want to show `m + m = m`. We first show that every element of `N` is of the form `m' + m`.-/ have scaling_eq_self : (* m) '' N = N, { apply N_minimal, { refine ⟨(continuous_mul_left m).is_closed_map _ N_closed, ⟨_, ⟨m, hm, rfl⟩⟩, _⟩, rintros _ ⟨m'', hm'', rfl⟩ _ ⟨m', hm', rfl⟩, refine ⟨m'' * m * m', N_mul _ (N_mul _ hm'' _ hm) _ hm', mul_assoc _ _ _⟩, }, { rintros _ ⟨m', hm', rfl⟩, exact N_mul _ hm' _ hm, }, }, /- In particular, this means that `m' * m = m` for some `m'`. We now use minimality again to show that this holds for _all_ `m' ∈ N`. -/ have absorbing_eq_self : N ∩ { m' | m' * m = m} = N, { apply N_minimal, { refine ⟨N_closed.inter ((t1_space.t1 m).preimage (continuous_mul_left m)), _, _⟩, { rw ←scaling_eq_self at hm, exact hm }, { rintros m'' ⟨mem'', eq'' : _ = m⟩ m' ⟨mem', eq' : _ = m⟩, refine ⟨N_mul _ mem'' _ mem', _⟩, rw [set.mem_set_of_eq, mul_assoc, eq', eq''], }, }, apply set.inter_subset_left, }, /- Thus `m * m = m` as desired. -/ rw ←absorbing_eq_self at hm, exact hm.2, }, apply zorn_superset, intros c hcs hc, refine ⟨⋂₀ c, ⟨is_closed_sInter $ λ t ht, (hcs ht).1, _, _⟩, _⟩, { obtain rfl | hcnemp := c.eq_empty_or_nonempty, { rw set.sInter_empty, apply set.univ_nonempty, }, convert @is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ _ _ (c.nonempty_coe_sort.mpr hcnemp) (coe : c → set M) _ _ _ _, { simp only [subtype.range_coe_subtype, set.set_of_mem_eq] } , { refine directed_on.directed_coe (is_chain.directed_on hc.symm) }, { intro i, exact (hcs i.property).2.1, }, { intro i, exact (hcs i.property).1.is_compact, }, { intro i, exact (hcs i.property).1, }, }, { intros m hm m' hm', rw set.mem_sInter, intros t ht, exact (hcs ht).2.2 m (set.mem_sInter.mp hm t ht) m' (set.mem_sInter.mp hm' t ht) }, { intros s hs, exact set.sInter_subset_of_mem hs, }, end /-- A version of `exists_idempotent_of_compact_t2_of_continuous_mul_left` where the idempotent lies in some specified nonempty compact subsemigroup. -/ @[to_additive exists_idempotent_in_compact_add_subsemigroup "A version of `exists_idempotent_of_compact_t2_of_continuous_add_left` where the idempotent lies in some specified nonempty compact additive subsemigroup."] lemma exists_idempotent_in_compact_subsemigroup {M} [semigroup M] [topological_space M] [t2_space M] (continuous_mul_left : ∀ r : M, continuous (* r)) (s : set M) (snemp : s.nonempty) (s_compact : is_compact s) (s_add : ∀ x y ∈ s, x * y ∈ s) : ∃ m ∈ s, m * m = m := begin let M' := { m // m ∈ s }, letI : semigroup M' := { mul := λ p q, ⟨p.1 * q.1, s_add _ p.2 _ q.2⟩, mul_assoc := λ p q r, subtype.eq (mul_assoc _ _ _) }, haveI : compact_space M' := is_compact_iff_compact_space.mp s_compact, haveI : nonempty M' := nonempty_subtype.mpr snemp, have : ∀ p : M', continuous (* p) := λ p, continuous_subtype_mk _ ((continuous_mul_left p.1).comp continuous_subtype_val), obtain ⟨⟨m, hm⟩, idem⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left this, exact ⟨m, hm, subtype.ext_iff.mp idem⟩, end
14688e2379e78357d73d5333f1b1ff77b2248fe5
46125763b4dbf50619e8846a1371029346f4c3db
/src/ring_theory/polynomial.lean
3141ff049540a5b10dfbb60ec3a23a4ef097fb8d
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
17,223
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Ring-theoretic supplement of data.polynomial. Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. -/ import data.equiv.fin data.polynomial data.mv_polynomial import ring_theory.subring import ring_theory.ideals ring_theory.noetherian noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v w namespace polynomial variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum, submodule.mem_coe], refine submodule.sum_mem _ (λ k hk, _), have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem _ else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [comm_ring S] {f : R → S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f ∘ subtype.val) x p.restriction := rfl section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem _ else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans (finset.coe_subset.2 finsupp.frange_single) (set.singleton_subset_iff.2 (is_submonoid.one_mem _))) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefificents are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ⟨p.support, subtype.val ∘ p.to_fun, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩ @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2 end polynomial variables {R : Type u} {σ : Type v} [comm_ring R] namespace ideal open polynomial /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero := I.zero_mem, add := λ _ _, I.add_mem, smul := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, lattice.bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add' (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add' hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, { exact ⟨0⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := ⟨assume I : ideal (polynomial R), let L := I.leading_coeff in let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, letI : nonzero_comm_ring R := { zero_ne_one := this, ..(infer_instance : comm_ring R) }, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul_eq', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans (mv_polynomial.ring_equiv_of_equiv _ fin_zero_equiv'.symm)) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxilliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n) lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (ring_equiv_of_equiv R e) /-- Auxilliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : p.rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) * q.rename (subtype.map id (finset.subset_union_right s t)) = 0, { apply injective_rename _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, zero_ne_one := begin intro H, have : eval₂ id (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ id (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } end mv_polynomial
99e0ea4ad2de264c5e5323e2574118e06f718235
fe84e287c662151bb313504482b218a503b972f3
/src/combinatorics/choose.lean
ef1b952fee5696704d6d2179a16353661533c3c0
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
11,353
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file is about ordered subsets of a finite type, i.e. lists of distinct elements. It probably has some overlap with Mario's recent mathlib additions on lists of sublists etc. -/ import data.nat.choose data.fintype.basic import tactic.squeeze import combinatorics.erase combinatorics.falling combinatorics.qualify open nat namespace combinatorics variables (α : Type*) [fintype α] [decidable_eq α] /- @latex: defn-F -/ def ordered_subset (k : ℕ) := { s : list α // s.length = k ∧ s.nodup } namespace ordered_subset instance (k : ℕ) : has_mem α (ordered_subset α k) := ⟨λ (a : α) (s : ordered_subset α k), list.mem a s.val⟩ instance (k : ℕ) : decidable_eq (ordered_subset α k) := by {apply_instance} variable {α} @[ext] lemma ext {k : ℕ} {s₁ s₂ : ordered_subset α k} : s₁ = s₂ ↔ s₁.val = s₂.val := begin split; intro e,rw[e],exact subtype.eq e, end section map /- ordered_subset α k is covariantly functorial for injective functions of α. -/ variables {β : Type*} [fintype β] [decidable_eq β] variables {γ : Type*} [fintype γ] [decidable_eq γ] variables {f : α → β} (f_inj : function.injective f) variables {g : β → γ} (g_inj : function.injective g) def map {k : ℕ} : ∀ (s : ordered_subset α k), ordered_subset β k | ⟨s,⟨s_len,s_nodup⟩⟩ := ⟨s.map f,⟨(list.length_map f s).trans s_len,list.nodup.map f_inj s_nodup⟩⟩ @[simp] lemma map_id {k : ℕ} : ∀ s : ordered_subset α k, map function.injective_id s = s | ⟨s,⟨s_len,s_nodup⟩⟩ := by {apply subtype.eq,exact list.map_id s} lemma map_map {k : ℕ} : ∀ s : ordered_subset α k, map (function.injective.comp g_inj f_inj) s = map g_inj (map f_inj s) | ⟨s,⟨s_len,s_nodup⟩⟩ := by { apply subtype.eq,exact (list.map_map g f s).symm } lemma mem_map {k : ℕ} (b : β) : ∀ (s : ordered_subset α k), b ∈ (map f_inj s) ↔ ∃ a, a ∈ s ∧ f a = b | ⟨s,⟨s_len,s_nodup⟩⟩ := begin split,{intro b_in_fs,exact (@list.mem_map _ _ f b s).mp b_in_fs,}, {intro ex_a,exact (@list.mem_map _ _ f b s).mpr ex_a,} end lemma list.map_inj {f : α → β} (f_inj : function.injective f) : function.injective (list.map f) | [] [] e := rfl | [] (a2 :: l2) e := false.elim (list.no_confusion e) | (a1 :: l1) [] e := false.elim (list.no_confusion e) | (a1 :: l1) (a2 :: l2) e := begin rw[list.map,list.map] at e, injection e with e_head e_tail, congr,exact f_inj e_head,exact list.map_inj e_tail, end lemma map_inj (k : ℕ) : function.injective (@map α _ _ β _ _ f f_inj k) | ⟨s1,⟨s1_len,s1_nodup⟩⟩ ⟨s2,⟨s2_len,s2_nodup⟩⟩ e := begin apply subtype.eq, change s1 = s2, rw[ext] at e, change s1.map f = s2.map f at e, exact list.map_inj f_inj e, end end map def nil : ordered_subset α 0 := ⟨list.nil,⟨rfl,list.nodup_nil⟩⟩ lemma eq_nil : ∀ s : ordered_subset α 0, s = nil | ⟨s,⟨s_len,s_nodup⟩⟩ := subtype.eq $ list.eq_nil_of_length_eq_zero s_len variable {α} def cons : ∀ (a : α) {n : ℕ} (s : ordered_subset α n) (h : ¬ (a ∈ s)), ordered_subset α (n + 1) | a _ ⟨s,⟨s_len,s_nodup⟩⟩ h := ⟨list.cons a s,⟨by {rw[← s_len],refl},list.nodup_cons.mpr ⟨h,s_nodup⟩⟩⟩ @[simp] lemma val_cons : ∀ (a : α) {n : ℕ} (s : ordered_subset α n) (h : ¬ (a ∈ s)), (cons a s h).val = a :: s.val | a _ ⟨s,⟨s_len,s_nodup⟩⟩ h := rfl def head : ∀ {n : ℕ} (s : ordered_subset α (n + 1)), α | _ ⟨list.cons a t,⟨s_len,s_nodup⟩⟩ := a | n ⟨list.nil,⟨s_len,s_nodup⟩⟩ := false.elim (succ_ne_zero n s_len.symm) def tail : ∀ {n : ℕ} (s : ordered_subset α (n + 1)), ordered_subset α n | _ ⟨list.cons a t,⟨s_len,s_nodup⟩⟩ := ⟨t,⟨nat.succ_inj'.mp s_len,(list.nodup_cons.mp s_nodup).right⟩⟩ | n ⟨list.nil,⟨s_len,s_nodup⟩⟩ := false.elim (succ_ne_zero n s_len.symm) @[simp] lemma val_tail : ∀ {n : ℕ} (s : ordered_subset α (n + 1)), s.tail.val = s.val.tail | _ ⟨list.cons a t,⟨s_len,s_nodup⟩⟩ := rfl | n ⟨list.nil,⟨s_len,s_nodup⟩⟩ := false.elim (succ_ne_zero n s_len.symm) @[simp] lemma head_cons : ∀ {n : ℕ} (a : α) (s : ordered_subset α n) (h : a ∉ s), head (cons a s h) = a | n a ⟨s,⟨s_len,s_nodup⟩⟩ h := rfl @[simp] lemma tail_cons : ∀ {n : ℕ} (a : α) (s : ordered_subset α n) (h : a ∉ s), tail (cons a s h) = s | n a ⟨s,⟨s_len,s_nodup⟩⟩ h := by { apply subtype.eq,refl } lemma head_not_in_tail : ∀ {n : ℕ} (s : ordered_subset α (n + 1)), s.head ∉ s.tail | _ ⟨list.cons a t,⟨s_len,s_nodup⟩⟩ := (list.nodup_cons.mp s_nodup).left | n ⟨list.nil,⟨s_len,s_nodup⟩⟩ := false.elim (succ_ne_zero n s_len.symm) lemma head_not_in_tail' {n : ℕ} {s : ordered_subset α (n + 1)} {a : α} (e : s.head = a) (b : α) : b ∈ s.tail → b ≠ a := λ b_in_t b_eq_a, s.head_not_in_tail ((b_eq_a.trans e.symm) ▸ b_in_t) lemma eq_cons : ∀ {n : ℕ} (s : ordered_subset α (n + 1)), s = cons s.head s.tail s.head_not_in_tail | _ ⟨list.cons a t,⟨s_len,s_nodup⟩⟩ := by {apply subtype.eq,refl} | n ⟨list.nil,⟨s_len,s_nodup⟩⟩ := false.elim (succ_ne_zero n s_len.symm) def qualify {u : α → Prop} [decidable_pred u] {n : ℕ} : ∀ (s : ordered_subset α n) (h : ∀ {a}, a ∈ s → u a), ordered_subset {a // u a} n | ⟨s,⟨s_len,s_nodup⟩⟩ h := ⟨list.qualify s @h,⟨(list.length_qualify s @h).trans s_len, (list.nodup_qualify s @h).mpr s_nodup⟩⟩ @[simp] lemma val_qualify {u : α → Prop} [decidable_pred u] {n : ℕ} : ∀ (s : ordered_subset α n) (h : ∀ {a}, a ∈ s → u a), (qualify s @h).val = list.qualify s.val @h | ⟨s,⟨s_len,s_nodup⟩⟩ h := rfl def unqualify {u : set α} [decidable_pred (∈ u)] {n : ℕ} : ∀ (s : ordered_subset u n), ordered_subset α n | ⟨s,⟨s_len,s_nodup⟩⟩ := ⟨list.unqualify s,⟨(list.length_unqualify s).trans s_len, list.nodup_unqualify.mpr s_nodup⟩⟩ @[simp] lemma val_unqualify {u : set α} [decidable_pred (∈ u)] {n : ℕ} : ∀ (s : ordered_subset u n), (unqualify s).val = list.unqualify s.val | ⟨s,⟨s_len,s_nodup⟩⟩ := rfl lemma unqualify_eq {u : set α} [decidable_pred (∈ u)] {n : ℕ} {s₁ s₂ : ordered_subset u n} : s₁ = s₂ ↔ (unqualify s₁) = (unqualify s₂) := begin rw[ext,ext,val_unqualify,val_unqualify], exact list.unqualify_eq, end lemma mem_unqualify {u : set α} [decidable_pred (∈ u)] {n : ℕ} : ∀ (s : ordered_subset u n) (a : α), a ∈ (unqualify s) ↔ ∃ h : u a, subtype.mk a h ∈ s | ⟨s,⟨s_len,s_nodup⟩⟩ a := @list.mem_unqualify α u s a lemma mem_unqualify' {u : set α} [decidable_pred (∈ u)] {n : ℕ} : ∀ (s : ordered_subset u n) (a : u), a.val ∈ (unqualify s) ↔ a ∈ s | ⟨s,⟨s_len,s_nodup⟩⟩ a := @list.mem_unqualify' α u s a @[simp] lemma un_qualify {u : set α} [decidable_pred (∈ u)] {n : ℕ} : ∀ (s : ordered_subset α n) (h : ∀ {a}, a ∈ s → u a), unqualify (qualify s @h) = s | ⟨s,⟨s_len,s_nodup⟩⟩ h := begin rw[qualify,unqualify], {apply subtype.eq,simp only [],rw[list.un_qualify],}, {exact (list.length_qualify s @h).trans s_len,}, {exact (list.nodup_qualify s @h).mpr s_nodup,} end def cons' (a : α) {n : ℕ} (s : ordered_subset (erase a) n) : ordered_subset α n.succ := cons a s.unqualify begin -- Need to supply proof that a ∉ s.unqualify intro a_in_s, cases (mem_unqualify s a).mp a_in_s with h, exact h rfl, end variables P Q : Prop def tail' {n : ℕ} (s : ordered_subset α n.succ) {a : α} (e : s.head = a) : ordered_subset (erase a) n := (qualify s.tail) (head_not_in_tail' e) @[simp] lemma unqualify_tail {n : ℕ} (s : ordered_subset α n.succ) {a : α} (e : s.head = a) : unqualify (tail' s e) = s.tail := un_qualify s.tail _ @[simp] lemma head_cons' (a : α) {n : ℕ} (s : ordered_subset (erase a) n) : head (cons' a s) = a := head_cons a s.unqualify _ @[simp] lemma tail_cons' (a : α) {n : ℕ} (s : ordered_subset (erase a) n) (e : head(cons' a s) = a) : tail' (cons' a s) e = s := begin apply unqualify_eq.mpr,rw[unqualify_tail,cons',tail_cons], end lemma eq_cons' {n : ℕ} (s : ordered_subset α n.succ) {a : α} (e : s.head = a) : s = cons' a (tail' s e) := begin apply ext.mpr,rw[cons',val_cons,val_unqualify,tail',val_qualify], rw[list.un_qualify,val_tail], rcases s with ⟨s_val,⟨s_len,s_nodup⟩⟩, rcases s_val with _ | ⟨a0,t⟩, {exact false.elim (succ_ne_zero _ s_len.symm)}, replace e : a0 = a := e, simp only [e],split; refl, end lemma sigma_eq {k : ℕ} : ∀ {x₁ x₂ : (Σ a : α, ordered_subset (erase a) k)}, x₁ = x₂ ↔ x₁.1 = x₂.1 ∧ unqualify x₁.2 = unqualify x₂.2 | ⟨a₁,t₁⟩ ⟨a₂,t₂⟩ := begin split, {intro e,rw[e],split;refl}, {rintro ⟨ea,et⟩,replace ea : a₁ = a₂ := ea, rcases ea with rfl,congr,exact unqualify_eq.mpr et, } end def base_equiv : unit ≃ ordered_subset α 0 := { to_fun := λ _,nil, inv_fun := λ _,unit.star, left_inv := λ s,by { cases s,refl}, right_inv := λ s, (eq_nil s).symm, } def sigma_equiv (k : ℕ) : (Σ a : α, ordered_subset (erase a) k) ≃ (ordered_subset α k.succ) := { to_fun := λ x,cons' x.1 x.2, inv_fun := λ s,⟨s.head,tail' s rfl⟩, right_inv := λ s,(eq_cons' s rfl).symm, left_inv := λ x,begin rcases x with ⟨a,t⟩, apply sigma_eq.mpr,split,simp only[head_cons'], simp only[tail',unqualify_tail,un_qualify,cons',tail_cons], end } instance (n : ℕ) : fintype (ordered_subset α n) := begin tactic.unfreeze_local_instances, induction n with n ih generalizing α, {exact fintype.of_equiv unit base_equiv}, {exact fintype.of_equiv _ (sigma_equiv n)} end #check finset.sum_const lemma card (n m : ℕ) (e : fintype.card α = m) : fintype.card (ordered_subset α n) = falling m n := begin tactic.unfreeze_local_instances, induction n with n ih generalizing α m e, {exact ((fintype.card_congr base_equiv).symm.trans fintype.card_unit).trans (falling_zero m).symm, }, {rcases m with _ | m, {rw[falling_zero_succ], rw[fintype.card_eq_zero_iff,is_empty_iff] at e ⊢, intro s, exact e s.head },{ rw[falling_succ], let h0 := (fintype.card_congr (sigma_equiv n)).symm.trans (fintype.card_sigma (λ a : α, ordered_subset (erase a) n)), have h1 : ∀ (a : α), fintype.card (erase a) = m := λ a, nat.succ_inj'.mp ((erase.card a).trans e), have h2 : ∀ (a : α), fintype.card (ordered_subset (erase a) n) = falling m n := λ (a : α), ih m (h1 a), let c0 : α → ℕ := λ a, fintype.card (ordered_subset (erase a) n), let c1 : α → ℕ := λ a, falling m n, have h3 : finset.univ.sum c0 = finset.univ.sum c1 := finset.sum_congr rfl (λ a _, h2 a), have : finset.univ.sum c1 = _ := finset.sum_const (falling m n), let h4 : finset.univ.sum c1 = m.succ * (falling m n) := begin change finset.univ.card = m + 1 at e, rw[finset.sum_const (falling m n),e],refl end, exact h0.trans (h3.trans h4), } } end end ordered_subset end combinatorics
3a68f90c0bde58f122fe4db5bf94b4fc0935ca08
1446f520c1db37e157b631385707cc28a17a595e
/tests/bench/unionfind.lean
8ce07c866a07e499f413ee3a60ad6d2a592ae729
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,363
lean
def StateT' (m : Type → Type) (σ : Type) (α : Type) := σ → m (α × σ) namespace StateT' variables {m : Type → Type} [Monad m] {σ : Type} {α β : Type} @[inline] protected def pure (a : α) : StateT' m σ α := fun s => pure (a, s) @[inline] protected def bind (x : StateT' m σ α) (f : α → StateT' m σ β) : StateT' m σ β := fun s => do (a, s') ← x s; f a s' @[inline] def read : StateT' m σ σ := fun s => pure (s, s) @[inline] def write (s' : σ) : StateT' m σ Unit := fun s => pure ((), s') @[inline] def updt (f : σ → σ) : StateT' m σ Unit := fun s => pure ((), f s) instance : Monad (StateT' m σ) := {pure := @StateT'.pure _ _ _, bind := @StateT'.bind _ _ _} end StateT' def ExceptT' (m : Type → Type) (ε : Type) (α : Type) := m (Except ε α) namespace ExceptT' variables {m : Type → Type} [Monad m] {ε : Type} {α β : Type} @[inline] protected def pure (a : α) : ExceptT' m ε α := (pure (Except.ok a) : m (Except ε α)) @[inline] protected def bind (x : ExceptT' m ε α) (f : α → ExceptT' m ε β) : ExceptT' m ε β := (do { v ← x; match v with | Except.error e => pure (Except.error e) | Except.ok a => f a } : m (Except ε β)) @[inline] def error (e : ε) : ExceptT' m ε α := (pure (Except.error e) : m (Except ε α)) @[inline] def lift (x : m α) : ExceptT' m ε α := (do {a ← x; pure (Except.ok a) } : m (Except ε α)) instance : Monad (ExceptT' m ε) := {pure := @ExceptT'.pure _ _ _, bind := @ExceptT'.bind _ _ _} end ExceptT' abbrev Node := Nat structure nodeData := (find : Node) (rank : Nat := 0) abbrev ufData := Array nodeData abbrev M (α : Type) := ExceptT' (StateT' Id ufData) String α @[inline] def read : M ufData := ExceptT'.lift StateT'.read @[inline] def write (s : ufData) : M Unit := ExceptT'.lift (StateT'.write s) @[inline] def updt (f : ufData → ufData) : M Unit := ExceptT'.lift (StateT'.updt f) @[inline] def error {α : Type} (e : String) : M α := ExceptT'.error e def run {α : Type} (x : M α) (s : ufData := ∅) : Except String α × ufData := x s def capacity : M Nat := do d ← read; pure d.size def findEntryAux : Nat → Node → M nodeData | 0, n => error "out of fuel" | i+1, n => do s ← read; if h : n < s.size then do { let e := s.get ⟨n, h⟩; if e.find = n then pure e else do e₁ ← findEntryAux i e.find; updt (fun s => s.set! n e₁); pure e₁ } else error "invalid Node" def findEntry (n : Node) : M nodeData := do c ← capacity; findEntryAux c n def find (n : Node) : M Node := do e ← findEntry n; pure e.find def mk : M Node := do n ← capacity; updt $ fun s => s.push {find := n, rank := 1}; pure n def union (n₁ n₂ : Node) : M Unit := do r₁ ← findEntry n₁; r₂ ← findEntry n₂; if r₁.find = r₂.find then pure () else updt $ fun s => if r₁.rank < r₂.rank then s.set! r₁.find { find := r₂.find } else if r₁.rank = r₂.rank then let s₁ := s.set! r₁.find { find := r₂.find }; s₁.set! r₂.find { rank := r₂.rank + 1, .. r₂} else s.set! r₂.find { find := r₁.find } def mkNodes : Nat → M Unit | 0 => pure () | n+1 => mk *> mkNodes n def checkEq (n₁ n₂ : Node) : M Unit := do r₁ ← find n₁; r₂ ← find n₂; unless (r₁ = r₂) $ error "nodes are not equal" def mergePackAux : Nat → Nat → Nat → M Unit | 0, _, _ => pure () | i+1, n, d => do c ← capacity; if (n+d) < c then union n (n+d) *> mergePackAux i (n+1) d else pure () def mergePack (d : Nat) : M Unit := do c ← capacity; mergePackAux c 0 d def numEqsAux : Nat → Node → Nat → M Nat | 0, _, r => pure r | i+1, n, r => do c ← capacity; if n < c then do { n₁ ← find n; numEqsAux i (n+1) (if n = n₁ then r else r+1) } else pure r def numEqs : M Nat := do c ← capacity; numEqsAux c 0 0 def test (n : Nat) : M Nat := if n < 2 then error "input must be greater than 1" else do mkNodes n; mergePack 50000; mergePack 10000; mergePack 5000; mergePack 1000; numEqs def main (xs : List String) : IO UInt32 := let n := xs.head!.toNat; match run (test n) with | (Except.ok v, s) => IO.println ("ok " ++ toString v) *> pure 0 | (Except.error e, s) => IO.println ("Error : " ++ e) *> pure 1
72cf652839803792fcd3289e32e8ed19fdf17d9e
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/theories/set_theory.lean
57f079d51fca24668e2062b6eb3b10f1a650828c
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
27,732
lean
import data.set.basic universes u v def arity (α : Type u) : nat → Type u | 0 := α | (n+1) := α → arity n inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet def type : pSet → Type u | ⟨α, A⟩ := α def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A def mk_type_func : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl 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 def equiv.refl (x) : equiv x x := pSet.rec_on x $ λα A IH, ⟨λa, ⟨a, IH a⟩, λa, ⟨a, IH a⟩⟩ def equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λα A IH y, pSet.rec_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⟩⟩ def equiv.symm {x y} : equiv x y → equiv y x := equiv.euc (equiv.refl y) def equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := equiv.euc h1 (equiv.symm h2) instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λx y, equiv.symm, λx y z, equiv.trans⟩ protected def subset : pSet → pSet → Prop | ⟨α, A⟩ ⟨β, B⟩ := ∀a, ∃b, equiv (A a) (B b) instance : has_subset pSet := ⟨pSet.subset⟩ def 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⟩⟩⟩ def 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.trans (equiv.symm ba) ac⟩, λβγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ def 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, equiv.trans ca ab⟩, λγβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, equiv.trans cb (equiv.symm ab)⟩⟩ def mem : pSet → pSet → Prop | x ⟨β, B⟩ := ∃b, equiv x (B b) instance : has_mem pSet.{u} pSet.{u} := ⟨mem⟩ def mem.mk {α: Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := show mem (A a) ⟨α, A⟩, from ⟨a, equiv.refl (A a)⟩ def 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, equiv.symm ha⟩⟩ def 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, equiv.trans ha hb⟩, λ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, equiv.euc hb ha⟩⟩ def mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀{w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ⟨a, ha⟩, ⟨a, equiv.trans (equiv.symm h) ha⟩, λ⟨a, ha⟩, ⟨a, equiv.trans h ha⟩⟩ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} def equiv.eq {x y : pSet} (h : equiv x y) : to_set x = to_set y := set.ext (λz, mem.congr_right h) instance : has_coe pSet (set pSet) := ⟨to_set⟩ protected def empty : pSet := ⟨ulift empty, λe, match e with end⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ def mem_empty (x : pSet.{u}) : x ∉ (∅:pSet.{u}) := λe, match e with end protected def insert : pSet → pSet → pSet | u ⟨α, A⟩ := ⟨option α, λo, option.rec u A o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := pSet.insert (of_nat n) (of_nat n) def omega : pSet := ⟨ulift ℕ, λn, of_nat n.down⟩ protected def sep (p : set pSet) : pSet → pSet | ⟨α, A⟩ := ⟨{a // p (A a)}, λx, A x.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ def powerset : pSet → pSet | ⟨α, A⟩ := ⟨set α, λp, ⟨{a // p a}, λx, A x.1⟩⟩ 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⟩⟩⟩ def Union : pSet → pSet | ⟨α, A⟩ := ⟨Σx, (A x).type, λ⟨x, y⟩, (A x).func y⟩ theorem mem_Union : Π {x y : pSet.{u}}, y ∈ Union x ↔ ∃ z:pSet.{u}, ∃_: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 mk_type_func at this)⟩, λ⟨⟨β, B⟩, ⟨a, (e:equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by rw ←(mk_type_func (A a)) at e; exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, equiv.trans yb bc⟩⟩ def image (f : pSet.{u} → pSet.{u}) : pSet.{u} → pSet | ⟨α, A⟩ := ⟨α, λa, f (A a)⟩ def 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, equiv.trans yz (H za)⟩⟩ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ⟨x⟩, lift (A x)⟩ prefix ⇑ := pSet.lift def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ def lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λx, ⟨⟨x⟩, equiv.refl _⟩ 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) def resp (n) := { x : arity pSet.{u} n // arity.equiv x x } def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 def resp.refl {n} (a : resp n) : resp.equiv a a := a.2 def resp.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 := by delta resp.equiv; simp[arity.equiv]; exact λx y h, @resp.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.refl, λx y h, resp.euc (resp.refl y) h, λx y z h1 h2, resp.euc h1 $ resp.euc (resp.refl z) h2⟩ end pSet def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp 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 _ _ (equiv.refl z))⟩ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 @[simp] def eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (f.f x) := rfl end resp inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval _ f) attribute [class] definable attribute [instance] definable.mk def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f def 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 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.refl _⟩ (some_spec p) | (n+1) (F : Set → arity Set.{u} n) := begin have I := λx, (all_definable (F x)), refine definable.eq_mk ⟨λx:pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp[arity.equiv], intros x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, exact funext (λq, quotient.induction_on q $ λx, by simp[resp.f]; exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧)) end local attribute [instance] prop_decidable end classical namespace Set open pSet def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λx y x' y' hx hy, propext (iff.trans (mem.congr_left hx) (mem.congr_right hy))) instance : has_mem Set Set := ⟨mem⟩ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} protected def subset (x y : Set.{u}) := ∀ ⦃z:Set.{u}⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ instance has_subset' : has_subset (quotient pSet.setoid) := Set.has_subset theorem subset_iff : Π (x y : pSet), ⟦x⟧ ⊆ ⟦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, equiv.trans za ab⟩)⟩ def 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⟧))) def ext_iff {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) ↔ x = y := ⟨ext, λh, by simp[h]⟩ def empty : Set := ⟦∅⟧ instance : has_emptyc Set.{u} := ⟨empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] def mem_empty (x : Set.{u}) : x ∉ (∅:Set.{u}) := quotient.induction_on x pSet.mem_empty def eq_empty (x : Set.{u}) : x = ∅ ↔ ∀y:Set.{u}, y ∉ x := ⟨λh, by rw h; exact mem_empty, λh, ext (λy, ⟨λyx, absurd yx (h y), λy0, absurd y0 (mem_empty _)⟩)⟩ protected def insert : Set.{u} → Set.{u} → Set.{u} := 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⟩ @[simp] def mem_insert {x y z : Set.{u}} : x ∈ insert y z ↔ (x = y ∨ x ∈ z) := quotient.induction_on₃ x y z (λx y ⟨α, A⟩, show x ∈ mk (option α) (λo, option.rec y A o) ↔ ⟦x⟧ = ⟦y⟧ ∨ x ∈ 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⟩) @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ _ y ↔ x = y := iff.trans mem_insert ⟨λo, or.rec (λh, h) (λn, absurd n (mem_empty _)) o, or.inl⟩ @[simp] theorem mem_singleton' {x y : Set.{u}} : x ∈ @insert Set.{u} Set.{u} _ y ∅ ↔ x = y := mem_singleton -- It looks better when you print it, but I can't get the {y, z} notation to typecheck @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ (insert z (@insert Set.{u} Set.{u} _ y ∅)) ↔ (x = y ∨ x = z) := iff.trans mem_insert $ iff.trans or.comm $ let m := @mem_singleton x y in ⟨or.imp_left m.1, or.imp_left m.2⟩ def omega : Set := ⟦omega⟧ @[simp] theorem omega_zero : (∅:Set.{u}) ∈ omega.{u} := show pSet.mem ∅ pSet.omega, from ⟨⟨0⟩, equiv.refl _⟩ @[simp] theorem omega_succ {n : Set.{u}} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λx ⟨⟨n⟩, (h : x ≈ of_nat n)⟩, ⟨⟨n+1⟩, have Set.insert ⟦x⟧ ⟦x⟧ = Set.insert ⟦of_nat n⟧ ⟦of_nat n⟧, by rw (@quotient.sound pSet _ _ _ h), quotient.exact this⟩) protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λy, p ⟦y⟧), λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa ←(@quotient.sound pSet _ _ _ hb)⟩, hb⟩, λ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa (@quotient.sound pSet _ _ _ 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 rw (@quotient.sound pSet _ _ _ h); exact pa⟩, λ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by rw ←(@quotient.sound pSet _ _ _ h); exact pa⟩, h⟩⟩) 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} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y (λ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet) ∈ (pSet.powerset ⟨α, A⟩) ↔ _, by rw [mem_powerset, subset_iff]) theorem Union_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀a, ∃b, equiv (A a) (B b)) : ∀a, ∃b, (equiv ((Union ⟨α, A⟩).func a) ((Union ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin ginduction A a with ea γ Γ, ginduction B b with eb δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have 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, eq.rec d (eq.symm eb)⟩, this⟩ end def Union : Set → Set := resp.eval 1 ⟨pSet.Union, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨Union_lem A B αβ, λa, exists.elim (Union_lem B A (λb, exists.elim (βα b) (λc hc, ⟨c, equiv.symm hc⟩)) a) (λb hb, ⟨b, equiv.symm hb⟩)⟩⟩ notation `⋃` := Union @[simp] theorem mem_Union {x y : Set.{u}} : y ∈ Union x ↔ ∃ z:Set.{u}, ∃_:z ∈ x, y ∈ z := quotient.induction_on₂ x y (λx y, iff.trans mem_Union ⟨λ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ⟨z, h⟩, quotient.induction_on z (λz h, ⟨z, h⟩) h⟩) @[simp] theorem Union_singleton {x : Set.{u}} : Union (@insert Set.{u} _ _ x ∅) = x := ext $ λy, by simp; exact ⟨λ⟨z, zx, yz⟩, by simp at zx; simp[zx] at yz; exact yz, λyx, ⟨x, by simp, yx⟩⟩ theorem singleton_inj {x y : Set.{u}} (H : @insert Set.{u} Set.{u} _ x ∅ = @insert Set _ _ y ∅) : x = y := let this := congr_arg Union H in by rwa [Union_singleton, Union_singleton] at this protected def union (x y : Set.{u}) : Set.{u} := -- ⋃ {x, y} Set.Union (@insert Set _ _ y (insert x ∅)) protected def inter (x y : Set.{u}) : Set.{u} := -- {z ∈ x | z ∈ y} Set.sep (λz, z ∈ y) x protected def diff (x y : Set.{u}) : Set.{u} := -- {z ∈ x | z ∉ y} Set.sep (λz, z ∉ y) x instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ (z ∈ x ∨ z ∈ y) := iff.trans mem_Union ⟨λ⟨w, wxy, zw⟩, match mem_pair.1 wxy with | or.inl wx := or.inl (by rwa ←wx) | or.inr wy := or.inr (by rwa ←wy) end, λzxy, match zxy with | or.inl zx := ⟨x, mem_pair.2 (or.inl rfl), zx⟩ | or.inr zy := ⟨y, mem_pair.2 (or.inr rfl), zy⟩ end⟩ @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ (z ∈ x ∧ z ∈ y) := mem_sep @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ (z ∈ x ∧ z ∉ y) := mem_sep 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 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)⟩ 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)⟩ def 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] def 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⟩ def pair (x y : Set.{u}) : Set.{u} := -- {{x}, {x, y}} @insert Set.{u} _ _ (@insert Set.{u} _ _ y {x}) {insert x (∅ : Set.{u})} 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 := by refine iff.trans mem_sep ⟨and.right, λe, ⟨_, e⟩⟩; exact let ⟨a, ax, b, bY, ze, pab⟩ := e in by rw ze; exact mem_powerset.2 (λu uz, mem_powerset.2 $ (mem_pair.1 uz).elim (λua, by rw ua; exact λv vu, by rw mem_singleton.1 vu; exact mem_union.2 (or.inl ax)) (λuab, by rw uab; exact λv vu, (mem_pair.1 vu).elim (λva, by rw va; exact mem_union.2 (or.inl ax)) (λvb, by rw vb; exact mem_union.2 (or.inr bY)))) def pair_inj {x y x' y' : Set.{u}} (H : pair x y = pair x' y') : x = x' ∧ y = y' := begin have ae := ext_iff.2 H, simp[pair] at ae, have : x = x', { have xx'y' := (ae (@insert Set.{u} _ _ x ∅)).1 (by simp), cases xx'y' with h h, exact singleton_inj h, { have m : x' ∈ insert x (∅:Set.{u}), { rw h, simp }, simp at m, simp [*] } }, refine ⟨this, _⟩, cases this, have he : y = x → y = y', { intro yx, cases yx, have xy'x := (ae (@insert Set.{u} _ _ y' {x})).2 (by simp), cases xy'x with xy'x xy'xx, { have y'x : y' ∈ @insert Set.{u} Set.{u} _ x ∅ := by rw ←xy'x; simp, simp at y'x, simp [*] }, { have yxx := (ext_iff.2 xy'xx y').1 (by simp), simp at yxx, cases yxx; simp } }, have xyxy' := (ae (@insert Set.{u} _ _ y {x})).1 (by simp), cases xyxy' with xyx xyy', { have yx := (ext_iff.2 xyx y).1 (by simp), simp at yx, exact he yx }, { have yxy' := (ext_iff.2 xyy' y).1 (by simp), simp at yxy', cases yxy' with yx yy', exact he yx, assumption } end def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λa b, true) @[simp] def mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b := by simp[prod] @[simp] def 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_inj e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ⟨ax, bY⟩, by simp; exact ⟨a, ax, b, bY, rfl⟩⟩ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀z:Set.{u}, z ∈ x → ∃! w, pair z w ∈ f def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] def mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp[funs]; exact ⟨and.left, λh, ⟨h, h.left⟩⟩ -- 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 _ 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_inj 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 by rw (t2 (f z) (image.mk _ _ zx)); exact (pair_mem_prod.1 (ss t1)).right, λh, ⟨λy yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in by rw ←ze; exact pair_mem_prod.2 ⟨zx, h z zx⟩, λz, map_unique⟩⟩ end Set def Class := set Set namespace Class instance has_mem_Set_Class : has_mem Set Class := ⟨set.mem⟩ instance : has_subset Class := ⟨set.subset⟩ instance : has_sep Set Class := ⟨set.sep⟩ instance : has_emptyc Class := ⟨λ a, false⟩ instance : has_insert Set Class := ⟨set.insert⟩ instance : has_union Class := ⟨set.union⟩ instance : has_inter Class := ⟨set.inter⟩ instance : has_neg Class := ⟨set.compl⟩ instance : has_sdiff Class := ⟨set.diff⟩ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ def univ : Class := set.univ def to_Set (p : Set.{u} → Prop) (A : Class.{u}) : Prop := ∃x, ↑x = A ∧ p x protected def mem (A B : Class.{u}) : Prop := to_Set.{u} (λx, x ∈ 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 _ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) notation `𝒫` := powerset def Union (x : Class) : Class := set.sUnion (Class_to_Cong x) notation `⋃` := Union theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λz, by change z ∈ (x : Class.{u}) ↔ z ∈ (y : Class.{u}); simp [*] @[simp] theorem to_Set_of_Set (p : Set.{u} → Prop) (x : Set.{u}) : to_Set p x ↔ p 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 ↔ x ∈ A := to_Set_of_Set _ _ @[simp] theorem mem_hom_right (x y : Set.{u}) : x ∈ (y : Class.{u}) ↔ x ∈ y := iff.refl _ @[simp] theorem subset_hom (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.refl _ @[simp] theorem sep_hom (p : Set.{u} → Prop) (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, show _ ↔ false, by simp; exact 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 @[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 Union_hom (x : Set.{u}) : Union.{u} x = Set.Union x := set.ext $ λz, by refine iff.trans _ (iff.symm Set.mem_Union); exact ⟨λ⟨._, ⟨a, rfl, ax⟩, za⟩, ⟨a, ax, za⟩, λ⟨a, ax, za⟩, ⟨_, ⟨a, rfl, ax⟩, za⟩⟩ def iota (p : Set → Prop) : Class := Union {x | ∀y, p y ↔ y = x} theorem iota_val (p : Set → Prop) (x : Set) (H : ∀y, p y ↔ y = x) : iota p = ↑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 (Set → Prop) → Set function. theorem iota_ex (p) : iota.{u} p ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃x, ∀y, p y ↔ y = x) (λ⟨x, h⟩, ⟨x, eq.symm $ iota_val p x h⟩) (λhn, ⟨∅, by simp; exact set.ext (λz, ⟨false.rec _, λ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) def fval (F A : Class.{u}) : Class.{u} := iota (λy, to_Set (λx, Set.pair x y ∈ F) A) infixl `′`:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] def 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 simp; exact ⟨λ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_inj pr in by rw[←fw, wy], λe, by cases e; exact ⟨_, h, rfl⟩⟩) variables (x : Set.{u}) (h : (∅:Set.{u}) ∉ x) noncomputable def choice : Set := @map (λy, classical.epsilon (λz, z ∈ y)) (classical.all_definable _) x include h def 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⟩) def choice_is_func : is_func x (Union x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λy yx, by simp; exact ⟨y, yx, choice_mem_aux x h y yx⟩ def choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := by delta choice; rw map_fval yx; simp[choice_mem_aux x h y yx] end Set
2776c5b61c59a76bfab76496431d37dd79b07900
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/finsupp/defs.lean
2513d43d6cb1fdd6f6caadd54bb1528b98c3fd26
[ "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
38,675
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, Scott Morrison -/ import algebra.hom.group_action import algebra.indicator_function /-! # Type of functions with finite support For any type `α` and any type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements, which is defined in `algebra/big_operators/finsupp`. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `finsupp`: The type of finitely supported functions from `α` to `β`. * `finsupp.single`: The `finsupp` which is nonzero in exactly one point. * `finsupp.update`: Changes one value of a `finsupp`. * `finsupp.erase`: Replaces one value of a `finsupp` by `0`. * `finsupp.on_finset`: The restriction of a function to a `finset` as a `finsupp`. * `finsupp.map_range`: Composition of a `zero_hom` with a `finsupp`. * `finsupp.emb_domain`: Maps the domain of a `finsupp` by an embedding. * `finsupp.zip_with`: Postcomposition of two `finsupp`s with a function `f` such that `f 0 0 = 0`. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable theory open finset function open_locale classical big_operators variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance fun_like : fun_like (α →₀ M) α (λ _, M) := ⟨to_fun, begin rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g), congr', ext a, exact (hf _).trans (hg _).symm, end⟩ /-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →₀ M) (λ _, α → M) := fun_like.has_coe_to_fun @[ext] lemma ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := fun_like.ext _ _ h /-- Deprecated. Use `fun_like.ext_iff` instead. -/ lemma ext_iff {f g : α →₀ M} : f = g ↔ ∀ a, f a = g a := fun_like.ext_iff /-- Deprecated. Use `fun_like.coe_fn_eq` instead. -/ lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := fun_like.coe_fn_eq /-- Deprecated. Use `fun_like.coe_injective` instead. -/ lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn := fun_like.coe_injective /-- Deprecated. Use `fun_like.congr_fun` instead. -/ lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a := fun_like.congr_fun h _ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ @[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) : equiv_fun_on_fintype.symm f = f := by { ext, simp [equiv_fun_on_fintype], } /-- If `α` has a unique term, the type of finitely supported functions `α →₀ β` is equivalent to `β`. -/ @[simps] noncomputable def _root_.equiv.finsupp_unique {ι : Type*} [unique ι] : (ι →₀ M) ≃ M := finsupp.equiv_fun_on_fintype.trans (equiv.fun_unique ι M) end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function with value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update [decidable_eq α] (a : α) (b : M) : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single [decidable_eq α] (a : α) (b : M) : ⇑(single a b) = pi.single a b := single_eq_update a b @[simp] lemma single_zero (a : α) : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (a : α) (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma single_apply_ne_zero {a x : α} {b : M} : single a b x ≠ 0 ↔ (x = a ∧ b ≠ 0) := by simp [single_apply_eq_zero] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := by simpa only [support_single_ne_zero _ h] using singleton_ne_empty _ lemma support_single_disjoint [decidable_eq α] {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by rw [support_single_ne_zero _ hb, support_single_ne_zero _ hb', disjoint_singleton] @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single default x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single default (x default) := ext $ unique.forall_iff.2 single_eq_same.symm @[ext] lemma unique_ext [unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f default = g default := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero _ h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero _ hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] lemma support_subset_singleton {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ f = single a (f a) := ⟨λ h, eq_single_iff.mpr ⟨h, rfl⟩, λ h, (eq_single_iff.mp h).left⟩ lemma support_subset_singleton' {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ ∃ b, f = single a b := ⟨λ h, ⟨f a, support_subset_singleton.mp h⟩, λ ⟨b, hb⟩, by rw [hb, support_subset_singleton, single_eq_same]⟩ lemma card_support_le_one [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a, f = single a (f a) := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton] lemma card_support_le_one' [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a b, f = single a b := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton'] @[simp] lemma equiv_fun_on_fintype_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } @[simp] lemma equiv_fun_on_fintype_symm_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } end single /-! ### Declarations about `update` -/ section update variables [has_zero M] (f : α →₀ M) (a : α) (b : M) (i : α) /-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`. If `b = 0`, this amounts to removing `a` from the `finsupp.support`. Otherwise, if `a` was not in the `finsupp.support`, it is added to it. This is the finitely-supported version of `function.update`. -/ def update : α →₀ M := ⟨if b = 0 then f.support.erase a else insert a f.support, function.update f a b, λ i, begin simp only [function.update_apply, ne.def], split_ifs with hb ha ha hb; simp [ha, hb] end⟩ @[simp] lemma coe_update [decidable_eq α] : (f.update a b : α → M) = function.update f a b := by convert rfl @[simp] lemma update_self : f.update a (f a) = f := by { ext, simp } @[simp] lemma zero_update : update 0 a b = single a b := by { ext, rw single_eq_update, refl } lemma support_update [decidable_eq α] : support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := by convert rfl @[simp] lemma support_update_zero [decidable_eq α] : support (f.update a 0) = f.support.erase a := by convert if_pos rfl variables {b} lemma support_update_ne_zero [decidable_eq α] (h : b ≠ 0) : support (f.update a b) = insert a f.support := by convert if_neg h end update /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. If `a` is not in the support of `f` then `erase a f = f`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [decidable_eq α] {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := by convert rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_of_not_mem_support {f : α →₀ M} {a} (haf : a ∉ f.support) : erase a f = f := begin ext b, by_cases hab : b = a, { rwa [hab, erase_same, eq_comm, ←not_mem_support_iff] }, { rw erase_ne hab } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function must be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, which is well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled (defined in `data/finsupp/basic`): * `finsupp.map_range.equiv` * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] lemma support_map_range_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M) (he : function.injective e) : (finsupp.map_range e he0 f).support = f.support := begin ext, simp only [finsupp.mem_support_iff, ne.def, finsupp.map_range_apply], exact he.ne_iff' he0, end end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero _ hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end @[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) : emb_domain f (single a m) = single (f a) m := begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a', rfl⟩, simp [single_apply], }, { simp only [emb_domain_notin_range, h, single_apply, not_false_iff], rw if_neg, rintro rfl, simpa using h, }, end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- Given finitely supported functions `g₁ : α →₀ M` and `g₂ : α →₀ N` and function `f : M → N → P`, `zip_with f hf g₁ g₂` is the finitely supported function `α →₀ P` satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, which is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add (a : α) (b₁ b₂ : M) : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` in `linear_algebra/finsupp` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero a, single_add a⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` in `linear_algebra/finsupp` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ /-- Coercion from a `finsupp` to a function type is an `add_monoid_hom`. -/ @[simps] noncomputable def coe_fn_add_hom : (α →₀ M) →+ (α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } lemma update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) : f.update a b = single a b + f.erase a := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) : f.update a b = f.erase a + single a b := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := by rw [←update_eq_single_add_erase, update_self] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := by rw [←update_eq_erase_add_single, update_self] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end /-- `finsupp.erase` as an `add_monoid_hom`. -/ @[simps] def erase_add_hom (a : α) : (α →₀ M) →+ (α →₀ M) := { to_fun := erase a, map_zero' := erase_zero a, map_add' := erase_add a } @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_set_of_eq_single : add_submonoid.closure {f : α →₀ M | ∃ a b, f = single a b} = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ ⟨a, b, rfl⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_set_of_eq_single _, rintro _ ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] /-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ β →₀ M := { to_fun := λ v, emb_domain f v, map_zero' := by simp, map_add' := λ v w, begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a, rfl⟩, simp, }, { simp [emb_domain_notin_range, h], }, end, } @[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) : emb_domain f (v + w) = emb_domain f v + emb_domain f w := (emb_domain.add_monoid_hom f).map_add v w end add_zero_class section add_monoid variables [add_monoid M] /-- Note the general `finsupp.has_smul` instance doesn't apply as `ℕ` is not distributive unless `β i`'s addition is commutative. -/ instance has_nat_scalar : has_smul ℕ (α →₀ M) := ⟨λ n v, v.map_range ((•) n) (nsmul_zero _)⟩ instance : add_monoid (α →₀ M) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) instance [add_group G] : has_neg (α →₀ G) := ⟨map_range (has_neg.neg) neg_zero⟩ @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl /-- Note the general `finsupp.has_smul` instance doesn't apply as `ℤ` is not distributive unless `β i`'s addition is commutative. -/ instance has_int_scalar [add_group G] : has_smul ℤ (α →₀ G) := ⟨λ n v, v.map_range ((•) n) (zsmul_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_group G] : add_comm_group (α →₀ G) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) lemma single_add_single_eq_single_add_single [add_comm_monoid M] {k l m n : α} {u v : M} (hu : u ≠ 0) (hv : v ≠ 0) : single k u + single l v = single m u + single n v ↔ (k = m ∧ l = n) ∨ (u = v ∧ k = n ∧ l = m) ∨ (u + v = 0 ∧ k = l ∧ m = n) := begin simp_rw [fun_like.ext_iff, coe_add, single_eq_pi_single, ←funext_iff], exact pi.single_add_single_eq_single_add_single hu hv, end @[simp] lemma support_neg [add_group G] (f : α →₀ G) : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) lemma support_sub [decidable_eq α] [add_group G] {f g : α →₀ G} : support (f - g) ⊆ support f ∪ support g := begin rw [sub_eq_add_neg, ←support_neg g], exact support_add, end lemma erase_eq_sub_single [add_group G] (f : α →₀ G) (a : α) : f.erase a = f - single a (f a) := begin ext a', rcases eq_or_ne a a' with rfl|h, { simp }, { simp [erase_ne h.symm, single_eq_of_ne h] } end lemma update_eq_sub_add_single [add_group G] (f : α →₀ G) (a : α) (b : G) : f.update a b = f - single a (f a) + single a b := by rw [update_eq_erase_add_single, erase_eq_sub_single] end finsupp
44190dba4470378bbd27902c1c1535d3721628da
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0501/S0501.lean
bcb7ce89f8da8efbd5881d8d1f461f66f37ff705
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,271
lean
import algebra.group_power tactic.norm_num algebra.big_operators -- sheet 5 solns def Fib : ℕ → ℕ | 0 := 0 | 1 := 1 | (n+2) := Fib n + Fib (n+1) --#eval Fib 10 --#reduce Fib 10 def is_even (n : ℕ) : Prop := ∃ k, n=2*k def is_odd (n : ℕ) : Prop := ∃ k, n=2*k+1 lemma even_of_even_add_even (a b : ℕ) : is_even a → is_even b → is_even (a+b) := begin intros Ha Hb, cases Ha with k Hk, cases Hb with l Hl, existsi k+l, simp [Hk,Hl,add_mul], end lemma odd_of_odd_add_even {a b : ℕ} : is_odd a → is_even b → is_odd (a+b) := begin intros Ha Hb, cases Ha with k Hk, cases Hb with l Hl, existsi k+l, simp [Hk,Hl,add_mul], end lemma odd_of_even_add_odd {a b : ℕ} : is_even a → is_odd b → is_odd (a+b) := λ h1 h2, (add_comm b a) ▸ (odd_of_odd_add_even h2 h1) lemma even_of_odd_add_odd {a b : ℕ} : is_odd a → is_odd b → is_even (a+b) := begin intros Ha Hb, cases Ha with k Hk, cases Hb with l Hl, existsi k+l+1, -- simp [mul_add,Hk,Hl,one_add_one_eq_two] -- fails! rw [Hk,Hl,mul_add,mul_add], change 2 with 1+1, simp [mul_add,add_mul], end theorem Q1a : ∀ n : ℕ, n ≥ 1 → is_odd (Fib (3*n-2)) ∧ is_odd (Fib (3*n-1)) ∧ is_even (Fib (3*n)) := begin intros n Hn, cases n with m, have : ¬ (0 ≥ 1) := dec_trivial, exfalso, exact (this Hn), induction m with d Hd, exact ⟨⟨0,rfl⟩,⟨0,rfl⟩,⟨1,rfl⟩⟩, change 3*nat.succ d-2 with 3*d+1 at Hd, change 3*nat.succ d -1 with 3*d+2 at Hd, change 3*nat.succ d with 3*d+3 at Hd, change 3*nat.succ (nat.succ d)-2 with 3*d+4, change 3*nat.succ (nat.succ d)-1 with 3*d+5, change 3*nat.succ (nat.succ d) with 3*d+6, let Hyp := Hd (begin apply nat.succ_le_succ,exact nat.zero_le d,end), let H1 := Hyp.left, let H2 := Hyp.right.left, let H3 := Hyp.right.right, have H4 : is_odd (Fib (3*d+4)), change Fib (3*d+4) with Fib (3*d+2)+Fib(3*d+3), exact odd_of_odd_add_even H2 H3, have H5 : is_odd (Fib (3*d+5)), change Fib (3*d+5) with Fib (3*d+3)+Fib(3*d+4), exact odd_of_even_add_odd H3 H4, have H6 : is_even (Fib (3*d+6)), change Fib (3*d+6) with Fib (3*d+4)+Fib(3*d+5), exact even_of_odd_add_odd H4 H5, exact ⟨H4,H5,H6⟩, end theorem Q1b : is_odd (Fib (2017)) := begin have H : 2017 = 3*673-2 := dec_trivial, rw [H], exact (Q1a 673 (dec_trivial)).left, end
d9b23d4d44284165a1ea5fdc4662598183ae8cfa
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Compiler/IR/EmitC.lean
a92d1ce7da4e4c294d1702639fb3285e7569e442
[ "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
24,527
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.Runtime import Lean.Compiler.NameMangling import Lean.Compiler.ExportAttr import Lean.Compiler.InitAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.EmitUtil import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.SimpCase import Lean.Compiler.IR.Boxing namespace Lean namespace IR open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName) namespace EmitC def leanMainFn := "_lean_main" structure Context := (env : Environment) (modName : Name) (jpMap : JPParamsMap := {}) (mainFn : FunId := arbitrary _) (mainParams : Array Param := #[]) abbrev M := ReaderT Context (EStateM String String) def getEnv : M Environment := Context.env <$> read def getModName : M Name := Context.modName <$> read def getDecl (n : Name) : M Decl := do env ← getEnv; match findEnvDecl env n with | some d => pure d | none => throw ("unknown declaration '" ++ toString n ++ "'") @[inline] def emit {α : Type} [HasToString α] (a : α) : M Unit := modify (fun out => out ++ toString a) @[inline] def emitLn {α : Type} [HasToString α] (a : α) : M Unit := emit a *> emit "\n" def emitLns {α : Type} [HasToString α] (as : List α) : M Unit := as.forM $ fun a => emitLn a def argToCString (x : Arg) : String := match x with | Arg.var x => toString x | _ => "lean_box(0)" def emitArg (x : Arg) : M Unit := emit (argToCString x) def toCType : IRType → String | IRType.float => "double" | IRType.uint8 => "uint8_t" | IRType.uint16 => "uint16_t" | IRType.uint32 => "uint32_t" | IRType.uint64 => "uint64_t" | IRType.usize => "size_t" | IRType.object => "lean_object*" | IRType.tobject => "lean_object*" | IRType.irrelevant => "lean_object*" | IRType.struct _ _ => panic! "not implemented yet" | IRType.union _ _ => panic! "not implemented yet" def throwInvalidExportName {α : Type} (n : Name) : M α := throw ("invalid export name '" ++ toString n ++ "'") def toCName (n : Name) : M String := do env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure s | some _ => throwInvalidExportName n | none => if n == `main then pure leanMainFn else pure n.mangle def emitCName (n : Name) : M Unit := toCName n >>= emit def toCInitName (n : Name) : M String := do env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s | some _ => throwInvalidExportName n | none => pure ("_init_" ++ n.mangle) def emitCInitName (n : Name) : M Unit := toCInitName n >>= emit def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do let ps := decl.params; env ← getEnv; when (ps.isEmpty && addExternForConsts) (emit "extern "); emit (toCType decl.resultType ++ " " ++ cppBaseName); unless (ps.isEmpty) $ do { emit "("; -- We omit irrelevant parameters for extern constants let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps; if ps.size > closureMaxArgs && isBoxedName decl.name then emit "lean_object**" else ps.size.forM $ fun i => do { when (i > 0) (emit ", "); emit (toCType (ps.get! i).ty) }; emit ")" }; emitLn ";" def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do cppBaseName ← toCName decl.name; emitFnDeclAux decl cppBaseName addExternForConsts def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do let cName := mkNameSimple cNameStr; env ← getEnv; let extC := isExternC env decl.name; emitFnDeclAux decl cNameStr (!extC) def emitFnDecls : M Unit := do env ← getEnv; let decls := getDecls env; let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {}; let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {}; let usedDecls := usedDecls.toList; usedDecls.forM $ fun n => do decl ← getDecl n; match getExternNameFor env `c decl.name with | some cName => emitExternDeclAux decl cName | none => emitFnDecl decl (!modDecls.contains n) def emitMainFn : M Unit := do d ← getDecl `main; match d with | Decl.fdecl f xs t b => do unless (xs.size == 2 || xs.size == 1) (throw "invalid main function, incorrect arity when generating code"); env ← getEnv; let usesLeanAPI := usesModuleFrom env `Lean; if usesLeanAPI then emitLn "void lean_initialize();" else emitLn "void lean_initialize_runtime_module();"; emitLn " #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif int main(int argc, char ** argv) { #if defined(WIN32) || defined(_WIN32) SetErrorMode(SEM_FAILCRITICALERRORS); #endif lean_object* in; lean_object* res;"; if usesLeanAPI then emitLn "lean_initialize();" else emitLn "lean_initialize_runtime_module();"; modName ← getModName; emitLn ("res = initialize_" ++ (modName.mangle "") ++ "(lean_io_mk_world());"); emitLns ["lean_io_mark_end_initialization();", "if (lean_io_result_is_ok(res)) {", "lean_dec_ref(res);", "lean_init_task_manager();"]; if xs.size == 2 then do { emitLns ["in = lean_box(0);", "int i = argc;", "while (i > 1) {", " lean_object* n;", " i--;", " n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);", " in = n;", "}"]; emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());") } else do { emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());") }; emitLn "}"; emitLns ["if (lean_io_result_is_ok(res)) {", " int ret = lean_unbox(lean_io_result_get_value(res));", " lean_dec_ref(res);", " return ret;", "} else {", " lean_io_result_show_error(res);", " lean_dec_ref(res);", " return 1;", "}"]; emitLn "}" | other => throw "function declaration expected" def hasMainFn : M Bool := do env ← getEnv; let decls := getDecls env; pure $ decls.any (fun d => d.name == `main) def emitMainFnIfNeeded : M Unit := whenM hasMainFn emitMainFn def emitFileHeader : M Unit := do env ← getEnv; modName ← getModName; emitLn "// Lean compiler output"; emitLn ("// Module: " ++ toString modName); emit "// Imports:"; env.imports.forM $ fun m => emit (" " ++ toString m); emitLn ""; emitLn "#include <lean/lean.h>"; emitLns [ "#if defined(__clang__)", "#pragma clang diagnostic ignored \"-Wunused-parameter\"", "#pragma clang diagnostic ignored \"-Wunused-label\"", "#elif defined(__GNUC__) && !defined(__CLANG__)", "#pragma GCC diagnostic ignored \"-Wunused-parameter\"", "#pragma GCC diagnostic ignored \"-Wunused-label\"", "#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"", "#endif", "#ifdef __cplusplus", "extern \"C\" {", "#endif" ] def emitFileFooter : M Unit := emitLns [ "#ifdef __cplusplus", "}", "#endif" ] def throwUnknownVar {α : Type} (x : VarId) : M α := throw ("unknown variable '" ++ toString x ++ "'") def getJPParams (j : JoinPointId) : M (Array Param) := do ctx ← read; match ctx.jpMap.find? j with | some ps => pure ps | none => throw "unknown join point" def declareVar (x : VarId) (t : IRType) : M Unit := do emit (toCType t); emit " "; emit x; emit "; " def declareParams (ps : Array Param) : M Unit := ps.forM $ fun p => declareVar p.x p.ty partial def declareVars : FnBody → Bool → M Bool | e@(FnBody.vdecl x t _ b), d => do ctx ← read; if isTailCallTo ctx.mainFn e then pure d else declareVar x t *> declareVars b true | FnBody.jdecl j xs _ b, d => declareParams xs *> declareVars b (d || xs.size > 0) | e, d => if e.isTerminal then pure d else declareVars e.body d def emitTag (x : VarId) (xType : IRType) : M Unit := do if xType.isObj then do emit "lean_obj_tag("; emit x; emit ")" else emit x def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) := if alts.size != 2 then none else match alts.get! 0 with | Alt.ctor c b => some (c.cidx, b, (alts.get! 1).body) | _ => none def emitIf (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")"; emitBody t; emitLn "else"; emitBody e def emitCase (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit := match isIf alts with | some (tag, t, e) => emitIf emitBody x xType tag t e | _ => do emit "switch ("; emitTag x xType; emitLn ") {"; let alts := ensureHasDefault alts; alts.forM $ fun alt => match alt with | Alt.ctor c b => emit "case " *> emit c.cidx *> emitLn ":" *> emitBody b | Alt.default b => emitLn "default: " *> emitBody b; emitLn "}" def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit $ if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n") else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n"); emit "(" *> emit x; when (n != 1) (emit ", " *> emit n); emitLn ");" def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit (if checkRef then "lean_dec" else "lean_dec_ref"); emit "("; emit x; when (n != 1) (do emit ", "; emit n); emitLn ");" def emitDel (x : VarId) : M Unit := do emit "lean_free_object("; emit x; emitLn ");" def emitSetTag (x : VarId) (i : Nat) : M Unit := do emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");" def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitOffset (n : Nat) (offset : Nat) : M Unit := if n > 0 then do emit "sizeof(void*)*"; emit n; when (offset > 0) (emit " + " *> emit offset) else emit offset def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");" def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do match t with | IRType.float => emit "lean_ctor_set_float" | IRType.uint8 => emit "lean_ctor_set_uint8" | IRType.uint16 => emit "lean_ctor_set_uint16" | IRType.uint32 => emit "lean_ctor_set_uint32" | IRType.uint64 => emit "lean_ctor_set_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");" def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do ps ← getJPParams j; unless (xs.size == ps.size) (throw "invalid goto"); xs.size.forM $ fun i => do { let p := ps.get! i; let x := xs.get! i; emit p.x; emit " = "; emitArg x; emitLn ";" }; emit "goto "; emit j; emitLn ";" def emitLhs (z : VarId) : M Unit := do emit z; emit " = " def emitArgs (ys : Array Arg) : M Unit := ys.size.forM $ fun i => do when (i > 0) (emit ", "); emitArg (ys.get! i) def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := if usize == 0 then emit ssize else if ssize == 0 then emit "sizeof(size_t)*" *> emit usize else emit "sizeof(size_t)*" *> emit usize *> emit " + " *> emit ssize def emitAllocCtor (c : CtorInfo) : M Unit := do emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", "; emitCtorScalarSize c.usize c.ssize; emitLn ");" def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit := ys.size.forM $ fun i => do emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg (ys.get! i); emitLn ");" def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do emitLhs z; if c.size == 0 && c.usize == 0 && c.ssize == 0 then do emit "lean_box("; emit c.cidx; emitLn ");" else do emitAllocCtor c; emitCtorSetArgs z ys def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do emit "if (lean_is_exclusive("; emit x; emitLn ")) {"; n.forM $ fun i => do { emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");" }; emit " "; emitLhs z; emit x; emitLn ";"; emitLn "} else {"; emit " lean_dec_ref("; emit x; emitLn ");"; emit " "; emitLhs z; emitLn "lean_box(0);"; emitLn "}" def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do emit "if (lean_is_scalar("; emit x; emitLn ")) {"; emit " "; emitLhs z; emitAllocCtor c; emitLn "} else {"; emit " "; emitLhs z; emit x; emitLn ";"; when updtHeader (do emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");"); emitLn "}"; emitCtorSetArgs z ys def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");" def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");" def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.float => emit "lean_ctor_get_float" | IRType.uint8 => emit "lean_ctor_get_uint8" | IRType.uint16 => emit "lean_ctor_get_uint16" | IRType.uint32 => emit "lean_ctor_get_uint32" | IRType.uint64 => emit "lean_ctor_get_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");" def toStringArgs (ys : Array Arg) : List String := ys.toList.map argToCString def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do emit f; emit "("; -- We must remove irrelevant arguments to extern calls. _ ← ys.size.foldM (fun i (first : Bool) => if (ps.get! i).ty.isIrrelevant then pure first else do unless first (emit ", "); emitArg (ys.get! i); pure false) true; emitLn ");"; pure () def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit := match getExternEntryFor extData `c with | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys | some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";" | some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys | _ => throw ("failed to emit extern application '" ++ toString f ++ "'") def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do emitLhs z; decl ← getDecl f; match decl with | Decl.extern _ ps _ extData => emitExternCall f ps extData ys | _ => do emitCName f; when (ys.size > 0) (do emit "("; emitArgs ys; emit ")"); emitLn ";" def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do decl ← getDecl f; let arity := decl.params.size; emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");"; ys.size.forM $ fun i => do { let y := ys.get! i; emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" } def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit := if ys.size > closureMaxArgs then do emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};"; emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }" else do emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");" def emitBoxFn (xType : IRType) : M Unit := match xType with | IRType.usize => emit "lean_box_usize" | IRType.uint32 => emit "lean_box_uint32" | IRType.uint64 => emit "lean_box_uint64" | IRType.float => emit "lean_box_float" | other => emit "lean_box" def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");" def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.usize => emit "lean_unbox_usize" | IRType.uint32 => emit "lean_unbox_uint32" | IRType.uint64 => emit "lean_unbox_uint64" | IRType.float => emit "lean_unbox_float" | other => emit "lean_unbox"; emit "("; emit x; emitLn ");" def emitIsShared (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");" def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");" def toHexDigit (c : Nat) : String := String.singleton c.digitChar def quoteString (s : String) : String := let q := "\""; let q := s.foldl (fun q c => q ++ if c == '\n' then "\\n" else if c == '\n' then "\\t" else if c == '\\' then "\\\\" else if c == '\"' then "\\\"" else if c.toNat <= 31 then "\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16) -- TODO(Leo): we should use `\unnnn` for escaping unicode characters. else String.singleton c) q; q ++ "\"" def emitNumLit (t : IRType) (v : Nat) : M Unit := if t.isObj then do if v < uint32Sz then emit "lean_unsigned_to_nat(" *> emit v *> emit "u)" else emit "lean_cstr_to_nat(\"" *> emit v *> emit "\")" else emit v def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := emitLhs z *> match v with | LitVal.num v => emitNumLit t v *> emitLn ";" | LitVal.str v => do emit "lean_mk_string("; emit (quoteString v); emitLn ");" def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit := match v with | Expr.ctor c ys => emitCtor z c ys | Expr.reset n x => emitReset z n x | Expr.reuse x c u ys => emitReuse z x c u ys | Expr.proj i x => emitProj z i x | Expr.uproj i x => emitUProj z i x | Expr.sproj n o x => emitSProj z t n o x | Expr.fap c ys => emitFullApp z c ys | Expr.pap c ys => emitPartialApp z c ys | Expr.ap x ys => emitApp z x ys | Expr.box t x => emitBox z x t | Expr.unbox x => emitUnbox z t x | Expr.isShared x => emitIsShared z x | Expr.isTaggedPtr x => emitIsTaggedPtr z x | Expr.lit v => emitLit z t v def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do ctx ← read; match v, b with | Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y | _, _ => pure false def paramEqArg (p : Param) (x : Arg) : Bool := match x with | Arg.var x => p.x == x | _ => false /- Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments ``` p_0 := y_0, ... p_{n-1} := y_{n-1} ``` Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`. That is, we have ``` p_i := y_i, ... p_j := p_i, -- p_i was overwritten above ``` -/ def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool := let n := ps.size; n.any $ fun i => let p := ps.get! i; (i+1, n).anyI $ fun j => paramEqArg p (ys.get! j) def emitTailCall (v : Expr) : M Unit := match v with | Expr.fap _ ys => do ctx ← read; let ps := ctx.mainParams; unless (ps.size == ys.size) (throw "invalid tail call"); if overwriteParam ps ys then do { emitLn "{"; ps.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) $ do { emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";" } }; ps.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) (do emit p.x; emit " = _tmp_"; emit i; emitLn ";") }; emitLn "}" } else do { ys.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) (do emit p.x; emit " = "; emitArg y; emitLn ";") } }; emitLn "goto _start;" | _ => throw "bug at emitTailCall" partial def emitBlock (emitBody : FnBody → M Unit) : FnBody → M Unit | FnBody.jdecl j xs v b => emitBlock b | d@(FnBody.vdecl x t v b) => do ctx ← read; if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v *> emitBlock b | FnBody.inc x n c p b => unless p (emitInc x n c) *> emitBlock b | FnBody.dec x n c p b => unless p (emitDec x n c) *> emitBlock b | FnBody.del x b => emitDel x *> emitBlock b | FnBody.setTag x i b => emitSetTag x i *> emitBlock b | FnBody.set x i y b => emitSet x i y *> emitBlock b | FnBody.uset x i y b => emitUSet x i y *> emitBlock b | FnBody.sset x i o y t b => emitSSet x i o y t *> emitBlock b | FnBody.mdata _ b => emitBlock b | FnBody.ret x => emit "return " *> emitArg x *> emitLn ";" | FnBody.case _ x xType alts => emitCase emitBody x xType alts | FnBody.jmp j xs => emitJmp j xs | FnBody.unreachable => emitLn "lean_panic_unreachable();" partial def emitJPs (emitBody : FnBody → M Unit) : FnBody → M Unit | FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitBody v; emitJPs b | e => unless e.isTerminal (emitJPs e.body) partial def emitFnBody : FnBody → M Unit | b => do emitLn "{"; declared ← declareVars b false; when declared (emitLn ""); emitBlock emitFnBody b; emitJPs emitFnBody b; emitLn "}" def emitDeclAux (d : Decl) : M Unit := do env ← getEnv; let (vMap, jpMap) := mkVarJPMaps d; adaptReader (fun (ctx : Context) => { ctx with jpMap := jpMap }) $ do unless (hasInitAttr env d.name) $ match d with | Decl.fdecl f xs t b => do baseName ← toCName f; emit (toCType t); emit " "; if xs.size > 0 then do { emit baseName; emit "("; if xs.size > closureMaxArgs && isBoxedName d.name then emit "lean_object** _args" else xs.size.forM $ fun i => do { when (i > 0) (emit ", "); let x := xs.get! i; emit (toCType x.ty); emit " "; emit x.x }; emit ")" } else do { emit ("_init_" ++ baseName ++ "()") }; emitLn " {"; when (xs.size > closureMaxArgs && isBoxedName d.name) $ xs.size.forM $ fun i => do { let x := xs.get! i; emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];" }; emitLn "_start:"; adaptReader (fun (ctx : Context) => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b); emitLn "}" | _ => pure () def emitDecl (d : Decl) : M Unit := let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices catch (emitDeclAux d) (fun err => throw (err ++ "\ncompiling:\n" ++ toString d)) def emitFns : M Unit := do env ← getEnv; let decls := getDecls env; decls.reverse.forM emitDecl def emitMarkPersistent (d : Decl) (n : Name) : M Unit := when d.resultType.isObj $ do { emit "lean_mark_persistent("; emitCName n; emitLn ");" } def emitDeclInit (d : Decl) : M Unit := do env ← getEnv; let n := d.name; if isIOUnitInitFn env n then do { emit "res = "; emitCName n; emitLn "(lean_io_mk_world());"; emitLn "if (lean_io_result_is_error(res)) return res;"; emitLn "lean_dec_ref(res);" } else when (d.params.size == 0) $ match getInitFnNameFor env d.name with | some initFn => do { emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());"; emitLn "if (lean_io_result_is_error(res)) return res;"; emitCName n; emitLn " = lean_io_result_get_value(res);"; emitMarkPersistent d n; emitLn "lean_dec_ref(res);" } | _ => do { emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n } def emitInitFn : M Unit := do env ← getEnv; modName ← getModName; env.imports.forM $ fun imp => emitLn ("lean_object* initialize_" ++ imp.module.mangle "" ++ "(lean_object*);"); emitLns [ "static bool _G_initialized = false;", "lean_object* initialize_" ++ modName.mangle "" ++ "(lean_object* w) {", "lean_object * res;", "if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));", "_G_initialized = true;" ]; env.imports.forM $ fun imp => emitLns [ "res = initialize_" ++ imp.module.mangle "" ++ "(lean_io_mk_world());", "if (lean_io_result_is_error(res)) return res;", "lean_dec_ref(res);"]; let decls := getDecls env; decls.reverse.forM emitDeclInit; emitLns ["return lean_io_result_mk_ok(lean_box(0));", "}"] def main : M Unit := do emitFileHeader; emitFnDecls; emitFns; emitInitFn; emitMainFnIfNeeded; emitFileFooter end EmitC @[export lean_ir_emit_c] def emitC (env : Environment) (modName : Name) : Except String String := match (EmitC.main { env := env, modName := modName }).run "" with | EStateM.Result.ok _ s => Except.ok s | EStateM.Result.error err _ => Except.error err end IR end Lean
9abec5bff1fe78214d57b5d59b5623f1e881fcd6
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/witt_vector/witt_polynomial.lean
b60dbd26ad8a18f0629ed06ae777c43e4364b935
[ "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
10,811
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.char_p.invertible import data.mv_polynomial.variables import data.mv_polynomial.comm_ring import data.mv_polynomial.expand import data.zmod.basic /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ open mv_polynomial open finset (hiding map) open finsupp (single) open_locale big_operators local attribute [-simp] coe_eval₂_hom variables (p : ℕ) variables (R : Type*) [comm_ring R] /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ noncomputable def witt_polynomial (n : ℕ) : mv_polynomial ℕ R := ∑ i in range (n+1), monomial (single i (p ^ (n - i))) (p ^ i) lemma witt_polynomial_eq_sum_C_mul_X_pow (n : ℕ) : witt_polynomial p R n = ∑ i in range (n+1), C (p ^ i : R) * X i ^ (p ^ (n - i)) := begin apply sum_congr rfl, rintro i -, rw [monomial_eq, finsupp.prod_single_index], rw pow_zero, end /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit localized "notation `W_` := witt_polynomial p" in witt -- Notation with ring of coefficients implicit localized "notation `W` := witt_polynomial p _" in witt open_locale witt open mv_polynomial /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map_witt_polynomial (f : R →+* S) (n : ℕ) : map f (W n) = W n := begin rw [witt_polynomial, ring_hom.map_sum, witt_polynomial, sum_congr rfl], intros i hi, rw [map_monomial, ring_hom.map_pow, ring_hom.map_nat_cast], end variables (R) @[simp] lemma constant_coeff_witt_polynomial [hp : fact p.prime] (n : ℕ) : constant_coeff (witt_polynomial p R n) = 0 := begin simp only [witt_polynomial, ring_hom.map_sum, constant_coeff_monomial], rw [sum_eq_zero], rintro i hi, rw [if_neg], rw [finsupp.single_eq_zero], exact ne_of_gt (pow_pos hp.1.pos _) end @[simp] lemma witt_polynomial_zero : witt_polynomial p R 0 = X 0 := by simp only [witt_polynomial, X, sum_singleton, range_one, pow_zero] @[simp] lemma witt_polynomial_one : witt_polynomial p R 1 = C ↑p * X 1 + (X 0) ^ p := by simp only [witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ, range_one, sum_singleton, one_mul, pow_one, C_1, pow_zero] lemma aeval_witt_polynomial {A : Type*} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : aeval f (W_ R n) = ∑ i in range (n+1), p^i * (f i) ^ (p ^ (n-i)) := by simp [witt_polynomial, alg_hom.map_sum, aeval_monomial, finsupp.prod_single_index] /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th witt polynomial by `p`. -/ @[simp] lemma witt_polynomial_zmod_self (n : ℕ) : W_ (zmod (p ^ (n + 1))) (n + 1) = expand p (W_ (zmod (p^(n + 1))) n) := begin simp only [witt_polynomial_eq_sum_C_mul_X_pow], rw [sum_range_succ, ← nat.cast_pow, char_p.cast_eq_zero (zmod (p^(n+1))) (p^(n+1)), C_0, zero_mul, zero_add, alg_hom.map_sum, sum_congr rfl], intros k hk, rw [alg_hom.map_mul, alg_hom.map_pow, expand_X, alg_hom_C, ← pow_mul, ← pow_succ], congr, rw mem_range at hk, rw [add_comm, nat.add_sub_assoc (nat.lt_succ_iff.mp hk), ← add_comm], end section p_prime -- in fact, `0 < p` would be sufficient variables [hp : fact p.prime] include hp lemma witt_polynomial_vars [char_zero R] (n : ℕ) : (witt_polynomial p R n).vars = range (n + 1) := begin have : ∀ i, (monomial (finsupp.single i (p ^ (n - i))) (p ^ i : R)).vars = {i}, { intro i, rw vars_monomial_single, { rw ← pos_iff_ne_zero, apply pow_pos hp.1.pos }, { rw [← nat.cast_pow, nat.cast_ne_zero], apply ne_of_gt, apply pow_pos hp.1.pos i } }, rw [witt_polynomial, vars_sum_of_disjoint], { simp only [this, int.nat_cast_eq_coe_nat, bUnion_singleton_eq_self], }, { simp only [this, int.nat_cast_eq_coe_nat], intros a b h, apply singleton_disjoint.mpr, rwa mem_singleton, }, end lemma witt_polynomial_vars_subset (n : ℕ) : (witt_polynomial p R n).vars ⊆ range (n + 1) := begin rw [← map_witt_polynomial p (int.cast_ring_hom R), ← witt_polynomial_vars p ℤ], apply vars_map, end end p_prime end /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ noncomputable def X_in_terms_of_W [invertible (p : R)] : ℕ → mv_polynomial ℕ R | n := (X n - (∑ i : fin n, have _ := i.2, (C (p^(i : ℕ) : R) * (X_in_terms_of_W i)^(p^(n-i))))) * C (⅟p ^ n : R) lemma X_in_terms_of_W_eq [invertible (p : R)] {n : ℕ} : X_in_terms_of_W p R n = (X n - (∑ i in range n, C (p^i : R) * X_in_terms_of_W p R i ^ p ^ (n - i))) * C (⅟p ^ n : R) := by { rw [X_in_terms_of_W, ← fin.sum_univ_eq_sum_range] } @[simp] lemma constant_coeff_X_in_terms_of_W [hp : fact p.prime] [invertible (p : R)] (n : ℕ) : constant_coeff (X_in_terms_of_W p R n) = 0 := begin apply nat.strong_induction_on n; clear n, intros n IH, rw [X_in_terms_of_W_eq, mul_comm, ring_hom.map_mul, ring_hom.map_sub, ring_hom.map_sum, constant_coeff_C, sum_eq_zero], { simp only [constant_coeff_X, sub_zero, mul_zero] }, { intros m H, rw mem_range at H, simp only [ring_hom.map_mul, ring_hom.map_pow, constant_coeff_C, IH m H], rw [zero_pow, mul_zero], apply pow_pos hp.1.pos, } end @[simp] lemma X_in_terms_of_W_zero [invertible (p : R)] : X_in_terms_of_W p R 0 = X 0 := by rw [X_in_terms_of_W_eq, range_zero, sum_empty, pow_zero, C_1, mul_one, sub_zero] section p_prime variables [hp : fact p.prime] include hp lemma X_in_terms_of_W_vars_aux (n : ℕ) : n ∈ (X_in_terms_of_W p ℚ n).vars ∧ (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := begin apply nat.strong_induction_on n, clear n, intros n ih, rw [X_in_terms_of_W_eq, mul_comm, vars_C_mul, vars_sub_of_disjoint, vars_X, range_succ, insert_eq], swap 3, { apply nonzero_of_invertible }, work_on_goal 0 { simp only [true_and, true_or, eq_self_iff_true, mem_union, mem_singleton], intro i, rw [mem_union, mem_union], apply or.imp id }, work_on_goal 1 { rw [vars_X, singleton_disjoint] }, all_goals { intro H, replace H := vars_sum_subset _ _ H, rw mem_bUnion at H, rcases H with ⟨j, hj, H⟩, rw vars_C_mul at H, swap, { apply pow_ne_zero, exact_mod_cast hp.1.ne_zero }, rw mem_range at hj, replace H := (ih j hj).2 (vars_pow _ _ H), rw mem_range at H }, { rw mem_range, exact lt_of_lt_of_le H hj }, { exact lt_irrefl n (lt_of_lt_of_le H hj) }, end lemma X_in_terms_of_W_vars_subset (n : ℕ) : (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := (X_in_terms_of_W_vars_aux p n).2 end p_prime lemma X_in_terms_of_W_aux [invertible (p : R)] (n : ℕ) : X_in_terms_of_W p R n * C (p^n : R) = X n - ∑ i in range n, C (p^i : R) * (X_in_terms_of_W p R i)^p^(n-i) := by rw [X_in_terms_of_W_eq, mul_assoc, ← C_mul, ← mul_pow, inv_of_mul_self, one_pow, C_1, mul_one] @[simp] lemma bind₁_X_in_terms_of_W_witt_polynomial [invertible (p : R)] (k : ℕ) : bind₁ (X_in_terms_of_W p R) (W_ R k) = X k := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum], simp only [alg_hom.map_pow, C_pow, alg_hom.map_mul, alg_hom_C], rw [sum_range_succ, nat.sub_self, pow_zero, pow_one, bind₁_X_right, mul_comm, ← C_pow, X_in_terms_of_W_aux], simp only [C_pow, bind₁_X_right, sub_add_cancel], end @[simp] lemma bind₁_witt_polynomial_X_in_terms_of_W [invertible (p : R)] (n : ℕ) : bind₁ (W_ R) (X_in_terms_of_W p R n) = X n := begin apply nat.strong_induction_on n, clear n, intros n H, rw [X_in_terms_of_W_eq, alg_hom.map_mul, alg_hom.map_sub, bind₁_X_right, alg_hom_C, alg_hom.map_sum], have : W_ R n - ∑ i in range n, C (p ^ i : R) * (X i) ^ p ^ (n - i) = C (p ^ n : R) * X n, by simp only [witt_polynomial_eq_sum_C_mul_X_pow, nat.sub_self, sum_range_succ, pow_one, add_sub_cancel, pow_zero], rw [sum_congr rfl, this], { -- this is really slow for some reason rw [mul_right_comm, ← C_mul, ← mul_pow, mul_inv_of_self, one_pow, C_1, one_mul] }, { intros i h, rw mem_range at h, simp only [alg_hom.map_mul, alg_hom.map_pow, alg_hom_C, H i h] }, end
8da4487329420c2ef3071c0c688395423436eb6c
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tactic12.lean
9982049983409f45e2131b885fcadcf9c9df3c19
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
214
lean
(* import("tactic.lua") *) theorem T (a b : Bool) : ((fun x, x /\ b) a) → ((fun x, x) a). beta. conj_hyp. exact. done. variables p q : Bool. theorem T2 : p /\ q → q. conj_hyp. exact. done.
759b0d2ef285247623279d4c445534d61e53b391
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/hmul2.lean
e71af86b9d72e010e124d5b6f39768390f5d52a1
[ "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,112
lean
@[default_instance] instance [Mul α] : HMul α (Array α) (Array α) where hMul a as := as.map (a * ·) instance [Mul α] : Mul (Array α) where mul as bs := (as.zip bs).map fun (a, b) => a * b #eval 2 * #[3, 4, 5] #eval (2:Nat) * #[3, 4, 5] #check fun x => x * 2 #check fun y : Int => let x := 1; x * y #check fun y : Int => let_delayed x := 1; x * y def f1 (n : Nat) (i : Int) := i * n def f2 (n : Nat) (i : Int) := n * i def f3 (n : Nat) (i : Int) := n * (n * (n * (n * i))) def f4 (n : Nat) (i : Int) := n + (n + (n * (n * i))) def f5 (n : Nat) (i : Int) := n + (n + (n * (i, i).1)) def f6 (n : Nat) (i : Int) := let y := 2 * i let x := y * n n + x def f7 (n : Nat) (i : Int) := n + (n * 2 * i) def f8 (n : Nat) (i : Int) := n * 2 + (i * 1 * n * 2 * i) def f9 [Mul α] (a : α) (as bs : Array α) : Array α := a * as * bs def f10 (a : Int) (as bs : Array Int) : Array Int := 2 * a * as * bs def f11 (a : Int) (as bs : Array Int) : Array Int := 3 * a * as * (2 * bs) def f12 [Mul α] (as bs : Array α) : Array α := as.foldl (init := bs) fun bs a => a * bs
855d4855b44fada3faebe257d0a8d59464dad98a
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/field_theory/splitting_field.lean
b19a3e5de8d0dd733839093f085132d947b047ed
[ "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
37,237
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.intermediate_field import ring_theory.adjoin_root /-! # Splitting fields This file introduces the notion of a splitting field of a polynomial and provides an embedding from a splitting field to any field that splits the polynomial. A polynomial `f : polynomial K` splits over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have degree `1`. A field extension of `K` of a polynomial `f : polynomial K` is called a splitting field if it is the smallest field extension of `K` such that `f` splits. ## Main definitions * `polynomial.splits i f`: A predicate on a field homomorphism `i : K → L` and a polynomial `f` saying that `f` is zero or all of its irreducible factors over `L` have degree `1`. * `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`. * `polynomial.is_splitting_field`: A predicate on a field to be a splitting field of a polynomial `f`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. * `lift_of_splits`: If `K` and `L` are field extensions of a field `F` and for some finite subset `S` of `K`, the minimal polynomial of every `x ∈ K` splits as a polynomial with coefficients in `L`, then `algebra.adjoin F S` embeds into `L`. * `polynomial.is_splitting_field.lift`: An embedding of a splitting field of the polynomial `f` into another field such that `f` splits. * `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorphic to `splitting_field f` and thus, being a splitting field is unique up to isomorphism. -/ noncomputable theory open_locale classical big_operators polynomial universes u v w variables {F : Type u} {K : Type v} {L : Type w} namespace polynomial variables [field K] [field L] [field F] open polynomial section splits variables (i : K →+* L) /-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/ def splits (f : K[X]) : Prop := f = 0 ∨ ∀ {g : L[X]}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : K[X]) := or.inl rfl @[simp] lemma splits_C (a : K) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 K _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((injective_iff_map_eq_zero i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : K[X]} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : K[X]} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h le_rfl)]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_of_nat_degree_le_one {f : K[X]} (hf : nat_degree f ≤ 1) : splits i f := splits_of_degree_le_one i (degree_le_of_nat_degree_le hf) lemma splits_of_nat_degree_eq_one {f : K[X]} (hf : nat_degree f = 1) : splits i f := splits_of_nat_degree_le_one i (le_of_eq hf) lemma splits_mul {f g : K[X]} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : K[X]} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw polynomial.map_mul; exact hg.trans (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw polynomial.map_mul; exact hg.trans (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : K[X]} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : K[X]} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : K[X]} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : L →+* F) {f : K[X]} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : K[X]} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : K} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_X : X.splits i := splits_of_degree_eq_one _ $ degree_X theorem splits_id_iff_splits {f : K[X]} : (f.map i).splits (ring_hom.id L) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : K[X]} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type u} {s : ι → K[X]} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end lemma splits_pow {f : K[X]} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i := begin rw [←finset.card_range n, ←finset.prod_const], exact splits_prod i (λ j hj, hf), end lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n theorem splits_prod_iff {ι : Type u} {s : ι → K[X]} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : L[X]} (hp : irreducible p) (hp_splits : splits (ring_hom.id L) p) : p.degree = 1 := begin by_cases h_nz : p = 0, { exfalso, simp * at *, }, rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : K[X]} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then by simp [hf0] else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma roots_ne_zero_of_splits {f : K[X]} (hs : splits i f) (hf0 : nat_degree f ≠ 0) : (f.map i).roots ≠ 0 := let ⟨x, hx⟩ := exists_root_of_splits i hs (λ h, hf0 $ nat_degree_eq_of_degree_eq_some h) in λ h, by { rw ← eval_map at hx, cases h.subst ((mem_roots _).2 hx), exact map_ne_zero (λ h, (h.subst hf0) rfl) } /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : K[X]} (hf : f.splits i) (hfd : f.degree ≠ 0) : L := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : K[X]} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd lemma nat_degree_eq_card_roots {p : K[X]} {i : K →+* L} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases hp : p = 0, { rw [hp, nat_degree_zero, polynomial.map_zero, roots_zero, multiset.card_zero] }, obtain ⟨q, he, hd, hr⟩ := exists_prod_multiset_X_sub_C_mul (p.map i), rw [← splits_id_iff_splits, ← he] at hsplit, have hpm : p.map i ≠ 0 := map_ne_zero hp, rw ← he at hpm, have hq : q ≠ 0 := λ h, hpm (by rw [h, mul_zero]), rw [← nat_degree_map i, ← hd, add_right_eq_self], by_contra, have := roots_ne_zero_of_splits (ring_hom.id L) (splits_of_splits_mul _ _ hsplit).2 h, { rw map_id at this, exact this hr }, { exact mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq }, end lemma degree_eq_card_roots {p : K[X]} {i : K →+* L} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] theorem roots_map {f : K[X]} (hf : f.splits $ ring_hom.id K) : (f.map i).roots = f.roots.map i := (roots_map_of_injective_card_eq_total_degree i.injective $ by { convert (nat_degree_eq_card_roots hf).symm, rw map_id }).symm lemma image_root_set [algebra F K] [algebra F L] {p : F[X]} (h : p.splits (algebra_map F K)) (f : K →ₐ[F] L) : f '' p.root_set K = p.root_set L := begin classical, rw [root_set, ←finset.coe_image, ←multiset.to_finset_map, ←f.coe_to_ring_hom, ←roots_map ↑f ((splits_id_iff_splits (algebra_map F K)).mpr h), map_map, f.comp_algebra_map, ←root_set], end lemma adjoin_root_set_eq_range [algebra F K] [algebra F L] {p : F[X]} (h : p.splits (algebra_map F K)) (f : K →ₐ[F] L) : algebra.adjoin F (p.root_set L) = f.range ↔ algebra.adjoin F (p.root_set K) = ⊤ := begin rw [←image_root_set h f, algebra.adjoin_image, ←algebra.map_top], exact (subalgebra.map_injective f.to_ring_hom.injective).eq_iff, end lemma eq_prod_roots_of_splits {p : K[X]} {i : K →+* L} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin rw ← leading_coeff_map, symmetry, apply C_leading_coeff_mul_prod_multiset_X_sub_C, rw nat_degree_map, exact (nat_degree_eq_card_roots hsplit).symm, end lemma eq_prod_roots_of_splits_id {p : K[X]} (hsplit : splits (ring_hom.id K) p) : p = C p.leading_coeff * (p.roots.map (λ a, X - C a)).prod := by simpa using eq_prod_roots_of_splits hsplit lemma eq_prod_roots_of_monic_of_splits_id {p : K[X]} (m : monic p) (hsplit : splits (ring_hom.id K) p) : p = (p.roots.map (λ a, X - C a)).prod := begin convert eq_prod_roots_of_splits_id hsplit, simp [m], end lemma eq_X_sub_C_of_splits_of_single_root {x : K} {h : K[X]} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = C h.leading_coeff * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : K[X]} {s : multiset L} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : L, X - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, begin rw irreducible_iff_prime at hp, rw [hs, ← multiset.prod_to_list] at hdp, obtain (hd|hd) := hp.2.2 _ _ hdp, { refine (hp.2.1 $ is_unit_of_dvd_unit hd _).elim, exact is_unit_C.2 ((leading_coeff_ne_zero.2 hf0).is_unit.map i) }, { obtain ⟨q, hq, hd⟩ := hp.dvd_prod_iff.1 hd, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.1 ((multiset.mem_to_list _ _).1 hq), rw degree_eq_degree_of_associated ((hp.dvd_prime_iff_associated $ prime_X_sub_C a).1 hd), exact degree_X_sub_C a }, end lemma splits_of_splits_id {f : K[X]} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 hp.irreducible (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : K[X]} : splits i f ↔ ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, X - C a)).prod := ⟨λ hf, ⟨(f.map i).roots, eq_prod_roots_of_splits hf⟩, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : L →+* F) {f : K[X]} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A polynomial splits if and only if it has as many roots as its degree. -/ lemma splits_iff_card_roots {p : K[X]} : splits (ring_hom.id K) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, rw splits_iff_exists_multiset (ring_hom.id K), use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end lemma aeval_root_derivative_of_splits [algebra K L] {P : K[X]} (hmo : P.monic) (hP : P.splits (algebra_map K L)) {r : L} (hr : r ∈ (P.map (algebra_map K L)).roots) : aeval r P.derivative = (((P.map $ algebra_map K L).roots.erase r).map (λ a, r - a)).prod := begin replace hmo := hmo.map (algebra_map K L), replace hP := (splits_id_iff_splits (algebra_map K L)).2 hP, rw [aeval_def, ← eval_map, ← derivative_map], nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [eval_multiset_prod_X_sub_C_derivative hr] end /-- If `P` is a monic polynomial that splits, then `coeff P 0` equals the product of the roots. -/ lemma prod_roots_eq_coeff_zero_of_monic_of_split {P : K[X]} (hmo : P.monic) (hP : P.splits (ring_hom.id K)) : coeff P 0 = (-1) ^ P.nat_degree * P.roots.prod := begin nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [coeff_zero_eq_eval_zero, eval_multiset_prod, multiset.map_map], simp_rw [function.comp_app, eval_sub, eval_X, zero_sub, eval_C], conv_lhs { congr, congr, funext, rw [neg_eq_neg_one_mul] }, rw [multiset.prod_map_mul, multiset.map_const, multiset.prod_repeat, multiset.map_id', splits_iff_card_roots.1 hP] end /-- If `P` is a monic polynomial that splits, then `P.next_coeff` equals the sum of the roots. -/ lemma sum_roots_eq_next_coeff_of_monic_of_split {P : K[X]} (hmo : P.monic) (hP : P.splits (ring_hom.id K)) : P.next_coeff = - P.roots.sum := begin nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [monic.next_coeff_multiset_prod _ _ (λ a ha, _)], { simp_rw [next_coeff_X_sub_C, multiset.sum_map_neg'] }, { exact monic_X_sub_C a } end end splits end polynomial section embeddings variables (F) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly {R : Type*} [comm_ring R] [algebra F R] (x : R) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.lift_hom _ x $ minpoly.aeval F x) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range_aeval F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (injective_iff_map_eq_zero _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minpoly.dvd F x hp, λ y, let ⟨p, hp⟩ := (set_like.ext_iff.1 (algebra.adjoin_singleton_eq_range_aeval F x) (y : R)).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset /-- If a `subalgebra` is finite_dimensional as a submodule then it is `finite_dimensional`. -/ lemma finite_dimensional.of_subalgebra_to_submodule {K V : Type*} [field K] [ring V] [algebra K V] {s : subalgebra K V} (h : finite_dimensional K s.to_submodule) : finite_dimensional K s := h /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union_eq_adjoin_adjoin], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := ( (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite s.finite_to_set H3)).of_subalgebra_to_submodule, letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minpoly.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minpoly.dvd _ _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm, refine ⟨subalgebra.of_restrict_scalars _ _ _⟩, refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _, exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a end end embeddings namespace polynomial variables [field K] [field L] [field F] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : K[X]) : K[X] := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X lemma irreducible_factor (f : K[X]) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end /-- See note [fact non-instances]. -/ lemma fact_irreducible_factor (f : K[X]) : fact (irreducible (factor f)) := ⟨irreducible_factor f⟩ local attribute [instance] fact_irreducible_factor theorem factor_dvd_of_not_is_unit {f : K[X]} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : K[X]} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : K[X]} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : K[X]) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : K[X]) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : K[X]) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : K[X]} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial, which removes `n` (arbitrarily-chosen) factors. Uses recursion on the degree. For better definitional behaviour, structures including `splitting_field_aux` (such as instances) should be defined using this recursion in each field, rather than defining the whole tuple through recursion. -/ def splitting_field_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : K[X]), Type u := nat.rec_on n (λ K _ _, K) $ λ n ih K _ f, by exactI ih f.remove_factor namespace splitting_field_aux theorem succ (n : ℕ) (f : K[X]) : splitting_field_aux (n+1) f = splitting_field_aux n f.remove_factor := rfl instance field (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : K[X]}, field (splitting_field_aux n f) := nat.rec_on n (λ K _ _, ‹field K›) $ λ n ih K _ f, ih instance inhabited {n : ℕ} {f : K[X]} : inhabited (splitting_field_aux n f) := ⟨37⟩ /- Note that the recursive nature of this definition and `splitting_field_aux.field` creates non-definitionally-equal diamonds in the `ℕ`- and `ℤ`- actions. ```lean example (n : ℕ) {K : Type u} [field K] {f : K[X]} (hfn : f.nat_degree = n) : (add_comm_monoid.nat_module : module ℕ (splitting_field_aux n f hfn)) = @algebra.to_module _ _ _ _ (splitting_field_aux.algebra n _ hfn) := rfl -- fails ``` It's not immediately clear whether this _can_ be fixed; the failure is much the same as the reason that the following fails: ```lean def cases_twice {α} (a₀ aₙ : α) : ℕ → α × α | 0 := (a₀, a₀) | (n + 1) := (aₙ, aₙ) example (x : ℕ) {α} (a₀ aₙ : α) : (cases_twice a₀ aₙ x).1 = (cases_twice a₀ aₙ x).2 := rfl -- fails ``` We don't really care at this point because this is an implementation detail (which is why this is not a docstring), but we do in `splitting_field.algebra'` below. -/ instance algebra (n : ℕ) : Π (R : Type*) {K : Type u} [comm_semiring R] [field K], by exactI Π [algebra R K] {f : K[X]}, algebra R (splitting_field_aux n f) := nat.rec_on n (λ R K _ _ _ _, by exactI ‹algebra R K›) $ λ n ih R K _ _ _ f, by exactI ih R instance is_scalar_tower (n : ℕ) : Π (R₁ R₂ : Type*) {K : Type u} [comm_semiring R₁] [comm_semiring R₂] [has_smul R₁ R₂] [field K], by exactI Π [algebra R₁ K] [algebra R₂ K], by exactI Π [is_scalar_tower R₁ R₂ K] {f : K[X]}, is_scalar_tower R₁ R₂ (splitting_field_aux n f) := nat.rec_on n (λ R₁ R₂ K _ _ _ _ _ _ _ _, by exactI ‹is_scalar_tower R₁ R₂ K›) $ λ n ih R₁ R₂ K _ _ _ _ _ _ _ f, by exactI ih R₁ R₂ instance algebra''' {n : ℕ} {f : K[X]} : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor) := splitting_field_aux.algebra n _ instance algebra' {n : ℕ} {f : K[X]} : algebra (adjoin_root f.factor) (splitting_field_aux n.succ f) := splitting_field_aux.algebra''' instance algebra'' {n : ℕ} {f : K[X]} : algebra K (splitting_field_aux n f.remove_factor) := splitting_field_aux.algebra n K instance scalar_tower' {n : ℕ} {f : K[X]} : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor) := begin -- finding this instance ourselves makes things faster haveI : is_scalar_tower K (adjoin_root f.factor) (adjoin_root f.factor) := is_scalar_tower.right, exact splitting_field_aux.is_scalar_tower n K (adjoin_root f.factor), end instance scalar_tower {n : ℕ} {f : K[X]} : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux (n + 1) f) := splitting_field_aux.scalar_tower' theorem algebra_map_succ (n : ℕ) (f : K[X]) : by exact algebra_map K (splitting_field_aux (n+1) f) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor)).comp (adjoin_root.of f.factor) := is_scalar_tower.algebra_map_eq _ _ _ protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n), splits (algebra_map K $ splitting_field_aux n f) f := nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ (nat_degree_remove_factor' hf)) } theorem exists_lift (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n) {L : Type*} [field L], by exactI ∀ (j : K →+* L) (hf : splits j f), ∃ k : splitting_field_aux n f →+* L, k.comp (algebra_map _ _) = j := nat.rec_on n (λ K _ _ _ L _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih K _ f hf L _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n), algebra.adjoin K (↑(f.map $ algebra_map K $ splitting_field_aux n f).roots.to_finset : set (splitting_field_aux n f)) = ⊤ := nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih K _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map K (splitting_field_aux n.succ f)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, polynomial.map_mul] at hmf0 ⊢, rw [roots_mul hmf0, polynomial.map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_singleton, finset.coe_singleton, algebra.adjoin_union_eq_adjoin_adjoin, ← set.image_singleton, algebra.adjoin_algebra_map K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor), ih _ (nat_degree_remove_factor' hfn), subalgebra.restrict_scalars_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : K[X]) := splitting_field_aux f.nat_degree f namespace splitting_field variables (f : K[X]) instance : field (splitting_field f) := splitting_field_aux.field _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ /-- This should be an instance globally, but it creates diamonds with the `ℕ`, `ℤ`, and `ℚ` algebras (via their `smul` and `to_fun` fields): ```lean example : (algebra_nat : algebra ℕ (splitting_field f)) = splitting_field.algebra' f := rfl -- fails example : (algebra_int _ : algebra ℤ (splitting_field f)) = splitting_field.algebra' f := rfl -- fails example [char_zero K] [char_zero (splitting_field f)] : (algebra_rat : algebra ℚ (splitting_field f)) = splitting_field.algebra' f := rfl -- fails ``` Until we resolve these diamonds, it's more convenient to only turn this instance on with `local attribute [instance]` in places where the benefit of having the instance outweighs the cost. In the meantime, the `splitting_field.algebra` instance below is immune to these particular diamonds since `K = ℕ` and `K = ℤ` are not possible due to the `field K` assumption. Diamonds in `algebra ℚ (splitting_field f)` instances are still possible via this instance unfortunately, but these are less common as they require suitable `char_zero` instances to be present. -/ instance algebra' {R} [comm_semiring R] [algebra R K] : algebra R (splitting_field f) := splitting_field_aux.algebra _ _ instance : algebra K (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map K (splitting_field f)) f := splitting_field_aux.splits _ _ rfl variables [algebra K L] (hb : splits (algebra_map K L) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[K] L := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ rfl _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin K (↑(f.map (algebra_map K $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ rfl theorem adjoin_root_set : algebra.adjoin K (f.root_set f.splitting_field) = ⊤ := adjoin_roots f end splitting_field variables (K L) [algebra K L] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : K[X]) : Prop := (splits [] : splits (algebra_map K L) f) (adjoin_roots [] : algebra.adjoin K (↑(f.map (algebra_map K L)).roots.to_finset : set L) = ⊤) namespace is_splitting_field variables {K} instance splitting_field (f : K[X]) : is_splitting_field K (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {K L F} [algebra F K] [algebra F L] [is_scalar_tower F K L] variables {K} instance map (f : F[X]) [is_splitting_field F L f] : is_splitting_field K L (f.map $ algebra_map F K) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits L f }, subalgebra.restrict_scalars_injective F $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.restrict_scalars_top, eq_top_iff, ← adjoin_roots L f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin K _ _ _ _ _ _ hx }⟩ variables {K} (L) theorem splits_iff (f : K[X]) [is_splitting_field K L f] : polynomial.splits (ring_hom.id K) f ↔ (⊤ : subalgebra K L) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots L f ▸ (roots_map (algebra_map K L) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ set_like.mem_coe.2 $ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl K _ ▸ ring_equiv.self_trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits L f) }⟩ theorem mul (f g : F[X]) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field F K f] [is_splitting_field K L (g.map $ algebra_map F K)] : is_splitting_field F L (f * g) := ⟨(is_scalar_tower.algebra_map_eq F K L).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits K f)) ((splits_map_iff _ _).1 (splits L $ g.map $ algebra_map F K)), by rw [polynomial.map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map F L) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union_eq_adjoin_adjoin, is_scalar_tower.algebra_map_eq F K L, ← map_map, roots_map (algebra_map K L) ((splits_id_iff_splits $ algebra_map F K).2 $ splits K f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom, ← map_map, adjoin_roots, subalgebra.restrict_scalars_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra K F] (f : K[X]) [is_splitting_field K L f] (hf : polynomial.splits (algebra_map K F) f) : L →ₐ[K] F := if hf0 : f = 0 then (algebra.of_id K F).comp $ (algebra.bot_equiv K L : (⊥ : subalgebra K L) →ₐ[K] K).comp $ by { rw ← (splits_iff L f).1 (show f.splits (ring_hom.id K), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots L f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨is_algebraic_iff_is_integral.1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) }) algebra.to_top theorem finite_dimensional (f : K[X]) [is_splitting_field K L f] : finite_dimensional K L := ⟨@algebra.top_to_submodule K L _ _ _ ▸ adjoin_roots L f ▸ fg_adjoin_of_finite (finset.finite_to_set _) (λ y hy, if hf : f = 0 then by { rw [hf, polynomial.map_zero, roots_zero] at hy, cases hy } else is_algebraic_iff_is_integral.1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)⟩ instance (f : K[X]) : _root_.finite_dimensional K f.splitting_field := finite_dimensional f.splitting_field f /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : K[X]) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f := begin refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional L f, have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) := le_antisymm (linear_map.finrank_le_finrank_of_injective (show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field))) (linear_map.finrank_le_finrank_of_injective (show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))), change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _, exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field) end lemma of_alg_equiv [algebra K F] (p : K[X]) (f : F ≃ₐ[K] L) [is_splitting_field K F p] : is_splitting_field K L p := begin split, { rw ← f.to_alg_hom.comp_algebra_map, exact splits_comp_of_splits _ _ (splits F p) }, { rw [←(algebra.range_top_iff_surjective f.to_alg_hom).mpr f.surjective, ←root_set, adjoin_root_set_eq_range (splits F p), root_set, adjoin_roots F p] }, end end is_splitting_field end splitting_field end polynomial namespace intermediate_field open polynomial variables [field K] [field L] [algebra K L] {p : polynomial K} lemma splits_of_splits {F : intermediate_field K L} (h : p.splits (algebra_map K L)) (hF : ∀ x ∈ p.root_set L, x ∈ F) : p.splits (algebra_map K F) := begin simp_rw [root_set, finset.mem_coe, multiset.mem_to_finset] at hF, rw splits_iff_exists_multiset, refine ⟨multiset.pmap subtype.mk _ hF, map_injective _ (algebra_map F L).injective _⟩, conv_lhs { rw [polynomial.map_map, ←is_scalar_tower.algebra_map_eq, eq_prod_roots_of_splits h, ←multiset.pmap_eq_map _ _ _ hF] }, simp_rw [polynomial.map_mul, polynomial.map_multiset_prod, multiset.map_pmap, polynomial.map_sub, map_C, map_X], refl, end end intermediate_field
352856c51db39a51146f59e72c236496d543bc8b
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/adjunction/over.lean
806490206f7c541c75b988c72f6974fe52c61ed7
[ "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,604
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.binary_products import category_theory.monad.products import category_theory.over /-! # Adjunctions related to the over category Construct the left adjoint `star X` to `over.forget X : over X ⥤ C`. ## TODO Show `star X` itself has a left adjoint provided `C` is locally cartesian closed. -/ noncomputable theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category limits comonad variables {C : Type u} [category.{v} C] (X : C) /-- The functor from `C` to `over X` which sends `Y : C` to `π₁ : X ⨯ Y ⟶ X`, sometimes denoted `X*`. -/ @[simps] def star [has_binary_products C] : C ⥤ over X := cofree _ ⋙ coalgebra_to_over X /-- The functor `over.forget X : over X ⥤ C` has a right adjoint given by `star X`. Note that the binary products assumption is necessary: the existence of a right adjoint to `over.forget X` is equivalent to the existence of each binary product `X ⨯ -`. -/ def forget_adj_star [has_binary_products C] : over.forget X ⊣ star X := (coalgebra_equiv_over X).symm.to_adjunction.comp _ _ (adj _) /-- Note that the binary products assumption is necessary: the existence of a right adjoint to `over.forget X` is equivalent to the existence of each binary product `X ⨯ -`. -/ instance [has_binary_products C] : is_left_adjoint (over.forget X) := ⟨_, forget_adj_star X⟩ end category_theory
41d27772bcfbe4e6f75b7695dd32d632051eda75
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/archimedean.lean
b04d316a1169df2c260e421532901a04487150ab
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
14,493
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.int.least_greatest import data.rat.floor /-! # Archimedean groups and fields. This file defines the archimedean property for ordered groups and proves several results connected to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural number `n` such that `x ≤ n • y`. ## Main definitions * `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean property. * `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making it into a `floor_ring`. ## Main statements * `ℕ`, `ℤ`, and `ℚ` are archimedean. -/ open int set variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) instance order_dual.archimedean [ordered_add_comm_group α] [archimedean α] : archimedean αᵒᵈ := ⟨λ x y hy, let ⟨n, hn⟩ := archimedean.arch (-x : α) (neg_pos.2 hy) in ⟨n, by rwa [neg_nsmul, neg_le_neg_iff] at hn⟩⟩ section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_unique_zsmul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃! k : ℤ, k • a ≤ g ∧ g < (k + 1) • a := begin let s : set ℤ := {n : ℤ | n • a ≤ g}, obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ), { assume n hn, apply (zsmul_le_zsmul_iff ha).mp, rw ← coe_nat_zsmul at hk, exact le_trans hn hk }, obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, have hm'' : g < (m + 1) • a, { contrapose! hm', exact ⟨m + 1, hm', lt_add_one _⟩, }, refine ⟨m, ⟨hm, hm''⟩, λ n hn, (hm' n hn.1).antisymm $ int.le_of_lt_add_one _⟩, rw ← zsmul_lt_zsmul_iff ha, exact lt_of_le_of_lt hm hn.2 end lemma exists_unique_zsmul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃! k : ℤ, 0 ≤ g - k • a ∧ g - k • a < a := by simpa only [sub_nonneg, add_zsmul, one_zsmul, sub_lt_iff_lt_add'] using exists_unique_zsmul_near_of_pos ha g lemma exists_unique_add_zsmul_mem_Ico {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b + m • a ∈ set.Ico c (c + a) := (equiv.neg ℤ).bijective.exists_unique_iff.2 $ by simpa only [equiv.neg_apply, mem_Ico, neg_zsmul, ← sub_eq_add_neg, le_sub_iff_add_le, zero_add, add_comm c, sub_lt_iff_lt_add', add_assoc] using exists_unique_zsmul_near_of_pos' ha (b - c) lemma exists_unique_add_zsmul_mem_Ioc {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b + m • a ∈ set.Ioc c (c + a) := (equiv.add_right (1 : ℤ)).bijective.exists_unique_iff.2 $ by simpa only [add_zsmul, sub_lt_iff_lt_add', le_sub_iff_add_le', ← add_assoc, and.comm, mem_Ioc, equiv.coe_add_right, one_zsmul, add_le_add_iff_right] using exists_unique_zsmul_near_of_pos ha (c - b) end linear_ordered_add_comm_group theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := begin nontriviality α, exact (exists_nat_gt x).imp (λ n, le_of_lt) end lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le, let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n • y : h ... = n * y : nsmul_eq_mul _ _ ... < 1 + n * y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this) (add_nonneg zero_le_two hy.le) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section ordered_ring variables [ordered_ring α] [nontrivial α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa int.cast_coe_nat⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end ordered_ring section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] [archimedean α] {x y ε : α} /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_mem_Ioc_zpow`, but with ≤ and < the other way around. -/ lemma exists_mem_Ico_zpow (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, x ∈ Ico (y ^ n) (y ^ (n + 1)) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by { rw [zpow_neg y (↑N), zpow_coe_nat], exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (zpow_le_of_le hy.le hlt.le) (lt_of_le_of_lt hm (by rwa ← zpow_coe_nat at hM)))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_mem_Ico_zpow`, but with ≤ and < the other way around. -/ lemma exists_mem_Ioc_zpow (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, x ∈ Ioc (y ^ n) (y ^ (n + 1)) := let ⟨m, hle, hlt⟩ := exists_mem_Ico_zpow (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [zpow_neg, inv_lt (zpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, zpow_neg, le_inv hx (zpow_pos_of_pos hyp _)]⟩ /-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/ lemma exists_pow_lt_of_lt_one (hx : 0 < x) (hy : y < 1) : ∃ n : ℕ, y ^ n < x := begin by_cases y_pos : y ≤ 0, { use 1, simp only [pow_one], linarith, }, rw [not_le] at y_pos, rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩, exact ⟨q, by rwa [inv_pow, inv_lt_inv hx (pow_pos y_pos _)] at hq⟩ end /-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`. This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/ lemma exists_nat_pow_near_of_lt_one (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) : ∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n := begin rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩) with ⟨n, hn, h'n⟩, refine ⟨n, _, _⟩, { rwa [inv_pow, inv_lt_inv xpos (pow_pos ypos _)] at h'n }, { rwa [inv_pow, inv_le_inv (pow_pos ypos _) xpos] at hn } end lemma exists_rat_gt (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh, have n0 := nat.cast_pos.1 n0', rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 le_rfl) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, int.cast_coe_nat, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end lemma le_of_forall_rat_lt_imp_le (h : ∀ q : ℚ, (q : α) < x → (q : α) ≤ y) : x ≤ y := le_of_not_lt $ λ hyx, let ⟨q, hy, hx⟩ := exists_rat_btwn hyx in hy.not_le $ h _ hx lemma le_of_forall_lt_rat_imp_le (h : ∀ q : ℚ, y < q → x ≤ q) : x ≤ y := le_of_not_lt $ λ hyx, let ⟨q, hy, hx⟩ := exists_rat_btwn hyx in hx.not_le $ h _ hy lemma eq_of_forall_rat_lt_iff_lt (h : ∀ q : ℚ, (q : α) < x ↔ (q : α) < y) : x = y := (le_of_forall_rat_lt_imp_le $ λ q hq, ((h q).1 hq).le).antisymm $ le_of_forall_rat_lt_imp_le $ λ q hq, ((h q).2 hq).le lemma eq_of_forall_lt_rat_iff_lt (h : ∀ q : ℚ, x < q ↔ y < q) : x = y := (le_of_forall_lt_rat_imp_le $ λ q hq, ((h q).2 hq).le).antisymm $ le_of_forall_lt_rat_imp_le $ λ q hq, ((h q).1 hq).le theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 lemma exists_rat_near (x : α) (ε0 : 0 < ε) : ∃ q : ℚ, |x - q| < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ ((sub_lt_self_iff x).2 ε0).trans ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ end linear_ordered_field section linear_ordered_field variables [linear_ordered_field α] lemma archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ lemma archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ lemma archimedean_iff_int_lt : archimedean α ↔ ∀ x : α, ∃ n : ℤ, x < n := ⟨@exists_int_gt α _ _, begin rw archimedean_iff_nat_lt, intros h x, obtain ⟨n, h⟩ := h x, refine ⟨n.to_nat, h.trans_le _⟩, exact_mod_cast int.le_to_nat _, end⟩ lemma archimedean_iff_int_le : archimedean α ↔ ∀ x : α, ∃ n : ℤ, x ≤ n := archimedean_iff_int_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (int.cast_lt.2 (lt_add_one _))⟩⟩ lemma archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨⌈q⌉₊, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (nat.le_ceil _)⟩⟩ lemma archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := floor_ring.of_floor α (λ a, classical.some (exists_floor a)) (λ z a, (classical.some_spec (exists_floor a) z).symm) /-- A linear ordered field that is a floor ring is archimedean. -/ lemma floor_ring.archimedean (α) [linear_ordered_field α] [floor_ring α] : archimedean α := begin rw archimedean_iff_int_le, exact λ x, ⟨⌈x⌉, int.le_ceil x⟩ end
8915a6ca27aa88687e59b1410c6375152bc6555b
42610cc2e5db9c90269470365e6056df0122eaa0
/library/theories/finite_group_theory/sylow.lean
f83e290fb2c62dda1009d838292492d816ce6838
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
8,655
lean
import theories.number_theory.pinat import data algebra.group theories.finite_group_theory.subgroup theories.finite_group_theory.finsubg theories.number_theory.pinat theories.finite_group_theory.cyclic theories.finite_group_theory.perm theories.finite_group_theory.action import theories.finite_group_theory.extra_action theories.finite_group_theory.quotient theories.finite_group_theory.extra_finsubg data.finset.extra_finset import theories.finite_group_theory.newpgroup open nat finset fintype group_theory subtype namespace group_theory variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG section SylowTheorem parameter {p : nat} variable A : finset G variable [HAfG : is_finsubg A] -- for this definition to be interesting, we need to be able to talk about the group generated by H : finset G -- this may be done later but is not urgent -- definition maxGroup [reducible] (P : subgroup G → Prop) [HdecP : ∀ B, decidable (P B)] (H : finset G) : Prop := -- maxSet (λ (B : finset) , -- pose maxp A P := [max P | p.-subgroup(A) P]; definition maxp [class] (P : finset G) : Prop := maxSet (λ (B : finset G), pi_subgroup (pred_p p) B A ∧ is_finsubg_prop G B) P attribute maxp [reducible] -- lemma maxp_refl (P : finset G) : maxp A P → pi_subgroup (pred_p p) P A ∧ is_finsubg_prop G P := -- assume (Hmaxp : maxp A P), -- maxsetp Hmaxp -- TODO : extend to maxgroup (see fingroup.v) definition maxp_is_finsubg [instance] (P : finset G) [Hmaxp : maxp A P] : is_finsubg P := have H : is_finsubg_prop G P, from and.right (maxsetp Hmaxp), is_finsubg_is_finsubg_prop H definition decidable_maxp [instance] (P : finset G) : decidable (maxp A P) := decidable_maxset (λ B, pi_subgroup (pred_p p) B A ∧ is_finsubg_prop G B) P -- reveal decidable_maxp -- pose S := [set P | maxp G P]. definition S := { P : subgroup G | maxp A (elt_of P) } -- S A is a fintype because it is a subtype of a subtype of a fintype. There seem to be no instances of this yet definition finTSA [instance] : fintype (S A) := sorry -- definition S := subtype (maxp A) -- definition f : G → S → S := sorry abbreviation normalizer_in [reducible] (S T : finset G) : finset G := T ∩ normalizer S -- SmaxN P Q: Q \in S -> Q \subset 'N(P) -> maxp 'N_G(P) Q. -- reminder: 'N(P) = the normalizer of P, 'N_G(P) = the normalizer of P in G lemma SmaxN (P Q : finset G) : maxp A Q → Q ⊆ normalizer P → maxp (normalizer_in P A) Q := assume (HmaxP : maxp A Q) HQnormP, iff.elim_right (maxSet_iff) (take B HQB, have H : _, from iff.elim_left (maxSet_iff) HmaxP B HQB, iff.intro (assume H1, begin apply (iff.elim_left H), apply and.intro, apply pi_subgroup_trans (and.left H1), exact (finset_inter_subset_left), exact (and.right H1) end) (assume Heq, begin have pi_subgroup (pred_p p) B A ∧ is_finsubg_prop G B, from iff.elim_right H Heq, apply and.intro, have Hsub : B ⊆ (A ∩ (normalizer P)), from (subset_inter (and.left (and.left this)) ((eq.symm Heq) ▸ HQnormP)), apply (pi_subgroup_sub (and.left this) Hsub), exact finset_inter_subset_left, exact and.right this end)) -- Definition normal A B := (A \subset B) && (B \subset normaliser A). definition is_normal_in [reducible] (B C : finset G) : Prop := C ⊆ (normalizer B) definition normal_subgroup [reducible] (B C : finset G) [HB : is_finsubg B] [HC : is_finsubg C] := B ⊆ C ∧ C ⊆ (normalizer B) attribute normal_subgroup [class] -- lemma normSelf (A : finset G) : A ⊆ (normalizer A) := -- subset_normalizer include HAfG -- have nrmG P: P \subset G -> P <| 'N_G(P). lemma nrmG (P : finset G) [HfGP : is_finsubg P] (sPA : P ⊆ A) : is_normal_in P (normalizer_in P A) := begin rewrite ↑is_normal_in, exact finset_inter_subset_right end omit HAfG check pi_subgroup_subset open nat -- definition subgroup_lcoset_type [instance] (B C : finset G) [HB : is_finsubg B] [HC : is_finsubg C] [HnsBC : normal_subgroup B C] : is_finsubg (fin_lcosets C B) := sorry -- (in pgroup.v) Lemma normal_max_pgroup_Hall G H : -- [max H | pi.-subgroup(G) H] -> H <| G -> pi.-Hall(G) H. -- let us do a less general version for starters lemma normal_max_pgroup_Hall (B C : finset G) [HB : is_finsubg B] [HC : is_finsubg C] : maxp C B → normal_subgroup B C → pHall (pred_p p) B C := assume HmaxB Hnormal, have HB : (pi_subgroup (pred_p p) B C) ∧ is_finsubg_prop G B, from maxsetp HmaxB, have HsBC : B ⊆ C, from pi_subgroup_subset _ (and.left HB), and.intro (HsBC) (and.intro (and.right (and.left HB)) (have toto : _, from and.right (and.left HB), have Hindex : index B C = card (fin_lcosets B C), from by rewrite ↑index, have Hdiv : _, from index_card_div _ _ HsBC, have HCpos : card C > 0, from card_pos_of_mem (finsubg_has_one C), have HBpos : card B > 0, from card_pos_of_mem (finsubg_has_one B), have Hpos : card (fin_lcosets B C) > 0, from begin apply (pos_of_mul_pos_right (eq.subst Hindex _)), end, begin rewrite [Hindex,↑is_pi'_nat,↑is_pi_nat], apply and.intro, exact Hpos, rewrite -Hindex, intro p1 Hp1primeCB, have Hprimep1 : prime p1, from (prime_of_mem_prime_factors Hp1primeCB), have Hp1div : p1 ∣ card (fin_lcosets B C), from eq.subst Hindex (dvd_of_mem_prime_factors Hp1primeCB), have Hcard : card (phiH B ' C) = index B C, from begin rewrite (card_im_phi_lcosets B C (and.right Hnormal)) end, rewrite -image_psiH at Hp1div, rewrite -(card_im_phi_lcosets B C (and.right Hnormal)) at Hp1div, intro Habs, -- now we want to show that we can build a bigger group than B have Hfinsubg_imPhi: is_finsubg (phiH B ' C), from phiH_preserves_groups B C (and.right Hnormal), have Hp1divglob : p1 ∣ card (lcoset_type (normalizer B) B), from dvd.trans Hp1div (lagrange_div (subset_univ _)), have Cauchy : ∃ (g1 : lcoset_type (normalizer B) B), g1 ∈ (phiH B ' C) ∧ order g1 = p1 , from actual_Cauchy_theorem _ (prime_of_mem_prime_factors Hp1primeCB) Hp1div, cases Cauchy with g1 Hg1, cases (lift_subgroup _ (cyc g1)) with U HU, cases HU with DefU Hand, cases Hand with sBU Hand, cases Hand with sgU phi_cyc, have HsgU : is_finsubg U, from is_finsubg_is_finsubg_prop sgU, have HcardBU : card U = index B U * card B, from index_card_div B U sBU, revert HcardBU, rewrite index_card_fin_coset_type, rewrite card_lcoset_type, have HnormalU : U ⊆ normalizer B, from sorry, -- this should be added to lift_subgroup, in fact U ⊆ C rewrite -(image_psiH B U), rewrite -(card_im_phi_lcosets B U HnormalU), rewrite phi_cyc, have card (cyc g1) = p1, from (and.right Hg1), rewrite this, intro HcardU, have pgrpU : pgroup (pred_p p) U, from begin rewrite [↑pgroup,HcardU], rewrite pinat_mul, apply and.intro, apply (pinat_prime Hprimep1), exact Habs, exact toto end, -- cases (exists_of_mem_image (and.left Hg1)) with x1 Hx1g1, -- cases Hx1g1 with x1 Hx1g1, have Habs : pi_subgroup (pred_p p) U C ∧ is_finsubg_prop G U, from begin apply and.intro, rewrite ↑pi_subgroup, apply (and.intro sorry pgrpU), exact sgU end, have HeqBU : U = B, from (maxsetsup _ _ _ HmaxB Habs sBU), have H1 : p1 * card B = card B, from eq.symm (eq.subst HeqBU HcardU), have Hp1one : p1 = 1, from (eq_one_of_mul_eq_self_left HBpos H1), apply not_prime_one, exact(eq.subst Hp1one Hprimep1) end ) ) -- have sylS P: P \in S -> p.-Sylow('N_G(P)) P. lemma sylS (P : finset G) : maxp A P → is_sylow p P (normalizer_in P A) := assume HmaxP, sorry local attribute perm.f [coercion] check λ g, action_by_conj_on_finsets g print subtype.tag definition pre_conjG (g : G) (s : (S A)) : finset G := (action_by_conj_on_finsets g (elt_of (elt_of s))) lemma pre_conjG_in_S (g : G) (s : S A) : maxp A (pre_conjG A g s) := have HmaxS : maxp A (elt_of (elt_of s)), from has_property s, begin apply (iff.elim_right maxSet_iff), intro B HsB, apply iff.intro, apply sorry, apply sorry end -- (λ (B : finset G), pi_subgroup (pred_p p) B A ∧ is_finsubg_prop G B) A -- (pre_conjG A g s) definition conjG_hom (g : G) (s : S A) : _ := tag (pre_conjG A g s) (pre_conjG_in_S A g s) -- definition conjG (g : G) : perm (S A) := perm.mk (λ s, action_by_conj_on_finsets g s) (action_by_conj_on_finsets_inj) -- -- have{SmaxN} defCS P: P \in S -> 'Fix_(S |'JG)(P) = [set P]. -- lemma defCS (P : finset G) : maxp A P → fixed_points conjG (S A) = insert P empty := sorry end SylowTheorem end group_theory
21e70936791461ac056fbebcc215849e3bf2e97a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/sizeof2.lean
c6a0b88a5dfc5979c00d19168d7dda4c2838f27b
[ "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
435
lean
open tactic example : sizeof (λ a : nat, a) = 0 := rfl example : sizeof Type = 0 := rfl example : sizeof Prop = 0 := rfl example (p : Prop) (H : p) : sizeof H = 0 := rfl example (A : Type) (a b : A) : sizeof [a, b] = 3 := rfl example : sizeof [(1:nat), 4] = 8 := rfl example : sizeof [tt, ff, tt] = 7 := rfl set_option pp.implicit true check sizeof Prop check sizeof [tt, ff, tt] check λ (A : Type) (a b : A), sizeof [a, b]
87235e364f716c097b2edf25a7cc0f5c5ac0c570
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/sites/closed.lean
2a3ef6114eee2d1176f63368be83f124b4ef9e2f
[ "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
12,141
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.sheaf_of_types import order.closure /-! # Closed sieves A natural closure operator on sieves is a closure operator on `sieve X` for each `X` which commutes with pullback. We show that a Grothendieck topology `J` induces a natural closure operator, and define what the closed sieves are. The collection of `J`-closed sieves forms a presheaf which is a sheaf for `J`, and further this presheaf can be used to determine the Grothendieck topology from the sheaf predicate. Finally we show that a natural closure operator on sieves induces a Grothendieck topology, and hence that natural closure operators are in bijection with Grothendieck topologies. ## Main definitions * `category_theory.grothendieck_topology.close`: Sends a sieve `S` on `X` to the set of arrows which it covers. This has all the usual properties of a closure operator, as well as commuting with pullback. * `category_theory.grothendieck_topology.closure_operator`: The bundled `closure_operator` given by `category_theory.grothendieck_topology.close`. * `category_theory.grothendieck_topology.closed`: A sieve `S` on `X` is closed for the topology `J` if it contains every arrow it covers. * `category_theory.functor.closed_sieves`: The presheaf sending `X` to the collection of `J`-closed sieves on `X`. This is additionally shown to be a sheaf for `J`, and if this is a sheaf for a different topology `J'`, then `J' ≤ J`. * `category_theory.grothendieck_topology.topology_of_closure_operator`: A closure operator on the set of sieves on every object which commutes with pullback additionally induces a Grothendieck topology, giving a bijection with `category_theory.grothendieck_topology.closure_operator`. ## Tags closed sieve, closure, Grothendieck topology ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables (J₁ J₂ : grothendieck_topology C) namespace grothendieck_topology /-- The `J`-closure of a sieve is the collection of arrows which it covers. -/ @[simps] def close {X : C} (S : sieve X) : sieve X := { arrows := λ Y f, J₁.covers S f, downward_closed' := λ Y Z f hS, J₁.arrow_stable _ _ hS } /-- Any sieve is smaller than its closure. -/ lemma le_close {X : C} (S : sieve X) : S ≤ J₁.close S := λ Y g hg, J₁.covering_of_eq_top (S.pullback_eq_top_of_mem hg) /-- A sieve is closed for the Grothendieck topology if it contains every arrow it covers. In the case of the usual topology on a topological space, this means that the open cover contains every open set which it covers. Note this has no relation to a closed subset of a topological space. -/ def is_closed {X : C} (S : sieve X) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X), J₁.covers S f → S f /-- If `S` is `J₁`-closed, then `S` covers exactly the arrows it contains. -/ lemma covers_iff_mem_of_closed {X : C} {S : sieve X} (h : J₁.is_closed S) {Y : C} (f : Y ⟶ X) : J₁.covers S f ↔ S f := ⟨h _, J₁.arrow_max _ _⟩ /-- Being `J`-closed is stable under pullback. -/ lemma is_closed_pullback {X Y : C} (f : Y ⟶ X) (S : sieve X) : J₁.is_closed S → J₁.is_closed (S.pullback f) := λ hS Z g hg, hS (g ≫ f) (by rwa [J₁.covers_iff, sieve.pullback_comp]) /-- The closure of a sieve `S` is the largest closed sieve which contains `S` (justifying the name "closure"). -/ lemma le_close_of_is_closed {X : C} {S T : sieve X} (h : S ≤ T) (hT : J₁.is_closed T) : J₁.close S ≤ T := λ Y f hf, hT _ (J₁.superset_covering (sieve.pullback_monotone f h) hf) /-- The closure of a sieve is closed. -/ lemma close_is_closed {X : C} (S : sieve X) : J₁.is_closed (J₁.close S) := λ Y g hg, J₁.arrow_trans g _ S hg (λ Z h hS, hS) /-- The sieve `S` is closed iff its closure is equal to itself. -/ lemma is_closed_iff_close_eq_self {X : C} (S : sieve X) : J₁.is_closed S ↔ J₁.close S = S := begin split, { intro h, apply le_antisymm, { intros Y f hf, rw ← J₁.covers_iff_mem_of_closed h, apply hf }, { apply J₁.le_close } }, { intro e, rw ← e, apply J₁.close_is_closed } end lemma close_eq_self_of_is_closed {X : C} {S : sieve X} (hS : J₁.is_closed S) : J₁.close S = S := (J₁.is_closed_iff_close_eq_self S).1 hS /-- Closing under `J` is stable under pullback. -/ lemma pullback_close {X Y : C} (f : Y ⟶ X) (S : sieve X) : J₁.close (S.pullback f) = (J₁.close S).pullback f := begin apply le_antisymm, { refine J₁.le_close_of_is_closed (sieve.pullback_monotone _ (J₁.le_close S)) _, apply J₁.is_closed_pullback _ _ (J₁.close_is_closed _) }, { intros Z g hg, change _ ∈ J₁ _, rw ← sieve.pullback_comp, apply hg } end @[mono] lemma monotone_close {X : C} : monotone (J₁.close : sieve X → sieve X) := λ S₁ S₂ h, J₁.le_close_of_is_closed (h.trans (J₁.le_close _)) (J₁.close_is_closed S₂) @[simp] lemma close_close {X : C} (S : sieve X) : J₁.close (J₁.close S) = J₁.close S := le_antisymm (J₁.le_close_of_is_closed le_rfl (J₁.close_is_closed S)) (J₁.monotone_close (J₁.le_close _)) /-- The sieve `S` is in the topology iff its closure is the maximal sieve. This shows that the closure operator determines the topology. -/ lemma close_eq_top_iff_mem {X : C} (S : sieve X) : J₁.close S = ⊤ ↔ S ∈ J₁ X := begin split, { intro h, apply J₁.transitive (J₁.top_mem X), intros Y f hf, change J₁.close S f, rwa h }, { intro hS, rw eq_top_iff, intros Y f hf, apply J₁.pullback_stable _ hS } end /-- A Grothendieck topology induces a natural family of closure operators on sieves. -/ @[simps {rhs_md := semireducible}] def closure_operator (X : C) : closure_operator (sieve X) := closure_operator.mk' J₁.close (λ S₁ S₂ h, J₁.le_close_of_is_closed (h.trans (J₁.le_close _)) (J₁.close_is_closed S₂)) J₁.le_close (λ S, J₁.le_close_of_is_closed le_rfl (J₁.close_is_closed S)) @[simp] lemma closed_iff_closed {X : C} (S : sieve X) : S ∈ (J₁.closure_operator X).closed ↔ J₁.is_closed S := (J₁.is_closed_iff_close_eq_self S).symm end grothendieck_topology /-- The presheaf sending each object to the set of `J`-closed sieves on it. This presheaf is a `J`-sheaf (and will turn out to be a subobject classifier for the category of `J`-sheaves). -/ @[simps] def functor.closed_sieves : Cᵒᵖ ⥤ Type (max v u) := { obj := λ X, {S : sieve X.unop // J₁.is_closed S}, map := λ X Y f S, ⟨S.1.pullback f.unop, J₁.is_closed_pullback f.unop _ S.2⟩ } /-- The presheaf of `J`-closed sieves is a `J`-sheaf. The proof of this is adapted from [MM92], Chatper III, Section 7, Lemma 1. -/ lemma classifier_is_sheaf : presieve.is_sheaf J₁ (functor.closed_sieves J₁) := begin intros X S hS, rw ← presieve.is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, refine ⟨_, _⟩, { rintro x ⟨M, hM⟩ ⟨N, hN⟩ hM₂ hN₂, ext, dsimp only [subtype.coe_mk], rw [← J₁.covers_iff_mem_of_closed hM, ← J₁.covers_iff_mem_of_closed hN], have q : ∀ ⦃Z : C⦄ (g : Z ⟶ X) (hg : S g), M.pullback g = N.pullback g, { intros Z g hg, apply congr_arg subtype.val ((hM₂ g hg).trans (hN₂ g hg).symm) }, have MSNS : M ⊓ S = N ⊓ S, { ext Z g, rw [sieve.inter_apply, sieve.inter_apply, and_comm (N g), and_comm], apply and_congr_right, intro hg, rw [sieve.pullback_eq_top_iff_mem, sieve.pullback_eq_top_iff_mem, q g hg] }, split, { intro hf, rw J₁.covers_iff, apply J₁.superset_covering (sieve.pullback_monotone f inf_le_left), rw ← MSNS, apply J₁.arrow_intersect f M S hf (J₁.pullback_stable _ hS) }, { intro hf, rw J₁.covers_iff, apply J₁.superset_covering (sieve.pullback_monotone f inf_le_left), rw MSNS, apply J₁.arrow_intersect f N S hf (J₁.pullback_stable _ hS) } }, { intros x hx, rw presieve.compatible_iff_sieve_compatible at hx, let M := sieve.bind S (λ Y f hf, (x f hf).1), have : ∀ ⦃Y⦄ (f : Y ⟶ X) (hf : S f), M.pullback f = (x f hf).1, { intros Y f hf, apply le_antisymm, { rintro Z u ⟨W, g, f', hf', (hg : (x f' hf').1 _), c⟩, rw [sieve.pullback_eq_top_iff_mem, ←(show (x (u ≫ f) _).1 = (x f hf).1.pullback u, from congr_arg subtype.val (hx f u hf))], simp_rw ← c, rw (show (x (g ≫ f') _).1 = _, from congr_arg subtype.val (hx f' g hf')), apply sieve.pullback_eq_top_of_mem _ hg }, { apply sieve.le_pullback_bind S (λ Y f hf, (x f hf).1) } }, refine ⟨⟨_, J₁.close_is_closed M⟩, _⟩, { intros Y f hf, ext1, dsimp, rw [← J₁.pullback_close, this _ hf], apply le_antisymm (J₁.le_close_of_is_closed le_rfl (x f hf).2) (J₁.le_close _) } }, end /-- If presheaf of `J₁`-closed sieves is a `J₂`-sheaf then `J₁ ≤ J₂`. Note the converse is true by `classifier_is_sheaf` and `is_sheaf_of_le`. -/ lemma le_topology_of_closed_sieves_is_sheaf {J₁ J₂ : grothendieck_topology C} (h : presieve.is_sheaf J₁ (functor.closed_sieves J₂)) : J₁ ≤ J₂ := λ X S hS, begin rw ← J₂.close_eq_top_iff_mem, have : J₂.is_closed (⊤ : sieve X), { intros Y f hf, trivial }, suffices : (⟨J₂.close S, J₂.close_is_closed S⟩ : subtype _) = ⟨⊤, this⟩, { rw subtype.ext_iff at this, exact this }, apply (h S hS).is_separated_for.ext, { intros Y f hf, ext1, dsimp, rw [sieve.pullback_top, ← J₂.pullback_close, S.pullback_eq_top_of_mem hf, J₂.close_eq_top_iff_mem], apply J₂.top_mem }, end /-- If being a sheaf for `J₁` is equivalent to being a sheaf for `J₂`, then `J₁ = J₂`. -/ lemma topology_eq_iff_same_sheaves {J₁ J₂ : grothendieck_topology C} : J₁ = J₂ ↔ (∀ (P : Cᵒᵖ ⥤ Type (max v u)), presieve.is_sheaf J₁ P ↔ presieve.is_sheaf J₂ P) := begin split, { rintro rfl, intro P, refl }, { intro h, apply le_antisymm, { apply le_topology_of_closed_sieves_is_sheaf, rw h, apply classifier_is_sheaf }, { apply le_topology_of_closed_sieves_is_sheaf, rw ← h, apply classifier_is_sheaf } } end /-- A closure (increasing, inflationary and idempotent) operation on sieves that commutes with pullback induces a Grothendieck topology. In fact, such operations are in bijection with Grothendieck topologies. -/ @[simps] def topology_of_closure_operator (c : Π (X : C), closure_operator (sieve X)) (hc : Π ⦃X Y : C⦄ (f : Y ⟶ X) (S : sieve X), c _ (S.pullback f) = (c _ S).pullback f) : grothendieck_topology C := { sieves := λ X, {S | c X S = ⊤}, top_mem' := λ X, top_unique ((c X).le_closure _), pullback_stable' := λ X Y S f hS, begin rw set.mem_set_of_eq at hS, rw [set.mem_set_of_eq, hc, hS, sieve.pullback_top], end, transitive' := λ X S hS R hR, begin rw set.mem_set_of_eq at hS, rw [set.mem_set_of_eq, ←(c X).idempotent, eq_top_iff, ←hS], apply (c X).monotone (λ Y f hf, _), rw [sieve.pullback_eq_top_iff_mem, ←hc], apply hR hf, end } /-- The topology given by the closure operator `J.close` on a Grothendieck topology is the same as `J`. -/ lemma topology_of_closure_operator_self : topology_of_closure_operator J₁.closure_operator (λ X Y, J₁.pullback_close) = J₁ := begin ext X S, apply grothendieck_topology.close_eq_top_iff_mem, end lemma topology_of_closure_operator_close (c : Π (X : C), closure_operator (sieve X)) (pb : Π ⦃X Y : C⦄ (f : Y ⟶ X) (S : sieve X), c Y (S.pullback f) = (c X S).pullback f) (X : C) (S : sieve X) : (topology_of_closure_operator c pb).close S = c X S := begin ext, change c _ (sieve.pullback f S) = ⊤ ↔ c _ S f, rw [pb, sieve.pullback_eq_top_iff_mem], end end category_theory
250e95a101d7a5a8bef92c0967ba97823d64a8cc
de8d0cdc3dc15aa390280472764229d0e14e734c
/src/metric_spaces.lean
992d59cbaa7e427c5b962a346747e36b3eb95a38
[]
no_license
amesnard0/lean-topology
94720ccf0af34961b24b52b96bcfb19df5c8f544
e8f6a720c435cb59d098579a26f6eb70ea05f91a
refs/heads/main
1,682,525,569,376
1,622,116,766,000
1,622,116,766,000
358,047,823
0
0
null
null
null
null
UTF-8
Lean
false
false
6,647
lean
import tactic import data.set.finite import data.real.basic import topological_spaces import neighbourhoods import topological_spaces2 import t2_spaces noncomputable theory open set -- Definition d'un espace métrique : class metric_space (X : Type) := (dist : X → X → ℝ) (dist_eq_zero_iff : ∀ x y, dist x y = 0 ↔ x = y) (dist_symm : ∀ x y, dist x y = dist y x) (triangle : ∀ x y z, dist x z ≤ dist x y + dist y z) namespace metric_space open topological_space -- Preuve que la distance est positive à partir des autres axiomes : lemma dist_nonneg {X : Type} [metric_space X] (x y : X) : 0 ≤ dist x y := begin have := calc 0 = dist x x : by rw (dist_eq_zero_iff x x).2 rfl ... ≤ dist x y + dist y x : triangle x y x ... = dist x y + dist x y : by rw dist_symm x y ... = 2 * dist x y : by linarith, linarith, end -- Topologie induite par la distance : instance {X : Type} [metric_space X] : topological_space X := generate_from X { B | ∃ (x : X) r, B = {y | dist x y < r} } -- Caractérisation des ouverts pour la distance : lemma is_open_metric_iff {X : Type} [metric_space X] {U : set X}: is_open U ↔ ∀ x ∈ U, ∃ r > 0, {y | dist x y < r} ⊆ U := begin split, { intro hyp, intros x hx, induction hyp with G hG A B hA1 hB1 hA2 hB2 C hC1 hC2, { rcases hG with ⟨xG, r, hG⟩, rw hG at hx, simp at hx, use [r - dist xG x, by linarith [hx]], intros y hy, simp at hy, rw hG, calc dist xG y ≤ dist xG x + dist x y : triangle xG x y ... < dist xG x + r - dist xG x : by linarith [hy] ... = r : by linarith, }, { rcases hA2 hx.1 with ⟨r1, hr1, hA⟩, rcases hB2 hx.2 with ⟨r2, hr2, hB⟩, use min r1 r2, split, exact lt_min hr1 hr2, intros y hy, split, apply hA, calc dist x y < min r1 r2 : hy ... ≤ r1 : min_le_left r1 r2, apply hB, calc dist x y < min r1 r2 : hy ... ≤ r2 : min_le_right r1 r2, }, { rcases hx with ⟨c, hcC, hxc⟩, rcases hC2 c hcC hxc with ⟨r, hr, hc⟩, use [r, hr], intros y hy, use [c, hcC, hc hy], }, { use [1, by linarith], simp, }, }, { intro hyp, choose φ hφ using hyp, have clef : U = ⋃₀ { ({y : X | dist x y < φ x H}) | (x : X) (H : x ∈ U) }, { apply le_antisymm, { intros x hx, use {y : X | dist x y < φ x hx}, split, use [x, hx], specialize hφ x hx, rw exists_prop at hφ, calc dist x x = 0 : (dist_eq_zero_iff x x).2 rfl ... < φ x hx : by linarith [hφ.1], }, { apply sUnion_subset, rintros B ⟨x, hx, hB⟩, rw ← hB, specialize hφ x hx, rw exists_prop at hφ, exact hφ.2, }, }, rw clef, apply union, rintros B ⟨x, hx, hB⟩, rw ← hB, apply generated_open.generator, use [x, φ x hx], }, end end metric_space open topological_space open metric_space -- Espace métrique ℝ : instance metric_space_R : metric_space ℝ := { dist := λ x y, abs (x - y), dist_eq_zero_iff := begin intros x y, split, intro hyp, linarith [abs_eq_zero.1 hyp], intro hyp, simp [hyp], end, dist_symm := abs_sub, triangle := begin intros x y z, have clef : x - z = (x - y) + (y - z), linarith, calc abs (x - z) = abs ((x - y) + (y - z)) : by simp [clef] ... ≤ abs (x - y) + abs (y - z) : abs_add _ _, end } -- Produit de deux espaces métriques : instance prod.metric_space (X Y : Type) [metric_space X] [metric_space Y] : metric_space (X × Y) := { dist := λ u v, max (dist u.fst v.fst) (dist u.snd v.snd), dist_eq_zero_iff := begin intros u v, split, { intro hyp, have := dist_nonneg u.fst v.fst, have := dist_nonneg u.snd v.snd, have := max_le_iff.1 (le_of_eq hyp), ext; rw ← dist_eq_zero_iff; linarith, }, { intro hyp, rw [hyp, (dist_eq_zero_iff _ _).mpr, (dist_eq_zero_iff _ _).mpr, max_self]; refl }, end, dist_symm := begin intros u v, rw [dist_symm u.fst v.fst, dist_symm u.snd v.snd], end, triangle := begin intros u v w, have := triangle u.fst v.fst w.fst, have := triangle u.snd v.snd w.snd, unfold max, split_ifs; linarith, end } -- Tout espace métrique est séparé : instance metric_t2 {X : Type} [metric_space X] : t2_space X := { t2 := begin intros x y hxy, let r := dist x y, have r_strict_pos : r > 0, { cases le_or_gt r 0 with h1 h2, exfalso, exact hxy ((dist_eq_zero_iff x y).1 (le_antisymm h1 (dist_nonneg x y))), exact h2, }, let Ux := {z : X | dist x z < r/2}, let Uy := {z : X | dist y z < r/2}, use [Ux, Uy], repeat {split}, apply generated_open.generator, use [x, r/2], apply generated_open.generator, use [y, r/2], calc dist x x = 0 : (dist_eq_zero_iff x x).2 rfl ... < r/2 : by linarith, calc dist y y = 0 : (dist_eq_zero_iff y y).2 rfl ... < r/2 : by linarith, apply le_antisymm, { rintros z ⟨ hzUx, hzUy ⟩, have hxz : dist x z < r/2, exact hzUx, have hyz : dist y z < r/2, exact hzUy, have := calc dist x y ≤ dist x z + dist z y : triangle x z y ... = dist x z + dist y z : by linarith [dist_symm y z] ... < r/2 + r/2 : by linarith [hxz, hyz] ... = r : by linarith, linarith, }, { intros x hx, exfalso, exact hx, }, end } -- Convergence d'une suite dans un espace métrique : lemma seq_lim_metric {X : Type} [metric_space X] (u : ℕ → X) (l : X) : seq_lim u l ↔ ∀ ε > 0, ∃ (N : ℕ), ∀ n ≥ N, dist (u n) l < ε := begin split, { intro hyp, intros ε εpos, let V := { x | dist l x < ε }, have hV : V ∈ neighbourhoods l, { apply generated_filter.generator, split, apply generated_open.generator, use [l, ε], calc dist l l = 0 : (dist_eq_zero_iff l l).2 rfl ... < ε : by linarith [εpos], }, cases hyp V hV with N hN, use N, intros n hn, calc dist (u n) l = dist l (u n) : dist_symm (u n) l ... < ε : hN n hn, }, { intro hyp, intros V hV, rcases (is_neighbourhood_iff l).1 hV with ⟨U, hU, hlU, hUV⟩, rcases is_open_metric_iff.1 hU l hlU with ⟨ε, εpos, H⟩, cases hyp ε εpos with N hN, use N, intros n hn, apply hUV, apply H, calc dist l (u n) = dist (u n) l : dist_symm l (u n) ... < ε : hN n hn, }, end
e3477ae4d766a8fd81af69689e7f36b0fb1e0741
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/big_operators/basic.lean
7bfe0bade8f9a3dd9af72bb1f3af7852abc5f7bb
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
62,069
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) ## Implementation Notes The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. -/ universes u v w variables {β : Type u} {α : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs : s.nodup) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = s.fold (*) 1 f := rfl @[simp] lemma sum_multiset_singleton (s : finset α) : s.sum (λ x, {x}) = s.val := by simp only [sum_eq_multiset_sum, multiset.sum_map_singleton] end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [non_assoc_semiring β] [non_assoc_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s @[to_additive] lemma monoid_hom.coe_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ -- See also `finset.prod_apply`, with the same conclusion -- but with the weaker hypothesis `f : α → β → γ`. @[simp, to_additive] lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} namespace finset section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100, to_additive] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀ x ∈ s, ∀ y ∈ s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀ x ∈ s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm end comm_monoid end finset section open finset variables [fintype α] [decidable_eq α] [comm_monoid β] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl end namespace finset section comm_monoid variables [comm_monoid β] @[to_additive] lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl_compl.prod_mul_prod f @[to_additive] lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := is_compl_compl.symm.prod_mul_prod f @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bUnion_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀ y ∈ s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀ y ∈ s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bUnion s t), from (disjoint_bUnion_right _ _ _).mpr this, by simp only [bUnion_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bUnion, prod_bUnion], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λ a, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : Π a, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀ c ∈ s, f (g c) = ∏ x in s.filter (λ c', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀ a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀ x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λ x, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a := begin haveI := classical.dec_eq α, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, prod_eq_single_of_mem a this h₀) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; let s' := ({a, b} : finset α), have hu : s' ⊆ s, { refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb }, have hf : ∀ c ∈ s, c ∉ s' → f c = 1, { intros c hc hcs, apply h₀ c hc, apply not_or_distrib.mp, intro hab, apply hcs, apply mem_insert.mpr, rw mem_singleton, exact hab }, rw ←prod_subset hu hf, exact finset.prod_pair hn end @[to_additive] lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s, { exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ }, { rw [hb h₂, mul_one], apply prod_eq_single_of_mem a h₁, exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ }, { rw [ha h₁, one_mul], apply prod_eq_single_of_mem b h₂, exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ }, { rw [ha h₁, hb h₂, mul_one], exact trans (prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩)) prod_const_one } end @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_finset_coe (f : α → β) (s : finset α) : ∏ (i : (s : set α)), f i = ∏ i in s, f i := prod_attach @[to_additive] lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → β) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, by { substI p, rw [←prod_finset_coe], congr } @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀ x ∈ s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) := by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] } @[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) := by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa } @[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) := by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h } @[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) := by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h } @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp, to_additive] lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β): (∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x := by { split_ifs with h; refl } @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (i_inj : ∀ a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, ∃ a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (j : Π a ∈ t, α) (hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, f a ≠ 1 → γ) (hi : ∀ a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀ a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, g b ≠ 1 → ∃ a h₁ h₂, b = i a h₁ h₂) (h : ∀ a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λ x, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λ x, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λ h₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λ h₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma prod_dite_of_false {p : α → Prop} {hp : decidable_pred p} (h : ∀ x ∈ s, ¬ p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = ∏ (x : s), g x.val (h x.val x.property) := prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_neg }) (λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩) @[to_additive] lemma prod_dite_of_true {p : α → Prop} {hp : decidable_pred p} (h : ∀ x ∈ s, p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = ∏ (x : s), f x.val (h x.val x.property) := prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_pos }) (λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩) @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃ a ∈ s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end @[to_additive] lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = f n * ∏ x in range n, f x := by rw [range_succ, prod_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n := by simp only [mul_comm, prod_range_succ_comm] @[to_additive] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := prod_range_succ _ _ | (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ] @[to_additive] lemma eventually_constant_prod {u : ℕ → β} {N : ℕ} (hu : ∀ n ≥ N, u n = 1) {n : ℕ} (hn : N ≤ n) : ∏ k in range (n + 1), u k = ∏ k in range (N + 1), u k := begin obtain ⟨m, rfl : n = N + m⟩ := le_iff_exists_add.mp hn, clear hn, induction m with m hm, { simp }, erw [prod_range_succ, hm], simp [hu] end @[to_additive] lemma prod_range_add (f : ℕ → β) (n m : ℕ) : ∏ x in range (n + m), f x = (∏ x in range n, f x) * (∏ x in range m, f (n + x)) := begin induction m with m hm, { simp }, { rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], }, end @[to_additive] lemma prod_range_add_div_prod_range {α : Type*} [comm_group α] (f : ℕ → α) (n m : ℕ) : (∏ k in range (n + m), f k) / (∏ k in range n, f k) = ∏ k in finset.range m, f (n + k) := div_eq_of_eq_mul' (prod_range_add f n m) @[to_additive] lemma prod_range_zero (f : ℕ → β) : ∏ k in range 0, f k = 1 := by rw [range_zero, prod_empty] @[to_additive sum_range_one] lemma prod_range_one (f : ℕ → β) : ∏ k in range 1, f k = f 0 := by { rw [range_one], apply @prod_singleton β ℕ 0 f } open multiset lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, intros a s ih, simp only [prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end lemma sum_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [add_comm_monoid M] (f : α → M) : (s.map f).sum = ∑ m in s.to_finset, s.count m • f m := @prod_multiset_map_count _ _ _ (multiplicative M) _ f attribute [to_additive] prod_multiset_map_count @[to_additive] lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } @[to_additive] lemma prod_mem_multiset [decidable_eq α] (m : multiset α) (f : {x // x ∈ m} → β) (g : α → β) (hfg : ∀ x, f x = g x) : ∏ (x : {x // x ∈ m}), f x = ∏ x in m.to_finset, g x := prod_bij (λ x _, x.1) (λ x _, multiset.mem_to_finset.mpr x.2) (λ _ _, hfg _) (λ _ _ _ _ h, by { ext, assumption }) (λ y hy, ⟨⟨y, multiset.mem_to_finset.mp hy⟩, finset.mem_univ _, rfl⟩) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty]) (multiset.forall_mem_map_iff.mpr p_s) /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f n /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b | 0 := by simp | (n+1) := by simp lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : ∏ x in s, f x ^ n = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) @[to_additive] lemma prod_flip {n : ℕ} (f : ℕ → β) : ∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n)], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x := by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] } @[to_additive] lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i := by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] } @[to_additive] lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i := prod_eq_mul_prod_diff_singleton (mem_univ a) f @[to_additive] lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (∏ i in {a}ᶜ, f i) * f a := prod_eq_prod_diff_singleton_mul (mem_univ a) f /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λ j hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ @[to_additive eq_of_card_le_one_of_sum_eq "If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum."] lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- Taking a product over `s : finset α` is the same as multiplying the value on a single element `f a` by the product of `s.erase a`. -/ @[to_additive "Taking a sum over `s : finset α` is the same as adding the value on a single element `f a` to the the sum over `s.erase a`."] lemma mul_prod_erase [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : f a * (∏ x in s.erase a, f x) = ∏ x in s, f x := by rw [← prod_insert (not_mem_erase a s), insert_erase h] /-- A variant of `finset.mul_prod_erase` with the multiplication swapped. -/ @[to_additive "A variant of `finset.add_sum_erase` with the addition swapped."] lemma prod_erase_mul [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : (∏ x in s.erase a, f x) * f a = ∏ x in s, f x := by rw [mul_comm, mul_prod_erase s f h] /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _), rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n • (f x)) = n • ((∑ x in s, f x)) := @prod_pow (multiplicative β) _ _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card • b := @prod_const (multiplicative β) _ _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀ x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [non_assoc_semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card • (f b) := @prod_comp (multiplicative β) _ _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma eq_sum_range_sub [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = f 0 + ∑ i in range n, (f (i+1) - f i) := by { rw finset.sum_range_sub, abel } lemma eq_sum_range_sub' [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = ∑ i in range (n + 1), if i = 0 then f 0 else f i - f (i - 1) := begin conv_lhs { rw [finset.eq_sum_range_sub f] }, simp [finset.sum_range_succ', add_comm] end section opposite open opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _ end opposite section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := (monoid_hom.map_prod (comm_group.inv_monoid_hom : β →* β) f s).symm end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma gsmul_sum (α β : Type) [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := add_monoid_hom.map_sum (gsmul_add_group_hom z : β →+ β) f s @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib) section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by { haveI := classical.dec_eq α, rw [←prod_erase_mul _ _ ha, h, mul_zero] } lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃ a ∈ s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel' h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero @[to_additive] lemma prod_unique_nonempty {α β : Type*} [comm_monoid β] [unique α] (s : finset α) (f : α → β) (h : s.nonempty) : (∏ x in s, f x) = f (default α) := begin obtain ⟨a, ha⟩ := h, have : s = {a}, { ext b, simpa [subsingleton.elim a b] using ha }, rw [this, finset.prod_singleton, subsingleton.elim a (default α)] end end finset namespace fintype open finset /-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`. See `function.bijective.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts `function.bijective`. See `function.bijective.sum_comp` for a version without `h`. "] lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bij (λ x _, e x) (λ x _, mem_univ (e x)) (λ x _, h x) (λ x x' _ _ h, he.injective h) (λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩) /-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that automatically fills in most arguments. See `equiv.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that automatically fills in most arguments. See `equiv.sum_comp` for a version without `h`. "] lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bijective e e.bijective f g h @[to_additive] lemma prod_finset_coe [comm_monoid β] : ∏ (i : (s : set α)), f i = ∏ i in s, f i := (finset.prod_subtype s (λ _, iff.rfl) f).symm @[to_additive] lemma prod_unique {α β : Type*} [comm_monoid β] [unique α] (f : α → β) : (∏ x : α, f x) = f (default α) := by rw [univ_unique, prod_singleton] @[to_additive] lemma prod_subsingleton {α β : Type*} [comm_monoid β] [subsingleton α] (f : α → β) (a : α) : (∏ x : α, f x) = f a := begin haveI : unique α := unique_of_subsingleton a, convert prod_unique f end end fintype namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a • {a}) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s • {b}), { rw [count_nsmul, count_singleton_self, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_nsmul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), a ∈ s → k ∣ multiset.count a s) : ∃ (u : multiset α), s = k • u := begin use ∑ a in s.to_finset, (s.count a / k) • {a}, have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • ({x} : multiset α) = ∑ (x : α) in s.to_finset, count x s • {x}, { apply finset.sum_congr rfl, intros x hx, rw [← mul_nsmul, nat.mul_div_cancel' (h x (mem_to_finset.mp hx))] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq] end end multiset @[simp, norm_cast] lemma nat.cast_sum [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s @[simp, norm_cast] lemma int.cast_sum [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := (int.cast_add_hom β).map_sum f s @[simp, norm_cast] lemma nat.cast_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.cast_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _ lemma nat_abs_sum_le {ι : Type*} (s : finset ι) (f : ι → ℤ) : (∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, int.nat_abs_zero] }, { intros i s his IH, simp only [his, finset.sum_insert, not_false_iff], exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) } end
946b40157ddacfed557aa75e4c2ed6de77993280
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/tools/super/splitting.lean
6a781ed42a140f36f325020783651d5b8562e15d
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,664
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .prover_state open monad expr list tactic namespace super private meta def find_components : list expr → list (list (expr × ℕ)) → list (list (expr × ℕ)) | (e::es) comps := let (contain_e, do_not_contain_e) := partition (λc : list (expr × ℕ), c.exists_ $ λf, (abstract_local f.1 e.local_uniq_name).has_var) comps in find_components es $ list.join contain_e :: do_not_contain_e | _ comps := comps meta def get_components (hs : list expr) : list (list expr) := (find_components hs (hs.zip_with_index.map $ λh, [h])).map $ λc, (sort_on (λh : expr × ℕ, h.2) c).map $ λh, h.1 meta def extract_assertions : clause → prover (clause × list expr) | c := if c.num_lits = 0 then return (c, []) else if c.num_quants ≠ 0 then do qf ← c.open_constn c.num_quants, qf_wo_as ← extract_assertions qf.1, return (qf_wo_as.1.close_constn qf.2, qf_wo_as.2) else do hd ← return $ c.get_lit 0, hyp_opt ← get_sat_hyp_core hd.formula hd.is_neg, match hyp_opt with | some h := do wo_as ← extract_assertions (c.inst h), return (wo_as.1, h :: wo_as.2) | _ := do op ← c.open_const, op_wo_as ← extract_assertions op.1, return (op_wo_as.1.close_const op.2, op_wo_as.2) end meta def mk_splitting_clause' (empty_clause : clause) : list (list expr) → tactic (list expr × expr) | [] := return ([], empty_clause.proof) | ([p] :: comps) := do p' ← mk_splitting_clause' comps, return (p::p'.1, p'.2) | (comp :: comps) := do (hs, p') ← mk_splitting_clause' comps, hnc ← mk_local_def `hnc (imp (pis comp empty_clause.local_false) empty_clause.local_false), p'' ← return $ app hnc (lambdas comp p'), return (hnc::hs, p'') meta def mk_splitting_clause (empty_clause : clause) (comps : list (list expr)) : tactic clause := do (hs, p) ← mk_splitting_clause' empty_clause comps, return $ { empty_clause with proof := p }.close_constn hs @[super.inf] meta def splitting_inf : inf_decl := inf_decl.mk 30 $ take given, do lf ← flip monad.lift state_t.read $ λst, st.local_false, op ← given.c.open_constn given.c.num_binders, if list.bor (given.c.get_lits.map $ λl, (is_local_not lf l.formula).is_some) then return () else let comps := get_components op.2 in if comps.length < 2 then return () else do splitting_clause ← mk_splitting_clause op.1 comps, ass ← collect_ass_hyps splitting_clause, add_sat_clause (splitting_clause.close_constn ass) given.sc.sched_default, remove_redundant given.id [] end super
7215ea2391c8e47f3d1c2728b6bcd3b29f54da19
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/Mbar/pseudo_normed_group.lean
cae07e6a77f614d5cf220192884fca2a4e813813
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
746
lean
import pseudo_normed_group.system_of_complexes import Mbar.Mbar_le universe u noncomputable theory open_locale big_operators nnreal open pseudo_normed_group local attribute [instance] type_pow variables {r' : ℝ≥0} {S : Type u} [fact (0 < r')] [fintype S] {c c₁ c₂ c₃ : ℝ≥0} namespace Mbar instance : profinitely_filtered_pseudo_normed_group_with_Tinv r' (Mbar r' S) := { Tinv := profinitely_filtered_pseudo_normed_group_hom.mk' Mbar.Tinv begin refine ⟨r'⁻¹, λ c, ⟨_, _⟩⟩, { intros x hx, exact Mbar.Tinv_mem_filtration hx }, { exact Mbar_le.continuous_Tinv _ _ _ _ } end, Tinv_mem_filtration := λ c x hx, Mbar.Tinv_mem_filtration hx, .. Mbar.profinitely_filtered_pseudo_normed_group } end Mbar
233c98e5d1c4cabe89f789612da5cdb66e7da93c
952248371e69ccae722eb20bfe6815d8641554a8
/src/additive.lean
1d3de7b11f696aeed17f81bd85d40e19e95e0ed1
[]
no_license
robertylewis/lean_polya
5fd079031bf7114449d58d68ccd8c3bed9bcbc97
1da14d60a55ad6cd8af8017b1b64990fccb66ab7
refs/heads/master
1,647,212,226,179
1,558,108,354,000
1,558,108,354,000
89,933,264
1
2
null
1,560,964,118,000
1,493,650,551,000
Lean
UTF-8
Lean
false
false
9,762
lean
import .datatypes .blackboard -- TODO: maybe more of this can move to datatypes namespace polya section sfcd_to_ineq -- assumes lhs < rhs as exprs. cl*lhs + cr*rhs R 0 ==> ineq_data private meta def mk_ineq_data_of_lhs_rhs (lhs rhs : expr) (cl cr : ℚ) (c : comp) {s} (pf : sum_form_proof s) : Σ l r, ineq_data l r := let c' := if cl > 0 then c else c.reverse, iq := ineq.of_comp_and_slope (c') (slope.some (-cr/cl)) in ⟨lhs, rhs, ⟨iq, ineq_proof.of_sum_form_proof lhs rhs iq pf⟩⟩ meta def sum_form_comp_data.to_ineq_data : sum_form_comp_data → option (Σ lhs rhs, ineq_data lhs rhs) | ⟨⟨sf, spec_comp.eq⟩, prf, _⟩ := none | ⟨sfc, prf, _⟩ := match sfc.sf.get_nonzero_factors with | [(rhs, cr), (lhs, cl)] := if rhs.lt lhs then mk_ineq_data_of_lhs_rhs lhs rhs cl cr (sfc.c.to_comp) prf else mk_ineq_data_of_lhs_rhs rhs lhs cr cl (sfc.c.to_comp) prf | _ := none end meta def sum_form_comp_data.to_eq_data : sum_form_comp_data → option (Σ lhs rhs, eq_data lhs rhs) | ⟨⟨sf, spec_comp.eq⟩, prf, _⟩ := match sf.get_nonzero_factors with | [(rhs, cr), (lhs, cl)] := some ⟨lhs, rhs, ⟨(-cr/cl), eq_proof.of_sum_form_proof _ _ _ prf⟩⟩ | _ := none end | _ := none meta def sum_form_comp_data.to_sign_data : sum_form_comp_data → option Σ e, sign_data e | ⟨sfc, prf, _⟩ := match sfc.sf.get_nonzero_factors with | [(e, n)] := let c := if n < 0 then sfc.c.to_gen_comp.reverse else sfc.c.to_gen_comp in some ⟨e, ⟨c, sign_proof.of_sum_form_proof _ _ prf⟩⟩ --sign_proof.adhoc _ _ (prf.reconstruct >>= tactic.trace, tactic.fail "sum_form_comp_data.to_sign_data not implemented")⟩⟩ | _ := none end end sfcd_to_ineq open native -- assumes the coeff of pvt in both is nonzero. Does not enforce elim_list preservation meta def sum_form_comp_data.elim_expr_aux : sum_form_comp_data → sum_form_comp_data → expr → option sum_form_comp_data | ⟨⟨sf1, c1⟩, prf1, elim_list1⟩ ⟨⟨sf2, c2⟩, prf2, elim_list2⟩ pvt := let cf1 := sf1.get_coeff pvt, cf2 := sf2.get_coeff pvt, fac := (-cf1/cf2) in if (fac > 0) then some ⟨_, sum_form_proof.of_add_factor_same_comp fac prf1 prf2, (rb_set.union elim_list1 elim_list2).insert pvt⟩ else if hce : c1 = spec_comp.eq then some ⟨_, sum_form_proof.of_add_eq_factor_op_comp fac prf2 (by rw ←hce; apply prf1), (rb_set.union elim_list1 elim_list2).insert pvt⟩ else if hce' : c2 = spec_comp.eq then some ⟨_, sum_form_proof.of_add_eq_factor_op_comp fac prf1 (by rw ←hce'; apply prf2), (rb_set.union elim_list1 elim_list2).insert pvt⟩ else none meta def sum_form_comp_data.elim_expr (sfcd1 sfcd2 : sum_form_comp_data) (pvt : expr) : option sum_form_comp_data := if sfcd1.get_coeff pvt = 0 then some ⟨sfcd1.sfc, sfcd1.prf, sfcd1.elim_list.insert pvt⟩ else if sfcd2.get_coeff pvt = 0 then none else sum_form_comp_data.elim_expr_aux sfcd1 sfcd2 pvt meta def sum_form_comp_data.elim_into (sfcd1 sfcd2 : sum_form_comp_data) (pvt : expr) (rv : rb_set sum_form_comp_data) : rb_set sum_form_comp_data := match sfcd1.elim_expr sfcd2 pvt with | none := rv | some sfcd := rv.insert sfcd end /-- Uses sfcd to eliminate the e from all comparisons in cmps, and adds the new comparisons to rv -/ meta def elim_expr_from_comp_data (sfcd : sum_form_comp_data) (cmps : rb_set sum_form_comp_data) (e : expr) (rv : rb_set sum_form_comp_data) : rb_set sum_form_comp_data := cmps.fold rv (λ c rv', sfcd.elim_into c e rv') /-- Eliminates the expression e from all comparisons in cmps in all possible ways -/ meta def elim_expr_from_comp_data_set (cmps : rb_set sum_form_comp_data) (e : expr) : rb_set sum_form_comp_data := cmps.fold mk_rb_set (λ c rv, elim_expr_from_comp_data c cmps e rv) /- /-- Performs all possible eliminations with sfcd on cmps. Returns a set of all new comps, NOT including the old ones. -/ meta def new_exprs_from_comp_data_set (sfcd : sum_form_comp_data) (cmps : rb_set sum_form_comp_data) : rb_set sum_form_comp_data := sfcd.vars.foldr (λ e rv, elim_expr_from_comp_data sfcd cmps e rv) mk_rb_set -/ meta def elim_expr_from_comp_data_list (cmps : list sum_form_comp_data) (e : expr) : list sum_form_comp_data := (elim_expr_from_comp_data_set (rb_map.set_of_list cmps) e).to_list private meta def check_elim_lists_aux (sfcd1 sfcd2 : sum_form_comp_data) : bool := sfcd1.vars.all (λ e, bnot (sfcd2.elim_list.contains e)) private meta def check_elim_lists (sfcd1 sfcd2 : sum_form_comp_data) : bool := check_elim_lists_aux sfcd1 sfcd2 && check_elim_lists_aux sfcd2 sfcd1 meta def sum_form_comp_data.needs_elim_against (sfcd1 sfcd2 : sum_form_comp_data) (e : expr) : bool := (check_elim_lists sfcd1 sfcd2)-- && --(((sfcd1.vars.append sfcd2.vars).filter (λ e' : expr, e'.lt e)).length ≤ 2) -- change back to e' lt e /-- Uses sfcd to eliminate the e from all comparisons in cmps, and adds the new comparisons to rv -/ meta def elim_expr_from_comp_data_filtered (sfcd : sum_form_comp_data) (cmps : rb_set sum_form_comp_data) (e : expr) (rv : rb_set sum_form_comp_data) : rb_set sum_form_comp_data := cmps.fold rv (λ c rv', if sfcd.needs_elim_against c e then sfcd.elim_into c e rv' else rv') /-- Performs all possible eliminations with sfcd on cmps. Returns a set of all new comps, NOT including the old ones. -/ meta def new_exprs_from_comp_data_set (sfcd : sum_form_comp_data) (cmps : rb_set sum_form_comp_data) : rb_set sum_form_comp_data := sfcd.vars.foldr (λ e rv, elim_expr_from_comp_data_filtered sfcd cmps e rv) mk_rb_set meta def elim_list_into_set : rb_set sum_form_comp_data → list sum_form_comp_data → rb_set sum_form_comp_data | cmps [] := cmps | cmps (sfcd::new_cmps) := let sfcdn := sfcd.normalize in if cmps.contains (/-trace_val-/ (new_cmps.length, sfcdn)).2 then elim_list_into_set cmps new_cmps else let new_gen := (new_exprs_from_comp_data_set sfcdn cmps).keys in elim_list_into_set (cmps.insert sfcdn) (new_cmps.append new_gen) meta def elim_list_set (cmps : list sum_form_comp_data) (start : rb_set sum_form_comp_data := mk_rb_set) : rb_set sum_form_comp_data := elim_list_into_set start (trace_val cmps) meta def elim_list (cmps : list sum_form_comp_data) (start : rb_set sum_form_comp_data := mk_rb_set) : list sum_form_comp_data := (elim_list_into_set start cmps).to_list meta def vars_of_sfcd_set (cmps : rb_set sum_form_comp_data) : rb_set expr := cmps.fold mk_rb_set (λ sfcd s, sfcd.vars.foldl rb_set.insert s) def list.first {α} (P : α → bool) : list α → option α | [] := none | (h::t) := if P h then some h else list.first t meta def find_contrad_sfcd_in_sfcd_set (cmps : rb_set sum_form_comp_data) : option sum_form_comp_data := let elimd := (vars_of_sfcd_set cmps).fold cmps (λ s cmps', elim_expr_from_comp_data_set cmps' s) in list.first sum_form_comp_data.is_contr elimd.keys -- dot notation doesn't work here?? meta def find_contrad_sfcd_in_sfcd_list (cmps : list sum_form_comp_data) : option sum_form_comp_data := find_contrad_sfcd_in_sfcd_set (rb_map.set_of_list cmps) meta def find_contrad_in_sfcd_set (cmps : rb_set sum_form_comp_data) : option contrad := do sfcd ← find_contrad_sfcd_in_sfcd_set cmps, return $ contrad.sum_form sfcd.prf meta def find_contrad_in_sfcd_list (cmps : list sum_form_comp_data) : option contrad := find_contrad_in_sfcd_set (rb_map.set_of_list cmps) meta def is_inconsistent (cmps : rb_set sum_form_comp_data) : bool := (find_contrad_sfcd_in_sfcd_set cmps).is_some meta def is_inconsistent_list (cmps : list sum_form_comp_data) : bool := is_inconsistent $ rb_map.set_of_list cmps section bb_process meta def mk_eqs_of_expr_sum_form_pair : expr × sum_form → sum_form_comp_data | (e, sf) := let sf' := sf - (sum_form.of_expr e) in ⟨⟨sf', spec_comp.eq⟩, sum_form_proof.of_expr_def e sf', mk_rb_set⟩ private meta def mk_sfcd_list : polya_state (list sum_form_comp_data) := do il ← get_ineq_list, el ← get_eq_list, sl ← get_sign_list, dfs ← get_add_defs, let il' := il.map (λ ⟨lhs, rhs, id⟩, sum_form_comp_data.of_ineq_data id) in let el' := el.map (λ ⟨_, _, ed⟩, sum_form_comp_data.of_eq_data ed) in let sl' := sl.map (λ ⟨_, sd⟩, sum_form_comp_data.of_sign_data sd) in let dfs' := dfs.map mk_eqs_of_expr_sum_form_pair in return $ (((il'.append el').append sl').append dfs').qsort (λ a b, a < b) private meta def mk_eq_list (cmps : list sum_form_comp_data) : list Σ lhs rhs, eq_data lhs rhs := let il := cmps.map (λ sfcd, sfcd.to_eq_data) in list.reduce_option il private meta def mk_ineq_list (cmps : list sum_form_comp_data) : list Σ lhs rhs, ineq_data lhs rhs := let il := cmps.map (λ sfcd, sfcd.to_ineq_data) in list.reduce_option il private meta def mk_sign_list (cmps : list sum_form_comp_data) : list Σ e, sign_data e := let il := cmps.map (λ sfcd, sfcd.to_sign_data) in list.reduce_option il meta def sum_form.add_new_ineqs (start : rb_set sum_form_comp_data := mk_rb_set) : polya_state (rb_set sum_form_comp_data) := do is_contr ← contr_found, if (/-trace_val-/ ("is_contr", is_contr)).2 then return start else do sfcds ← mk_sfcd_list, let elim_set := elim_list_set sfcds start, let elims := elim_set.to_list, let ineqs := mk_ineq_list elims, let eqs := mk_eq_list elims, let signs := (/-trace_val-/ ("found signs:", mk_sign_list elims)).2, ineqs.mmap' (λ s, add_ineq s.2.2), eqs.mmap' (λ s, add_eq s.2.2), signs.mmap' (λ s, add_sign s.2), return elim_set end bb_process end polya
d2816fd4fdda9063767c75c52fa8d24f76cd70a8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/holor.lean
e47e73adf516912249c7b9ac1d21034965bcef36
[ "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
14,347
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.pi_instances /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universes u open list /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [ring α] : module α (holor α ds) := pi.module α instance [field α] : vector_space α (holor α ds) := ⟨α, holor α ds⟩ /-- The tensor product of two holors. -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) : Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := funext (λ t, by simp [slice]; refl) lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : finset.sum s (λ x, slice (f x) i hid) = slice (finset.sum s f) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : (finset.range d).attach.sum (λ i, unit_vec d i.1 ⊗ slice x i.1 (nat.succ_le_of_lt (finset.mem_range.1 i.2))) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i _), { simp, refl }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b.val, { apply not.imp hbi, { assume h0 : i = b.val, apply subtype.eq, simp only [h0] }, { exact finset.mem_range.2 hid } }, simp [hbi']}, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (finset.sum s f) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (finset.sum s f), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
86ab5d0a0c321db4034cbe2474d20b46dceb712e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/structured_arrow.lean
2b289b795b53bf89effed064f919251cc97f084e
[ "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
16,707
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.punit import category_theory.comma import category_theory.limits.shapes.terminal import category_theory.essentially_small /-! # The category of "structured arrows" For `T : C ⥤ D`, a `T`-structured arrow with source `S : D` is just a morphism `S ⟶ T.obj Y`, for some `Y : C`. These form a category with morphisms `g : Y ⟶ Y'` making the obvious diagram commute. We prove that `𝟙 (T.obj Y)` is the initial object in `T`-structured objects with source `T.obj Y`. -/ namespace category_theory -- morphism levels before object levels. See note [category_theory universes]. universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- The category of `T`-structured arrows with domain `S : D` (here `T : C ⥤ D`), has as its objects `D`-morphisms of the form `S ⟶ T Y`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ @[derive category, nolint has_nonempty_instance] def structured_arrow (S : D) (T : C ⥤ D) := comma (functor.from_punit S) T namespace structured_arrow /-- The obvious projection functor from structured arrows. -/ @[simps] def proj (S : D) (T : C ⥤ D) : structured_arrow S T ⥤ C := comma.snd _ _ variables {S S' S'' : D} {Y Y' : C} {T : C ⥤ D} /-- Construct a structured arrow from a morphism. -/ def mk (f : S ⟶ T.obj Y) : structured_arrow S T := ⟨⟨⟨⟩⟩, Y, f⟩ @[simp] lemma mk_left (f : S ⟶ T.obj Y) : (mk f).left = ⟨⟨⟩⟩ := rfl @[simp] lemma mk_right (f : S ⟶ T.obj Y) : (mk f).right = Y := rfl @[simp] lemma mk_hom_eq_self (f : S ⟶ T.obj Y) : (mk f).hom = f := rfl @[simp, reassoc] lemma w {A B : structured_arrow S T} (f : A ⟶ B) : A.hom ≫ T.map f.right = B.hom := by { have := f.w; tidy } /-- To construct a morphism of structured arrows, we need a morphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps] def hom_mk {f f' : structured_arrow S T} (g : f.right ⟶ f'.right) (w : f.hom ≫ T.map g = f'.hom) : f ⟶ f' := { left := eq_to_hom (by ext), right := g, w' := by { dsimp, simpa using w.symm, }, } /-- Given a structured arrow `X ⟶ F(U)`, and an arrow `U ⟶ Y`, we can construct a morphism of structured arrow given by `(X ⟶ F(U)) ⟶ (X ⟶ F(U) ⟶ F(Y))`. -/ def hom_mk' {F : C ⥤ D} {X : D} {Y : C} (U : structured_arrow X F) (f : U.right ⟶ Y) : U ⟶ mk (U.hom ≫ F.map f) := { right := f } /-- To construct an isomorphism of structured arrows, we need an isomorphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps] def iso_mk {f f' : structured_arrow S T} (g : f.right ≅ f'.right) (w : f.hom ≫ T.map g.hom = f'.hom) : f ≅ f' := comma.iso_mk (eq_to_iso (by ext)) g (by simpa [eq_to_hom_map] using w.symm) lemma ext {A B : structured_arrow S T} (f g : A ⟶ B) : f.right = g.right → f = g := comma_morphism.ext _ _ (subsingleton.elim _ _) lemma ext_iff {A B : structured_arrow S T} (f g : A ⟶ B) : f = g ↔ f.right = g.right := ⟨λ h, h ▸ rfl, ext f g⟩ instance proj_faithful : faithful (proj S T) := { map_injective' := λ X Y, ext } /-- The converse of this is true with additional assumptions, see `mono_iff_mono_right`. -/ lemma mono_of_mono_right {A B : structured_arrow S T} (f : A ⟶ B) [h : mono f.right] : mono f := (proj S T).mono_of_mono_map h lemma epi_of_epi_right {A B : structured_arrow S T} (f : A ⟶ B) [h : epi f.right] : epi f := (proj S T).epi_of_epi_map h instance mono_hom_mk {A B : structured_arrow S T} (f : A.right ⟶ B.right) (w) [h : mono f] : mono (hom_mk f w) := (proj S T).mono_of_mono_map h instance epi_hom_mk {A B : structured_arrow S T} (f : A.right ⟶ B.right) (w) [h : epi f] : epi (hom_mk f w) := (proj S T).epi_of_epi_map h /-- Eta rule for structured arrows. Prefer `structured_arrow.eta`, since equality of objects tends to cause problems. -/ lemma eq_mk (f : structured_arrow S T) : f = mk f.hom := by { cases f, congr, ext, } /-- Eta rule for structured arrows. -/ @[simps] def eta (f : structured_arrow S T) : f ≅ mk f.hom := iso_mk (iso.refl _) (by tidy) /-- A morphism between source objects `S ⟶ S'` contravariantly induces a functor between structured arrows, `structured_arrow S' T ⥤ structured_arrow S T`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps] def map (f : S ⟶ S') : structured_arrow S' T ⥤ structured_arrow S T := comma.map_left _ ((functor.const _).map f) @[simp] lemma map_mk {f : S' ⟶ T.obj Y} (g : S ⟶ S') : (map g).obj (mk f) = mk (g ≫ f) := rfl @[simp] lemma map_id {f : structured_arrow S T} : (map (𝟙 S)).obj f = f := by { rw eq_mk f, simp, } @[simp] lemma map_comp {f : S ⟶ S'} {f' : S' ⟶ S''} {h : structured_arrow S'' T} : (map (f ≫ f')).obj h = (map f).obj ((map f').obj h) := by { rw eq_mk h, simp, } instance proj_reflects_iso : reflects_isomorphisms (proj S T) := { reflects := λ Y Z f t, by exactI ⟨⟨structured_arrow.hom_mk (inv ((proj S T).map f)) (by simp), by tidy⟩⟩ } open category_theory.limits local attribute [tidy] tactic.discrete_cases /-- The identity structured arrow is initial. -/ def mk_id_initial [full T] [faithful T] : is_initial (mk (𝟙 (T.obj Y))) := { desc := λ c, hom_mk (T.preimage c.X.hom) (by { dsimp, simp, }), uniq' := λ c m _, begin ext, apply T.map_injective, simpa only [hom_mk_right, T.image_preimage, ←w m] using (category.id_comp _).symm, end } variables {A : Type u₃} [category.{v₃} A] {B : Type u₄} [category.{v₄} B] /-- The functor `(S, F ⋙ G) ⥤ (S, G)`. -/ @[simps] def pre (S : D) (F : B ⥤ C) (G : C ⥤ D) : structured_arrow S (F ⋙ G) ⥤ structured_arrow S G := comma.pre_right _ F G /-- The functor `(S, F) ⥤ (G(S), F ⋙ G)`. -/ @[simps] def post (S : C) (F : B ⥤ C) (G : C ⥤ D) : structured_arrow S F ⥤ structured_arrow (G.obj S) (F ⋙ G) := { obj := λ X, { right := X.right, hom := G.map X.hom }, map := λ X Y f, { right := f.right, w' := by { simp [functor.comp_map, ←G.map_comp, ← f.w] } } } instance small_proj_preimage_of_locally_small {𝒢 : set C} [small.{v₁} 𝒢] [locally_small.{v₁} D] : small.{v₁} ((proj S T).obj ⁻¹' 𝒢) := begin suffices : (proj S T).obj ⁻¹' 𝒢 = set.range (λ f : Σ G : 𝒢, S ⟶ T.obj G, mk f.2), { rw this, apply_instance }, exact set.ext (λ X, ⟨λ h, ⟨⟨⟨_, h⟩, X.hom⟩, (eq_mk _).symm⟩, by tidy⟩) end end structured_arrow /-- The category of `S`-costructured arrows with target `T : D` (here `S : C ⥤ D`), has as its objects `D`-morphisms of the form `S Y ⟶ T`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ @[derive category, nolint has_nonempty_instance] def costructured_arrow (S : C ⥤ D) (T : D) := comma S (functor.from_punit T) namespace costructured_arrow /-- The obvious projection functor from costructured arrows. -/ @[simps] def proj (S : C ⥤ D) (T : D) : costructured_arrow S T ⥤ C := comma.fst _ _ variables {T T' T'' : D} {Y Y' : C} {S : C ⥤ D} /-- Construct a costructured arrow from a morphism. -/ def mk (f : S.obj Y ⟶ T) : costructured_arrow S T := ⟨Y, ⟨⟨⟩⟩, f⟩ @[simp] lemma mk_left (f : S.obj Y ⟶ T) : (mk f).left = Y := rfl @[simp] lemma mk_right (f : S.obj Y ⟶ T) : (mk f).right = ⟨⟨⟩⟩ := rfl @[simp] lemma mk_hom_eq_self (f : S.obj Y ⟶ T) : (mk f).hom = f := rfl @[simp, reassoc] lemma w {A B : costructured_arrow S T} (f : A ⟶ B) : S.map f.left ≫ B.hom = A.hom := by tidy /-- To construct a morphism of costructured arrows, we need a morphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps] def hom_mk {f f' : costructured_arrow S T} (g : f.left ⟶ f'.left) (w : S.map g ≫ f'.hom = f.hom) : f ⟶ f' := { left := g, right := eq_to_hom (by ext), w' := by simpa [eq_to_hom_map] using w, } /-- To construct an isomorphism of costructured arrows, we need an isomorphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps] def iso_mk {f f' : costructured_arrow S T} (g : f.left ≅ f'.left) (w : S.map g.hom ≫ f'.hom = f.hom) : f ≅ f' := comma.iso_mk g (eq_to_iso (by ext)) (by simpa [eq_to_hom_map] using w) lemma ext {A B : costructured_arrow S T} (f g : A ⟶ B) (h : f.left = g.left) : f = g := comma_morphism.ext _ _ h (subsingleton.elim _ _) lemma ext_iff {A B : costructured_arrow S T} (f g : A ⟶ B) : f = g ↔ f.left = g.left := ⟨λ h, h ▸ rfl, ext f g⟩ instance proj_faithful : faithful (proj S T) := { map_injective' := λ X Y, ext } lemma mono_of_mono_left {A B : costructured_arrow S T} (f : A ⟶ B) [h : mono f.left] : mono f := (proj S T).mono_of_mono_map h /-- The converse of this is true with additional assumptions, see `epi_iff_epi_left`. -/ lemma epi_of_epi_left {A B : costructured_arrow S T} (f : A ⟶ B) [h : epi f.left] : epi f := (proj S T).epi_of_epi_map h instance mono_hom_mk {A B : costructured_arrow S T} (f : A.left ⟶ B.left) (w) [h : mono f] : mono (hom_mk f w) := (proj S T).mono_of_mono_map h instance epi_hom_mk {A B : costructured_arrow S T} (f : A.left ⟶ B.left) (w) [h : epi f] : epi (hom_mk f w) := (proj S T).epi_of_epi_map h /-- Eta rule for costructured arrows. Prefer `costructured_arrow.eta`, as equality of objects tends to cause problems. -/ lemma eq_mk (f : costructured_arrow S T) : f = mk f.hom := by { cases f, congr, ext, } /-- Eta rule for costructured arrows. -/ @[simps] def eta (f : costructured_arrow S T) : f ≅ mk f.hom := iso_mk (iso.refl _) (by tidy) /-- A morphism between target objects `T ⟶ T'` covariantly induces a functor between costructured arrows, `costructured_arrow S T ⥤ costructured_arrow S T'`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps] def map (f : T ⟶ T') : costructured_arrow S T ⥤ costructured_arrow S T' := comma.map_right _ ((functor.const _).map f) @[simp] lemma map_mk {f : S.obj Y ⟶ T} (g : T ⟶ T') : (map g).obj (mk f) = mk (f ≫ g) := rfl @[simp] lemma map_id {f : costructured_arrow S T} : (map (𝟙 T)).obj f = f := by { rw eq_mk f, simp, } @[simp] lemma map_comp {f : T ⟶ T'} {f' : T' ⟶ T''} {h : costructured_arrow S T} : (map (f ≫ f')).obj h = (map f').obj ((map f).obj h) := by { rw eq_mk h, simp, } instance proj_reflects_iso : reflects_isomorphisms (proj S T) := { reflects := λ Y Z f t, by exactI ⟨⟨costructured_arrow.hom_mk (inv ((proj S T).map f)) (by simp), by tidy⟩⟩ } open category_theory.limits local attribute [tidy] tactic.discrete_cases /-- The identity costructured arrow is terminal. -/ def mk_id_terminal [full S] [faithful S] : is_terminal (mk (𝟙 (S.obj Y))) := { lift := λ c, hom_mk (S.preimage c.X.hom) (by { dsimp, simp, }), uniq' := begin rintros c m -, ext, apply S.map_injective, simpa only [hom_mk_left, S.image_preimage, ←w m] using (category.comp_id _).symm, end } variables {A : Type u₃} [category.{v₃} A] {B : Type u₄} [category.{v₄} B] /-- The functor `(F ⋙ G, S) ⥤ (G, S)`. -/ @[simps] def pre (F : B ⥤ C) (G : C ⥤ D) (S : D) : costructured_arrow (F ⋙ G) S ⥤ costructured_arrow G S := comma.pre_left F G _ /-- The functor `(F, S) ⥤ (F ⋙ G, G(S))`. -/ @[simps] def post (F : B ⥤ C) (G : C ⥤ D) (S : C) : costructured_arrow F S ⥤ costructured_arrow (F ⋙ G) (G.obj S) := { obj := λ X, { left := X.left, hom := G.map X.hom }, map := λ X Y f, { left := f.left, w' := by { simp [functor.comp_map, ←G.map_comp, ← f.w] } } } instance small_proj_preimage_of_locally_small {𝒢 : set C} [small.{v₁} 𝒢] [locally_small.{v₁} D] : small.{v₁} ((proj S T).obj ⁻¹' 𝒢) := begin suffices : (proj S T).obj ⁻¹' 𝒢 = set.range (λ f : Σ G : 𝒢, S.obj G ⟶ T, mk f.2), { rw this, apply_instance }, exact set.ext (λ X, ⟨λ h, ⟨⟨⟨_, h⟩, X.hom⟩, (eq_mk _).symm⟩, by tidy⟩) end end costructured_arrow open opposite namespace structured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `d ⟶ F.obj c` to the category of costructured arrows `F.op.obj c ⟶ (op d)`. -/ @[simps] def to_costructured_arrow (F : C ⥤ D) (d : D) : (structured_arrow d F)ᵒᵖ ⥤ costructured_arrow F.op (op d) := { obj := λ X, @costructured_arrow.mk _ _ _ _ _ (op X.unop.right) F.op X.unop.hom.op, map := λ X Y f, costructured_arrow.hom_mk (f.unop.right.op) begin dsimp, rw [← op_comp, ← f.unop.w, functor.const_obj_map], erw category.id_comp, end } /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `op d ⟶ F.op.obj c` to the category of costructured arrows `F.obj c ⟶ d`. -/ @[simps] def to_costructured_arrow' (F : C ⥤ D) (d : D) : (structured_arrow (op d) F.op)ᵒᵖ ⥤ costructured_arrow F d := { obj := λ X, @costructured_arrow.mk _ _ _ _ _ (unop X.unop.right) F X.unop.hom.unop, map := λ X Y f, costructured_arrow.hom_mk f.unop.right.unop begin dsimp, rw [← quiver.hom.unop_op (F.map (quiver.hom.unop f.unop.right)), ← unop_comp, ← F.op_map, ← f.unop.w, functor.const_obj_map], erw category.id_comp, end } end structured_arrow namespace costructured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.obj c ⟶ d` to the category of structured arrows `op d ⟶ F.op.obj c`. -/ @[simps] def to_structured_arrow (F : C ⥤ D) (d : D) : (costructured_arrow F d)ᵒᵖ ⥤ structured_arrow (op d) F.op := { obj := λ X, @structured_arrow.mk _ _ _ _ _ (op X.unop.left) F.op X.unop.hom.op, map := λ X Y f, structured_arrow.hom_mk f.unop.left.op begin dsimp, rw [← op_comp, f.unop.w, functor.const_obj_map], erw category.comp_id, end } /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.op.obj c ⟶ op d` to the category of structured arrows `d ⟶ F.obj c`. -/ @[simps] def to_structured_arrow' (F : C ⥤ D) (d : D) : (costructured_arrow F.op (op d))ᵒᵖ ⥤ structured_arrow d F := { obj := λ X, @structured_arrow.mk _ _ _ _ _ (unop X.unop.left) F X.unop.hom.unop, map := λ X Y f, structured_arrow.hom_mk (f.unop.left.unop) begin dsimp, rw [← quiver.hom.unop_op (F.map f.unop.left.unop), ← unop_comp, ← F.op_map, f.unop.w, functor.const_obj_map], erw category.comp_id, end } end costructured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of structured arrows `d ⟶ F.obj c` is contravariantly equivalent to the category of costructured arrows `F.op.obj c ⟶ op d`. -/ def structured_arrow_op_equivalence (F : C ⥤ D) (d : D) : (structured_arrow d F)ᵒᵖ ≌ costructured_arrow F.op (op d) := equivalence.mk (structured_arrow.to_costructured_arrow F d) (costructured_arrow.to_structured_arrow' F d).right_op (nat_iso.of_components (λ X, (@structured_arrow.iso_mk _ _ _ _ _ _ (structured_arrow.mk (unop X).hom) (unop X) (iso.refl _) (by tidy)).op) (λ X Y f, quiver.hom.unop_inj $ begin ext, dsimp, simp end)) (nat_iso.of_components (λ X, @costructured_arrow.iso_mk _ _ _ _ _ _ (costructured_arrow.mk X.hom) X (iso.refl _) (by tidy)) (λ X Y f, begin ext, dsimp, simp end)) /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of costructured arrows `F.obj c ⟶ d` is contravariantly equivalent to the category of structured arrows `op d ⟶ F.op.obj c`. -/ def costructured_arrow_op_equivalence (F : C ⥤ D) (d : D) : (costructured_arrow F d)ᵒᵖ ≌ structured_arrow (op d) F.op := equivalence.mk (costructured_arrow.to_structured_arrow F d) (structured_arrow.to_costructured_arrow' F d).right_op (nat_iso.of_components (λ X, (@costructured_arrow.iso_mk _ _ _ _ _ _ (costructured_arrow.mk (unop X).hom) (unop X) (iso.refl _) (by tidy)).op) (λ X Y f, quiver.hom.unop_inj $ begin ext, dsimp, simp end)) (nat_iso.of_components (λ X, @structured_arrow.iso_mk _ _ _ _ _ _ (structured_arrow.mk X.hom) X (iso.refl _) (by tidy)) (λ X Y f, begin ext, dsimp, simp end)) end category_theory
597c77fd954964848497999bbda62c2c2e5d1c6d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/shapes/images.lean
7ae28dbae9cabd58b44052d4bab8588d52ab910d
[ "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
31,520
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.equalizers import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.strong_epi /-! # Categorical images We define the categorical image of `f` as a factorisation `f = e ≫ m` through a monomorphism `m`, so that `m` factors through the `m'` in any other such factorisation. ## Main definitions * A `mono_factorisation` is a factorisation `f = e ≫ m`, where `m` is a monomorphism * `is_image F` means that a given mono factorisation `F` has the universal property of the image. * `has_image f` means that there is some image factorization for the morphism `f : X ⟶ Y`. * In this case, `image f` is some image object (selected with choice), `image.ι f : image f ⟶ Y` is the monomorphism `m` of the factorisation and `factor_thru_image f : X ⟶ image f` is the morphism `e`. * `has_images C` means that every morphism in `C` has an image. * Let `f : X ⟶ Y` and `g : P ⟶ Q` be morphisms in `C`, which we will represent as objects of the arrow category `arrow C`. Then `sq : f ⟶ g` is a commutative square in `C`. If `f` and `g` have images, then `has_image_map sq` represents the fact that there is a morphism `i : image f ⟶ image g` making the diagram X ----→ image f ----→ Y | | | | | | ↓ ↓ ↓ P ----→ image g ----→ Q commute, where the top row is the image factorisation of `f`, the bottom row is the image factorisation of `g`, and the outer rectangle is the commutative square `sq`. * If a category `has_images`, then `has_image_maps` means that every commutative square admits an image map. * If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is always a strong epimorphism. ## Main statements * When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism. * When `C` has strong epi images, then these images admit image maps. ## Future work * TODO: coimages, and abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. -/ noncomputable theory 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 {X Y : C} (f : X ⟶ Y) /-- A factorisation of a morphism `f = e ≫ m`, with `m` monic. -/ structure mono_factorisation (f : X ⟶ Y) := (I : C) (m : I ⟶ Y) [m_mono : mono m] (e : X ⟶ I) (fac' : e ≫ m = f . obviously) restate_axiom mono_factorisation.fac' attribute [simp, reassoc] mono_factorisation.fac attribute [instance] mono_factorisation.m_mono attribute [instance] mono_factorisation.m_mono namespace mono_factorisation /-- The obvious factorisation of a monomorphism through itself. -/ def self [mono f] : mono_factorisation f := { I := X, m := f, e := 𝟙 X } -- I'm not sure we really need this, but the linter says that an inhabited instance -- ought to exist... instance [mono f] : inhabited (mono_factorisation f) := ⟨self f⟩ variables {f} /-- The morphism `m` in a factorisation `f = e ≫ m` through a monomorphism is uniquely determined. -/ @[ext] lemma ext {F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) ≫ F'.m) : F = F' := begin cases F, cases F', cases hI, simp at hm, dsimp at F_fac' F'_fac', congr, { assumption }, { resetI, apply (cancel_mono F_m).1, rw [F_fac', hm, F'_fac'], } end /-- Any mono factorisation of `f` gives a mono factorisation of `f ≫ g` when `g` is a mono. -/ @[simps] def comp_mono (F : mono_factorisation f) {Y' : C} (g : Y ⟶ Y') [mono g] : mono_factorisation (f ≫ g) := { I := F.I, m := F.m ≫ g, m_mono := mono_comp _ _, e := F.e, } /-- A mono factorisation of `f ≫ g`, where `g` is an isomorphism, gives a mono factorisation of `f`. -/ @[simps] def of_comp_iso {Y' : C} {g : Y ⟶ Y'} [is_iso g] (F : mono_factorisation (f ≫ g)) : mono_factorisation f := { I := F.I, m := F.m ≫ (inv g), m_mono := mono_comp _ _, e := F.e, } /-- Any mono factorisation of `f` gives a mono factorisation of `g ≫ f`. -/ @[simps] def iso_comp (F : mono_factorisation f) {X' : C} (g : X' ⟶ X) : mono_factorisation (g ≫ f) := { I := F.I, m := F.m, e := g ≫ F.e, } /-- A mono factorisation of `g ≫ f`, where `g` is an isomorphism, gives a mono factorisation of `f`. -/ @[simps] def of_iso_comp {X' : C} (g : X' ⟶ X) [is_iso g] (F : mono_factorisation (g ≫ f)) : mono_factorisation f := { I := F.I, m := F.m, e := inv g ≫ F.e, } /-- If `f` and `g` are isomorphic arrows, then a mono factorisation of `f` gives a mono factorisation of `g` -/ @[simps] def of_arrow_iso {f g : arrow C} (F : mono_factorisation f.hom) (sq : f ⟶ g) [is_iso sq] : mono_factorisation g.hom := { I := F.I, m := F.m ≫ sq.right, e := inv sq.left ≫ F.e, m_mono := mono_comp _ _, fac' := by simp only [fac_assoc, arrow.w, is_iso.inv_comp_eq, category.assoc] } end mono_factorisation variable {f} /-- Data exhibiting that a given factorisation through a mono is initial. -/ structure is_image (F : mono_factorisation f) := (lift : Π (F' : mono_factorisation f), F.I ⟶ F'.I) (lift_fac' : Π (F' : mono_factorisation f), lift F' ≫ F'.m = F.m . obviously) restate_axiom is_image.lift_fac' attribute [simp, reassoc] is_image.lift_fac namespace is_image @[simp, reassoc] lemma fac_lift {F : mono_factorisation f} (hF : is_image F) (F' : mono_factorisation f) : F.e ≫ hF.lift F' = F'.e := (cancel_mono F'.m).1 $ by simp variable (f) /-- The trivial factorisation of a monomorphism satisfies the universal property. -/ @[simps] def self [mono f] : is_image (mono_factorisation.self f) := { lift := λ F', F'.e } instance [mono f] : inhabited (is_image (mono_factorisation.self f)) := ⟨self f⟩ variable {f} /-- Two factorisations through monomorphisms satisfying the universal property must factor through isomorphic objects. -/ -- TODO this is another good candidate for a future `unique_up_to_canonical_iso`. @[simps] def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I ≅ F'.I := { hom := hF.lift F', inv := hF'.lift F, hom_inv_id' := (cancel_mono F.m).1 (by simp), inv_hom_id' := (cancel_mono F'.m).1 (by simp) } variables {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') lemma iso_ext_hom_m : (iso_ext hF hF').hom ≫ F'.m = F.m := by simp lemma iso_ext_inv_m : (iso_ext hF hF').inv ≫ F.m = F'.m := by simp lemma e_iso_ext_hom : F.e ≫ (iso_ext hF hF').hom = F'.e := by simp lemma e_iso_ext_inv : F'.e ≫ (iso_ext hF hF').inv = F.e := by simp /-- If `f` and `g` are isomorphic arrows, then a mono factorisation of `f` that is an image gives a mono factorisation of `g` that is an image -/ @[simps] def of_arrow_iso {f g : arrow C} {F : mono_factorisation f.hom} (hF : is_image F) (sq : f ⟶ g) [is_iso sq] : is_image (F.of_arrow_iso sq) := { lift := λ F', hF.lift (F'.of_arrow_iso (inv sq)), lift_fac' := λ F', by simpa only [mono_factorisation.of_arrow_iso_m, arrow.inv_right, ← category.assoc, is_iso.comp_inv_eq] using hF.lift_fac (F'.of_arrow_iso (inv sq)) } end is_image variable (f) /-- Data exhibiting that a morphism `f` has an image. -/ structure image_factorisation (f : X ⟶ Y) := (F : mono_factorisation f) (is_image : is_image F) namespace image_factorisation instance [mono f] : inhabited (image_factorisation f) := ⟨⟨_, is_image.self f⟩⟩ /-- If `f` and `g` are isomorphic arrows, then an image factorisation of `f` gives an image factorisation of `g` -/ @[simps] def of_arrow_iso {f g : arrow C} (F : image_factorisation f.hom) (sq : f ⟶ g) [is_iso sq] : image_factorisation g.hom := { F := F.F.of_arrow_iso sq, is_image := F.is_image.of_arrow_iso sq } end image_factorisation /-- `has_image f` means that there exists an image factorisation of `f`. -/ class has_image (f : X ⟶ Y) : Prop := mk' :: (exists_image : nonempty (image_factorisation f)) lemma has_image.mk {f : X ⟶ Y} (F : image_factorisation f) : has_image f := ⟨nonempty.intro F⟩ lemma has_image.of_arrow_iso {f g : arrow C} [h : has_image f.hom] (sq : f ⟶ g) [is_iso sq] : has_image g.hom := ⟨⟨h.exists_image.some.of_arrow_iso sq⟩⟩ @[priority 100] instance mono_has_image (f : X ⟶ Y) [mono f] : has_image f := has_image.mk ⟨_, is_image.self f⟩ section variable [has_image f] /-- Some factorisation of `f` through a monomorphism (selected with choice). -/ def image.mono_factorisation : mono_factorisation f := (classical.choice (has_image.exists_image)).F /-- The witness of the universal property for the chosen factorisation of `f` through a monomorphism. -/ def image.is_image : is_image (image.mono_factorisation f) := (classical.choice (has_image.exists_image)).is_image /-- The categorical image of a morphism. -/ def image : C := (image.mono_factorisation f).I /-- The inclusion of the image of a morphism into the target. -/ def image.ι : image f ⟶ Y := (image.mono_factorisation f).m @[simp] lemma image.as_ι : (image.mono_factorisation f).m = image.ι f := rfl instance : mono (image.ι f) := (image.mono_factorisation f).m_mono /-- The map from the source to the image of a morphism. -/ def factor_thru_image : X ⟶ image f := (image.mono_factorisation f).e /-- Rewrite in terms of the `factor_thru_image` interface. -/ @[simp] lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl @[simp, reassoc] lemma image.fac : factor_thru_image f ≫ image.ι f = f := (image.mono_factorisation f).fac' variable {f} /-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the image. -/ def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (image.is_image f).lift F' @[simp, reassoc] lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := (image.is_image f).lift_fac' F' @[simp, reassoc] lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f ≫ image.lift F' = F'.e := (image.is_image f).fac_lift F' @[simp] lemma image.is_image_lift (F : mono_factorisation f) : (image.is_image f).lift F = image.lift F := rfl @[simp, reassoc] lemma is_image.lift_ι {F : mono_factorisation f} (hF : is_image F) : hF.lift (image.mono_factorisation f) ≫ image.ι f = F.m := hF.lift_fac _ -- TODO we could put a category structure on `mono_factorisation f`, -- with the morphisms being `g : I ⟶ I'` commuting with the `m`s -- (they then automatically commute with the `e`s) -- and show that an `image_of f` gives an initial object there -- (uniqueness of the lift comes for free). instance image.lift_mono (F' : mono_factorisation f) : mono (image.lift F') := by { apply mono_of_mono _ F'.m, simpa using mono_factorisation.m_mono _ } lemma has_image.uniq (F' : mono_factorisation f) (l : image f ⟶ F'.I) (w : l ≫ F'.m = image.ι f) : l = image.lift F' := (cancel_mono F'.m).1 (by simp [w]) /-- If `has_image g`, then `has_image (f ≫ g)` when `f` is an isomorphism. -/ instance {X Y Z : C} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) [has_image g] : has_image (f ≫ g) := { exists_image := ⟨ { F := { I := image g, m := image.ι g, e := f ≫ factor_thru_image g, }, is_image := { lift := λ F', image.lift { I := F'.I, m := F'.m, e := inv f ≫ F'.e, }, }, }⟩ } end section variables (C) /-- `has_images` asserts that every morphism has an image. -/ class has_images : Prop := (has_image : Π {X Y : C} (f : X ⟶ Y), has_image f) attribute [instance, priority 100] has_images.has_image end section variables (f) /-- The image of a monomorphism is isomorphic to the source. -/ def image_mono_iso_source [mono f] : image f ≅ X := is_image.iso_ext (image.is_image f) (is_image.self f) @[simp, reassoc] lemma image_mono_iso_source_inv_ι [mono f] : (image_mono_iso_source f).inv ≫ image.ι f = f := by simp [image_mono_iso_source] @[simp, reassoc] lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom ≫ f = image.ι f := begin conv { to_lhs, congr, skip, rw ←image_mono_iso_source_inv_ι f, }, rw [←category.assoc, iso.hom_inv_id, category.id_comp], end -- This is the proof that `factor_thru_image f` is an epimorphism -- from https://en.wikipedia.org/wiki/Image_%28category_theory%29, which is in turn taken from: -- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1 @[ext] lemma image.ext [has_image f] {W : C} {g h : image f ⟶ W} [has_limit (parallel_pair g h)] (w : factor_thru_image f ≫ g = factor_thru_image f ≫ h) : g = h := begin let q := equalizer.ι g h, let e' := equalizer.lift _ w, let F' : mono_factorisation f := { I := equalizer g h, m := q ≫ image.ι f, m_mono := by apply mono_comp, e := e' }, let v := image.lift F', have t₀ : v ≫ q ≫ image.ι f = image.ι f := image.lift_fac F', have t : v ≫ q = 𝟙 (image f) := (cancel_mono_id (image.ι f)).1 (by { convert t₀ using 1, rw category.assoc }), -- The proof from wikipedia next proves `q ≫ v = 𝟙 _`, -- and concludes that `equalizer g h ≅ image f`, -- but this isn't necessary. calc g = 𝟙 (image f) ≫ g : by rw [category.id_comp] ... = v ≫ q ≫ g : by rw [←t, category.assoc] ... = v ≫ q ≫ h : by rw [equalizer.condition g h] ... = 𝟙 (image f) ≫ h : by rw [←category.assoc, t] ... = h : by rw [category.id_comp] end instance [has_image f] [Π {Z : C} (g h : image f ⟶ Z), has_limit (parallel_pair g h)] : epi (factor_thru_image f) := ⟨λ Z g h w, image.ext f w⟩ lemma epi_image_of_epi {X Y : C} (f : X ⟶ Y) [has_image f] [E : epi f] : epi (image.ι f) := begin rw ←image.fac f at E, resetI, exact epi_of_epi (factor_thru_image f) (image.ι f), end lemma epi_of_epi_image {X Y : C} (f : X ⟶ Y) [has_image f] [epi (image.ι f)] [epi (factor_thru_image f)] : epi f := by { rw [←image.fac f], apply epi_comp, } end section variables {f} {f' : X ⟶ Y} [has_image f] [has_image f'] /-- An equation between morphisms gives a comparison map between the images (which momentarily we prove is an iso). -/ def image.eq_to_hom (h : f = f') : image f ⟶ image f' := image.lift { I := image f', m := image.ι f', e := factor_thru_image f', }. instance (h : f = f') : is_iso (image.eq_to_hom h) := ⟨⟨image.eq_to_hom h.symm, ⟨(cancel_mono (image.ι f)).1 (by simp [image.eq_to_hom]), (cancel_mono (image.ι f')).1 (by simp [image.eq_to_hom])⟩⟩⟩ /-- An equation between morphisms gives an isomorphism between the images. -/ def image.eq_to_iso (h : f = f') : image f ≅ image f' := as_iso (image.eq_to_hom h) /-- As long as the category has equalizers, the image inclusion maps commute with `image.eq_to_iso`. -/ lemma image.eq_fac [has_equalizers C] (h : f = f') : image.ι f = (image.eq_to_iso h).hom ≫ image.ι f' := by { ext, simp [image.eq_to_iso, image.eq_to_hom], } end section variables {Z : C} (g : Y ⟶ Z) /-- The comparison map `image (f ≫ g) ⟶ image g`. -/ def image.pre_comp [has_image g] [has_image (f ≫ g)] : image (f ≫ g) ⟶ image g := image.lift { I := image g, m := image.ι g, e := f ≫ factor_thru_image g } @[simp, reassoc] lemma image.pre_comp_ι [has_image g] [has_image (f ≫ g)] : image.pre_comp f g ≫ image.ι g = image.ι (f ≫ g) := by simp [image.pre_comp] @[simp, reassoc] lemma image.factor_thru_image_pre_comp [has_image g] [has_image (f ≫ g)] : factor_thru_image (f ≫ g) ≫ image.pre_comp f g = f ≫ factor_thru_image g := by simp [image.pre_comp] /-- `image.pre_comp f g` is a monomorphism. -/ instance image.pre_comp_mono [has_image g] [has_image (f ≫ g)] : mono (image.pre_comp f g) := begin apply mono_of_mono _ (image.ι g), simp only [image.pre_comp_ι], apply_instance, end /-- The two step comparison map `image (f ≫ (g ≫ h)) ⟶ image (g ≫ h) ⟶ image h` agrees with the one step comparison map `image (f ≫ (g ≫ h)) ≅ image ((f ≫ g) ≫ h) ⟶ image h`. -/ lemma image.pre_comp_comp {W : C} (h : Z ⟶ W) [has_image (g ≫ h)] [has_image (f ≫ g ≫ h)] [has_image h] [has_image ((f ≫ g) ≫ h)] : image.pre_comp f (g ≫ h) ≫ image.pre_comp g h = image.eq_to_hom (category.assoc f g h).symm ≫ (image.pre_comp (f ≫ g) h) := begin apply (cancel_mono (image.ι h)).1, simp [image.pre_comp, image.eq_to_hom], end variables [has_equalizers C] /-- `image.pre_comp f g` is an epimorphism when `f` is an epimorphism (we need `C` to have equalizers to prove this). -/ instance image.pre_comp_epi_of_epi [has_image g] [has_image (f ≫ g)] [epi f] : epi (image.pre_comp f g) := begin apply epi_of_epi_fac (image.factor_thru_image_pre_comp _ _), exact epi_comp _ _ end instance has_image_iso_comp [is_iso f] [has_image g] : has_image (f ≫ g) := has_image.mk { F := (image.mono_factorisation g).iso_comp f, is_image := { lift := λ F', image.lift (F'.of_iso_comp f) }, } /-- `image.pre_comp f g` is an isomorphism when `f` is an isomorphism (we need `C` to have equalizers to prove this). -/ instance image.is_iso_precomp_iso (f : X ⟶ Y) [is_iso f] [has_image g] : is_iso (image.pre_comp f g) := ⟨⟨image.lift { I := image (f ≫ g), m := image.ι (f ≫ g), e := inv f ≫ factor_thru_image (f ≫ g) }, ⟨by { ext, simp [image.pre_comp], }, by { ext, simp [image.pre_comp], }⟩⟩⟩ -- Note that in general we don't have the other comparison map you might expect -- `image f ⟶ image (f ≫ g)`. instance has_image_comp_iso [has_image f] [is_iso g] : has_image (f ≫ g) := has_image.mk { F := (image.mono_factorisation f).comp_mono g, is_image := { lift := λ F', image.lift F'.of_comp_iso }, } /-- Postcomposing by an isomorphism induces an isomorphism on the image. -/ def image.comp_iso [has_image f] [is_iso g] : image f ≅ image (f ≫ g) := { hom := image.lift (image.mono_factorisation (f ≫ g)).of_comp_iso, inv := image.lift ((image.mono_factorisation f).comp_mono g) } @[simp, reassoc] lemma image.comp_iso_hom_comp_image_ι [has_image f] [is_iso g] : (image.comp_iso f g).hom ≫ image.ι (f ≫ g) = image.ι f ≫ g := by { ext, simp [image.comp_iso] } @[simp, reassoc] lemma image.comp_iso_inv_comp_image_ι [has_image f] [is_iso g] : (image.comp_iso f g).inv ≫ image.ι f = image.ι (f ≫ g) ≫ inv g := by { ext, simp [image.comp_iso] } end end category_theory.limits namespace category_theory.limits variables {C : Type u} [category.{v} C] section instance {X Y : C} (f : X ⟶ Y) [has_image f] : has_image (arrow.mk f).hom := show has_image f, by apply_instance end section has_image_map /-- An image map is a morphism `image f → image g` fitting into a commutative square and satisfying the obvious commutativity conditions. -/ structure image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) := (map : image f.hom ⟶ image g.hom) (map_ι' : map ≫ image.ι g.hom = image.ι f.hom ≫ sq.right . obviously) instance inhabited_image_map {f : arrow C} [has_image f.hom] : inhabited (image_map (𝟙 f)) := ⟨⟨𝟙 _, by tidy⟩⟩ restate_axiom image_map.map_ι' attribute [simp, reassoc] image_map.map_ι @[simp, reassoc] lemma image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) (m : image_map sq) : factor_thru_image f.hom ≫ m.map = sq.left ≫ factor_thru_image g.hom := (cancel_mono (image.ι g.hom)).1 $ by simp /-- To give an image map for a commutative square with `f` at the top and `g` at the bottom, it suffices to give a map between any mono factorisation of `f` and any image factorisation of `g`. -/ def image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) (F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F') {map : F.I ⟶ F'.I} (map_ι : map ≫ F'.m = F.m ≫ sq.right) : image_map sq := { map := image.lift F ≫ map ≫ hF'.lift (image.mono_factorisation g.hom), map_ι' := by simp [map_ι] } /-- `has_image_map sq` means that there is an `image_map` for the square `sq`. -/ class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) : Prop := mk' :: (has_image_map : nonempty (image_map sq)) lemma has_image_map.mk {f g : arrow C} [has_image f.hom] [has_image g.hom] {sq : f ⟶ g} (m : image_map sq) : has_image_map sq := ⟨nonempty.intro m⟩ lemma has_image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) (F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F') (map : F.I ⟶ F'.I) (map_ι : map ≫ F'.m = F.m ≫ sq.right) : has_image_map sq := has_image_map.mk $ image_map.transport sq F hF' map_ι /-- Obtain an `image_map` from a `has_image_map` instance. -/ def has_image_map.image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) [has_image_map sq] : image_map sq := classical.choice $ @has_image_map.has_image_map _ _ _ _ _ _ sq _ @[priority 100] -- see Note [lower instance priority] instance has_image_map_of_is_iso {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) [is_iso sq] : has_image_map sq := has_image_map.mk { map := image.lift ((image.mono_factorisation g.hom).of_arrow_iso (inv sq)), map_ι' := begin erw [← cancel_mono (inv sq).right, category.assoc, ← mono_factorisation.of_arrow_iso_m, image.lift_fac, category.assoc, ← comma.comp_right, is_iso.hom_inv_id, comma.id_right, category.comp_id], end } instance has_image_map.comp {f g h : arrow C} [has_image f.hom] [has_image g.hom] [has_image h.hom] (sq1 : f ⟶ g) (sq2 : g ⟶ h) [has_image_map sq1] [has_image_map sq2] : has_image_map (sq1 ≫ sq2) := has_image_map.mk { map := (has_image_map.image_map sq1).map ≫ (has_image_map.image_map sq2).map, map_ι' := by simp only [image_map.map_ι, image_map.map_ι_assoc, comma.comp_right, category.assoc] } variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) section local attribute [ext] image_map instance : subsingleton (image_map sq) := subsingleton.intro $ λ a b, image_map.ext a b $ (cancel_mono (image.ι g.hom)).1 $ by simp only [image_map.map_ι] end variable [has_image_map sq] /-- The map on images induced by a commutative square. -/ abbreviation image.map : image f.hom ⟶ image g.hom := (has_image_map.image_map sq).map lemma image.factor_map : factor_thru_image f.hom ≫ image.map sq = sq.left ≫ factor_thru_image g.hom := by simp lemma image.map_ι : image.map sq ≫ image.ι g.hom = image.ι f.hom ≫ sq.right := by simp lemma image.map_hom_mk'_ι {X Y P Q : C} {k : X ⟶ Y} [has_image k] {l : P ⟶ Q} [has_image l] {m : X ⟶ P} {n : Y ⟶ Q} (w : m ≫ l = k ≫ n) [has_image_map (arrow.hom_mk' w)] : image.map (arrow.hom_mk' w) ≫ image.ι l = image.ι k ≫ n := image.map_ι _ section variables {h : arrow C} [has_image h.hom] (sq' : g ⟶ h) variables [has_image_map sq'] /-- Image maps for composable commutative squares induce an image map in the composite square. -/ def image_map_comp : image_map (sq ≫ sq') := { map := image.map sq ≫ image.map sq' } @[simp] lemma image.map_comp [has_image_map (sq ≫ sq')] : image.map (sq ≫ sq') = image.map sq ≫ image.map sq' := show (has_image_map.image_map (sq ≫ sq')).map = (image_map_comp sq sq').map, by congr end section variables (f) /-- The identity `image f ⟶ image f` fits into the commutative square represented by the identity morphism `𝟙 f` in the arrow category. -/ def image_map_id : image_map (𝟙 f) := { map := 𝟙 (image f.hom) } @[simp] lemma image.map_id [has_image_map (𝟙 f)] : image.map (𝟙 f) = 𝟙 (image f.hom) := show (has_image_map.image_map (𝟙 f)).map = (image_map_id f).map, by congr end end has_image_map section variables (C) [has_images C] /-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/ class has_image_maps := (has_image_map : Π {f g : arrow C} (st : f ⟶ g), has_image_map st) attribute [instance, priority 100] has_image_maps.has_image_map end section has_image_maps variables [has_images C] [has_image_maps C] /-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image and a commutative square to the induced morphism on images. -/ @[simps] def im : arrow C ⥤ C := { obj := λ f, image f.hom, map := λ _ _ st, image.map st } end has_image_maps section strong_epi_mono_factorisation /-- A strong epi-mono factorisation is a decomposition `f = e ≫ m` with `e` a strong epimorphism and `m` a monomorphism. -/ structure strong_epi_mono_factorisation {X Y : C} (f : X ⟶ Y) extends mono_factorisation f := [e_strong_epi : strong_epi e] attribute [instance] strong_epi_mono_factorisation.e_strong_epi /-- Satisfying the inhabited linter -/ instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X ⟶ Y) [strong_epi f] : inhabited (strong_epi_mono_factorisation f) := ⟨⟨⟨Y, 𝟙 Y, f, by simp⟩⟩⟩ /-- A mono factorisation coming from a strong epi-mono factorisation always has the universal property of the image. -/ def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X ⟶ Y} (F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation := { lift := λ G, (comm_sq.mk (show G.e ≫ G.m = F.e ≫ F.m, by rw [F.to_mono_factorisation.fac, G.fac])).lift, } variable (C) /-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono factorisation. -/ class has_strong_epi_mono_factorisations : Prop := mk' :: (has_fac : Π {X Y : C} (f : X ⟶ Y), nonempty (strong_epi_mono_factorisation f)) variable {C} lemma has_strong_epi_mono_factorisations.mk (d : Π {X Y : C} (f : X ⟶ Y), strong_epi_mono_factorisation f) : has_strong_epi_mono_factorisations C := ⟨λ X Y f, nonempty.intro $ d f⟩ @[priority 100] instance has_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_images C := { has_image := λ X Y f, let F' := classical.choice (has_strong_epi_mono_factorisations.has_fac f) in has_image.mk { F := F'.to_mono_factorisation, is_image := F'.to_mono_is_image } } end strong_epi_mono_factorisation section has_strong_epi_images variables (C) [has_images C] /-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong epimorphism for all `f`. -/ class has_strong_epi_images : Prop := (strong_factor_thru_image : Π {X Y : C} (f : X ⟶ Y), strong_epi (factor_thru_image f)) attribute [instance] has_strong_epi_images.strong_factor_thru_image end has_strong_epi_images section has_strong_epi_images /-- If there is a single strong epi-mono factorisation of `f`, then every image factorisation is a strong epi-mono factorisation. -/ lemma strong_epi_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y} (F : strong_epi_mono_factorisation f) {F' : mono_factorisation f} (hF' : is_image F') : strong_epi F'.e := by { rw ←is_image.e_iso_ext_hom F.to_mono_is_image hF', apply strong_epi_comp } lemma strong_epi_factor_thru_image_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y} [has_image f] (F : strong_epi_mono_factorisation f) : strong_epi (factor_thru_image f) := strong_epi_of_strong_epi_mono_factorisation F $ image.is_image f /-- If we constructed our images from strong epi-mono factorisations, then these images are strong epi images. -/ @[priority 100] instance has_strong_epi_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_strong_epi_images C := { strong_factor_thru_image := λ X Y f, strong_epi_factor_thru_image_of_strong_epi_mono_factorisation $ classical.choice $ has_strong_epi_mono_factorisations.has_fac f } end has_strong_epi_images section has_strong_epi_images variables [has_images C] /-- A category with strong epi images has image maps. -/ @[priority 100] instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] : has_image_maps C := { has_image_map := λ f g st, has_image_map.mk { map := (comm_sq.mk (show (st.left ≫ factor_thru_image g.hom) ≫ image.ι g.hom = factor_thru_image f.hom ≫ (image.ι f.hom ≫ st.right), by simp)).lift, }, } /-- If a category has images, equalizers and pullbacks, then images are automatically strong epi images. -/ @[priority 100] instance has_strong_epi_images_of_has_pullbacks_of_has_equalizers [has_pullbacks C] [has_equalizers C] : has_strong_epi_images C := { strong_factor_thru_image := λ X Y f, strong_epi.mk' (λ A B h h_mono x y sq, comm_sq.has_lift.mk' { l := image.lift { I := pullback h y, m := pullback.snd ≫ image.ι f, m_mono := by exactI mono_comp _ _, e := pullback.lift _ _ sq.w } ≫ pullback.fst, fac_left' := by simp only [image.fac_lift_assoc, pullback.lift_fst], fac_right' := by { ext, simp only [sq.w, category.assoc, image.fac_lift_assoc, pullback.lift_fst_assoc], }, }) } end has_strong_epi_images variables [has_strong_epi_mono_factorisations C] variables {X Y : C} {f : X ⟶ Y} /-- If `C` has strong epi mono factorisations, then the image is unique up to isomorphism, in that if `f` factors as a strong epi followed by a mono, this factorisation is essentially the image factorisation. -/ def image.iso_strong_epi_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : I' ≅ image f := is_image.iso_ext {strong_epi_mono_factorisation . I := I', m := m, e := e}.to_mono_is_image $ image.is_image f @[simp] lemma image.iso_strong_epi_mono_hom_comp_ι {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : (image.iso_strong_epi_mono e m comm).hom ≫ image.ι f = m := is_image.lift_fac _ _ @[simp] lemma image.iso_strong_epi_mono_inv_comp_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : (image.iso_strong_epi_mono e m comm).inv ≫ m = image.ι f := image.lift_fac _ end category_theory.limits namespace category_theory.functor open category_theory.limits variables {C D : Type*} [category C] [category D] lemma has_strong_epi_mono_factorisations_imp_of_is_equivalence (F : C ⥤ D) [is_equivalence F] [h : has_strong_epi_mono_factorisations C] : has_strong_epi_mono_factorisations D := ⟨λ X Y f, begin let em : strong_epi_mono_factorisation (F.inv.map f) := (has_strong_epi_mono_factorisations.has_fac (F.inv.map f)).some, haveI : mono (F.map em.m ≫ F.as_equivalence.counit_iso.hom.app Y) := mono_comp _ _, haveI : strong_epi (F.as_equivalence.counit_iso.inv.app X ≫ F.map em.e) := strong_epi_comp _ _, exact nonempty.intro { I := F.obj em.I, e := F.as_equivalence.counit_iso.inv.app X ≫ F.map em.e, m := F.map em.m ≫ F.as_equivalence.counit_iso.hom.app Y, fac' := by simpa only [category.assoc, ← F.map_comp_assoc, em.fac', is_equivalence.fun_inv_map, iso.inv_hom_id_app, iso.inv_hom_id_app_assoc] using category.comp_id _, }, end⟩ end category_theory.functor
94fea020b8829b97d823b97de4d7533f8258e143
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/test/library_search/basic.lean
0df419fd09ecdf410c04254de36820a3016e9a94
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
2,383
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.nat.basic import tactic.library_search /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.library_search true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search def lt_one (n : ℕ) := n < 1 lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp -- Verify that calls to solve_by_elim to discharge subgoals use `rfl` example : lt_one 0 := by library_search example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example {a b : ℕ} : a ≤ a + b := by library_search -- says: `exact le_add_right a b` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact nat.mul_sub_left_distrib n m k` example {n m : ℕ} (h : m < n) : m ≤ n - 1 := by library_search -- says: `exact nat.le_pred_of_lt h` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b := by library_search -- says: `exact add_pos` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c := by library_search -- exact mul_dvd_mul_left a w example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` end test.library_search
f12db8a5baca90d3843787b47fdfae3efc5fbca7
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/omega/nat/preterm.lean
5f139b56c13c65eeb2fd4564cd96f9291209ea2d
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
3,697
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear natural number arithmetic terms in pre-normalized form. -/ import tactic.omega.term open tactic namespace omega namespace nat @[derive has_reflect, derive decidable_eq] inductive preterm : Type | cst : nat → preterm | var : nat → nat → preterm | add : preterm → preterm → preterm | sub : preterm → preterm → preterm localized "notation `&` k := omega.nat.preterm.cst k" in omega.nat localized "infix ` ** ` : 300 := omega.nat.preterm.var" in omega.nat localized "notation t ` +* ` s := omega.nat.preterm.add t s" in omega.nat localized "notation t ` -* ` s := omega.nat.preterm.sub t s" in omega.nat namespace preterm meta def induce (tac : tactic unit := tactic.skip) : tactic unit := `[ intro t, induction t with m m n t s iht ihs t s iht ihs; tac] def val (v : nat → nat) : preterm → nat | (& i) := i | (i ** n) := if i = 1 then v n else (v n) * i | (t1 +* t2) := t1.val + t2.val | (t1 -* t2) := t1.val - t2.val @[simp] lemma val_const {v : nat → nat} {m : nat} : (& m).val v = m := rfl @[simp] lemma val_var {v : nat → nat} {m n : nat} : (m ** n).val v = m * (v n) := begin simp only [val], by_cases h1 : m = 1, rw [if_pos h1, h1, one_mul], rw [if_neg h1, mul_comm], end @[simp] lemma val_add {v : nat → nat} {t s : preterm} : (t +* s).val v = t.val v + s.val v := rfl @[simp] lemma val_sub {v : nat → nat} {t s : preterm} : (t -* s).val v = t.val v - s.val v := rfl def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index | (t1 -* t2) := max t1.fresh_index t2.fresh_index lemma val_constant (v w : nat → nat) : ∀ t : preterm, (∀ x < t.fresh_index, v x = w x) → t.val v = t.val w | (& n) h1 := rfl | (m ** n) h1 := begin simp only [val_var], apply congr_arg (λ y, m * y), apply h1 _ (lt_add_one _) end | (t +* s) h1 := begin simp only [val_add], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end | (t -* s) h1 := begin simp only [val_sub], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" | (t1 -* t2) := "(" ++ t1.repr ++ " - " ++ t2.repr ++ ")" @[simp] def add_one (t : preterm) : preterm := t +* (&1) def sub_free : preterm → Prop | (& m) := true | (m ** n) := true | (t +* s) := t.sub_free ∧ s.sub_free | (_ -* _) := false end preterm open_locale list.func -- get notation for list.func.set @[simp] def canonize : preterm → term | (& m) := ⟨↑m, []⟩ | (m ** n) := ⟨0, [] {n ↦ ↑m}⟩ | (t +* s) := term.add (canonize t) (canonize s) | (_ -* _) := ⟨0, []⟩ @[simp] lemma val_canonize {v : nat → nat} : ∀ {t : preterm}, t.sub_free → (canonize t).val (λ x, ↑(v x)) = t.val v | (& i) h1 := by simp only [canonize, preterm.val_const, term.val, coeffs.val_nil, add_zero] | (i ** n) h1 := by simp only [preterm.val_var, coeffs.val_set, term.val, zero_add, int.coe_nat_mul, canonize] | (t +* s) h1 := by simp only [val_canonize h1.left, val_canonize h1.right, int.coe_nat_add, canonize, term.val_add, preterm.val_add] end nat end omega
ea5c871ed77fb4b5c1ad270471230f18f2667dce
798dd332c1ad790518589a09bc82459fb12e5156
/analysis/metric_space.lean
301be94e9302655e40e60810eba366b4f75dd7ca
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,859
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.nnreal analysis.topology.topological_structures open lattice set filter classical noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a metric space from a distance function and metric space axioms -/ def metric_space.uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. -/ class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (to_uniform_space : uniform_space α := metric_space.uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : uniformity = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) theorem uniformity_dist_of_mem_uniformity {U : filter (α × α)} (D : α → α → ℝ) (H : ∀ s, s ∈ U.sets ↔ ∃ε>0, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>0, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) variables [metric_space α] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) section variables [metric_space α] def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) @[simp] lemma coe_dist (a b : α) : (nndist a b : ℝ) = dist a b := rfl theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y := by simp [nnreal.eq_iff.symm] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa [nnreal.eq_iff.symm] using dist_comm x y @[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y := by simp [nnreal.eq_iff.symm] @[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y := by simp [nnreal.eq_iff.symm] theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := by simpa [nnreal.coe_le] using dist_triangle x y z theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := by simpa [nnreal.coe_le] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := by simpa [nnreal.coe_le] using dist_triangle_right x y z end /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : uniformity = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) := metric_space.uniformity_dist _ theorem uniformity_dist' : uniformity = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (α×α)} : s ∈ (@uniformity α _).sets ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := begin rw [uniformity_dist', infi_sets_eq], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ (@uniformity α _).sets := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_of_metric [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ theorem uniform_embedding_of_metric [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ theorem totally_bounded_of_metric {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ lemma cauchy_of_metric {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f.sets, ∀ x y ∈ t, dist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ theorem nhds_eq_metric : nhds x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff_metric : s ∈ (nhds x).sets ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq_metric, infi_sets_eq], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_metric : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff_metric] theorem is_open_ball : is_open (ball x ε) := is_open_metric.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ (nhds x).sets := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem tendsto_nhds_of_metric [metric_space β] {f : α → β} {a b} : tendsto f (nhds a) (nhds b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := ⟨λ H ε ε0, mem_nhds_iff_metric.1 (H (ball_mem_nhds _ ε0)), λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff_metric.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_nhds_iff_metric.2 ⟨δ, δ0, λ x h, hε (hδ h)⟩⟩ theorem continuous_of_metric [metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_tendsto.trans $ forall_congr $ λ b, tendsto_nhds_of_metric theorem exists_delta_of_continuous [metric_space β] {f : α → β} {ε:ℝ} (hf : continuous f) (hε : ε > 0) (b : α) : ∃ δ > 0, ∀a, dist a b ≤ δ → dist (f a) (f b) < ε := let ⟨δ, δ_pos, hδ⟩ := continuous_of_metric.1 hf b ε hε in ⟨δ / 2, half_pos δ_pos, assume a ha, hδ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos δ_pos⟩ theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- Instantiate the reals as a metric space. -/ instance : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg instance : orderable_topology ℝ := orderable_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff_metric.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := U, uniformity_dist := H.trans (@uniformity_dist α _) } def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } theorem metric_space.induced_uniform_embedding {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : by haveI := metric_space.induced f hf m; exact uniform_embedding f := by let := metric_space.induced f hf m; exactI uniform_embedding_of_metric.2 ⟨hf, uniform_continuous_comap, λ ε ε0, ⟨ε, ε0, λ a b, id⟩⟩ instance {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} [t : metric_space α] (x y : subtype p) : dist x y = dist x.1 y.1 := rfl instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_dist := begin refine uniformity_prod.trans _, simp [uniformity_dist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_of_metric.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp uniform_continuous_dist' theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp continuous_dist' theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, dist (f x) (g x)) x (nhds (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)), from continuous_iff_tendsto.mp continuous_dist' (a, b), (hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this) lemma nhds_comap_dist (a : α) : (nhds (0 : ℝ)).comap (λa', dist a' a) = nhds a := have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε, by simp [subset_def, real.dist_0_eq_abs], have h₂ : tendsto (λa', dist a' a) (nhds a) (nhds (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq_metric, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_comap.symm, tendsto] using h₂) lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (nhds a)) ↔ (tendsto (λb, dist (f b) a) x (nhds 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const section pi open finset lattice variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] instance has_dist_pi : has_dist (Πb, π b) := ⟨λf g, ((finset.sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)⟩ lemma dist_pi_def (f g : Πb, π b) : dist f g = (finset.sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl instance metric_space_pi : metric_space (Πb, π b) := { dist := dist, dist_self := assume f, (nnreal.coe_eq_zero _).2 $ bot_unique $ finset.sup_le $ by simp, dist_comm := assume f g, nnreal.eq_iff.2 $ by congr; ext a; exact nndist_comm _ _, dist_triangle := assume f g h, show dist f h ≤ (dist f g) + (dist g h), from begin simp only [dist_pi_def, (nnreal.coe_add _ _).symm, (nnreal.coe_le _ _).symm, finset.sup_le_iff], assume b hb, exact le_trans (nndist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_dist_eq_zero := assume f g eq0, begin simp only [dist_pi_def, nnreal.coe_eq_zero, nnreal.bot_eq_zero.symm, eq_bot_iff, finset.sup_le_iff] at eq0, exact (funext $ assume b, eq_of_nndist_eq_zero $ bot_unique $ eq0 b $ mem_univ b), end } end pi lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
5e35d2712dfb64f477ba3df3a388f8eae8a2f209
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/quadratic_discriminant.lean
ea3439b5e939a4558d7ffd935410b31ebcf2c552
[ "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
5,250
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.char_p.invertible import order.filter.at_top_bot import tactic.linarith import tactic.field_simp import tactic.linear_combination /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition - `discrim a b c`: the discriminant of a quadratic `a * x * x + b * x + c` is `b * b - 4 * a * c`. ## Main statements - `quadratic_eq_zero_iff`: roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant. - `quadratic_ne_zero_of_discrim_ne_sq`: if the discriminant has no square root, then the corresponding quadratic has no root. - `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ open filter section ring variables {R : Type*} /-- Discriminant of a quadratic -/ def discrim [ring R] (a b c : R) : R := b^2 - 4 * a * c variables [comm_ring R] [is_domain R] {a b c : R} /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_sq (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (x : R) : a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 := begin dsimp [discrim] at *, split, { assume h, linear_combination -4 * a * h }, { assume h, have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero h2 h2) ha, apply mul_left_cancel₀ ha, linear_combination -h } end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_sq (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (h : ∀ s : R, discrim a b c ≠ s * s) (x : R) : a * x * x + b * x + c ≠ 0 := begin assume h', rw [quadratic_eq_zero_iff_discrim_eq_sq h2 ha, sq] at h', exact h _ h' end end ring section field variables {K : Type*} [field K] [invertible (2 : K)] {a b c x : K} /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) : a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := begin have h2 : (2 : K) ≠ 0 := nonzero_of_invertible 2, rw [quadratic_eq_zero_iff_discrim_eq_sq h2 ha, h, sq, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero h2 ha, field_simp, apply or_congr, { split; intro h'; linear_combination -h' }, { split; intro h'; linear_combination h' }, end /-- A quadratic has roots if its discriminant has square roots -/ lemma exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) : a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := begin have : discrim a b c = 0 * 0, by rw [h, mul_zero], rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self] end end field section linear_ordered_field variables {K : Type*} [linear_ordered_field K] {a b c : K} /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discrim_le_zero (h : ∀ x : K, 0 ≤ a * x * x + b * x + c) : discrim a b c ≤ 0 := begin rw [discrim, sq], obtain ha|rfl|ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0, -- if a < 0 { have : tendsto (λ x, (a * x + b) * x + c) at_top at_bot := tendsto_at_bot_add_const_right _ c ((tendsto_at_bot_add_const_right _ b (tendsto_id.neg_const_mul_at_top ha)).at_bot_mul_at_top tendsto_id), rcases (this.eventually (eventually_lt_at_bot 0)).exists with ⟨x, hx⟩, exact false.elim ((h x).not_lt $ by rwa ← add_mul) }, -- if a = 0 { rcases em (b = 0) with (rfl|hb), { simp }, { have := h ((-c - 1) / b), rw [mul_div_cancel' _ hb] at this, linarith } }, -- if a > 0 { have := calc 4 * a * (a * (-(b / a) * (1 / 2)) * (-(b / a) * (1 / 2)) + b * (-(b / a) * (1 / 2)) + c) = (a * (b / a)) * (a * (b / a)) - 2 * (a * (b / a)) * b + 4 * a * c : by ring ... = -(b * b - 4 * a * c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4 * a, by linarith, have h := (mul_nonneg ha' (h (-(b / a) * (1 / 2)))), rw this at h, rwa ← neg_nonneg } end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * x * x + b * x + c) : discrim a b c < 0 := begin have : ∀ x : K, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discrim_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end end linear_ordered_field
1455e2d7934e5ca626ff2b7ffef1f04cf31c9183
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Init/Data/Format/Syntax.lean
14b035f9f26bf13f8373ee73807f8f63c1a0c917
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
1,822
lean
/- Copyright (c) 2021 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.Format.Macro import Init.Data.Format.Instances import Init.Meta namespace Lean.Syntax open Std open Std.Format private def formatInfo (showInfo : Bool) (info : SourceInfo) (f : Format) : Format := match showInfo, info with | true, SourceInfo.original lead pos trail endPos => f!"{lead}:{pos}:{f}:{endPos}:{trail}" | true, SourceInfo.synthetic pos endPos => f!"{pos}:{f}:{endPos}" | _, _ => f partial def formatStxAux (maxDepth : Option Nat) (showInfo : Bool) : Nat → Syntax → Format | _, atom info val => formatInfo showInfo info $ format (repr val) | _, ident info _ val pre => formatInfo showInfo info $ format "`" ++ format val | _, missing => "<missing>" | depth, node kind args => let depth := depth + 1; if kind == nullKind then sbracket $ if args.size > 0 && depth > maxDepth.getD depth then ".." else joinSep (args.toList.map (formatStxAux maxDepth showInfo depth)) line else let shorterName := kind.replacePrefix `Lean.Parser Name.anonymous; let header := format shorterName; let body : List Format := if args.size > 0 && depth > maxDepth.getD depth then [".."] else args.toList.map (formatStxAux maxDepth showInfo depth); paren $ joinSep (header :: body) line def formatStx (stx : Syntax) (maxDepth : Option Nat := none) (showInfo := false) : Format := formatStxAux maxDepth showInfo 0 stx instance : ToFormat (Syntax) := ⟨formatStx⟩ instance : ToString (Syntax) := ⟨@toString Format _ ∘ format⟩ end Lean.Syntax
6086c919f400320aa08b6bce202f46709ad8ab82
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/polynomial/content.lean
553e6d72747e378f5426413907b6963bdddd9ee8
[ "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
17,118
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.gcd_monoid.finset import data.polynomial import data.polynomial.erase_lead import data.polynomial.cancel_leads /-! # GCD structures on polynomials Definitions and basic results about polynomials over GCD domains, particularly their contents and primitive polynomials. ## Main Definitions Let `p : polynomial R`. - `p.content` is the `gcd` of the coefficients of `p`. - `p.is_primitive` indicates that `p.content = 1`. ## Main Results - `polynomial.content_mul`: If `p q : polynomial R`, then `(p * q).content = p.content * q.content`. - `polynomial.gcd_monoid`: The polynomial ring of a GCD domain is itself a GCD domain. -/ namespace polynomial section primitive variables {R : Type*} [comm_semiring R] /-- A polynomial is primitive when the only constant polynomials dividing it are units -/ def is_primitive (p : polynomial R) : Prop := ∀ (r : R), C r ∣ p → is_unit r lemma is_primitive_iff_is_unit_of_C_dvd {p : polynomial R} : p.is_primitive ↔ ∀ (r : R), C r ∣ p → is_unit r := iff.rfl @[simp] lemma is_primitive_one : is_primitive (1 : polynomial R) := λ r h, is_unit_C.mp (is_unit_of_dvd_one (C r) h) lemma monic.is_primitive {p : polynomial R} (hp : p.monic) : p.is_primitive := begin rintros r ⟨q, h⟩, exact is_unit_of_mul_eq_one r (q.coeff p.nat_degree) (by rwa [←coeff_C_mul, ←h]), end lemma is_primitive.ne_zero [nontrivial R] {p : polynomial R} (hp : p.is_primitive) : p ≠ 0 := begin rintro rfl, exact (hp 0 (dvd_zero (C 0))).ne_zero rfl, end end primitive variables {R : Type*} [integral_domain R] section gcd_monoid variable [gcd_monoid R] /-- `p.content` is the `gcd` of the coefficients of `p`. -/ def content (p : polynomial R) : R := (p.support).gcd p.coeff lemma content_dvd_coeff {p : polynomial R} (n : ℕ) : p.content ∣ p.coeff n := begin by_cases h : n ∈ p.support, { apply finset.gcd_dvd h }, rw [mem_support_iff, not_not] at h, rw h, apply dvd_zero, end @[simp] lemma content_C {r : R} : (C r).content = normalize r := begin rw content, by_cases h0 : r = 0, { simp [h0] }, have h : (C r).support = {0} := support_monomial _ _ h0, simp [h], end @[simp] lemma content_zero : content (0 : polynomial R) = 0 := by rw [← C_0, content_C, normalize_zero] @[simp] lemma content_one : content (1 : polynomial R) = 1 := by rw [← C_1, content_C, normalize_one] lemma content_X_mul {p : polynomial R} : content (X * p) = content p := begin rw [content, content, finset.gcd_def, finset.gcd_def], refine congr rfl _, have h : (X * p).support = p.support.map ⟨nat.succ, nat.succ_injective⟩, { ext a, simp only [exists_prop, finset.mem_map, function.embedding.coe_fn_mk, ne.def, mem_support_iff], cases a, { simp [coeff_X_mul_zero, nat.succ_ne_zero] }, rw [mul_comm, coeff_mul_X], split, { intro h, use a, simp [h] }, { rintros ⟨b, ⟨h1, h2⟩⟩, rw ← nat.succ_injective h2, apply h1 } }, rw h, simp only [finset.map_val, function.comp_app, function.embedding.coe_fn_mk, multiset.map_map], refine congr (congr rfl _) rfl, ext a, rw mul_comm, simp [coeff_mul_X], end @[simp] lemma content_X_pow {k : ℕ} : content ((X : polynomial R) ^ k) = 1 := begin induction k with k hi, { simp }, rw [pow_succ, content_X_mul, hi] end @[simp] lemma content_X : content (X : polynomial R) = 1 := by { rw [← mul_one X, content_X_mul, content_one] } lemma content_C_mul (r : R) (p : polynomial R) : (C r * p).content = normalize r * p.content := begin by_cases h0 : r = 0, { simp [h0] }, rw content, rw content, rw ← finset.gcd_mul_left, refine congr (congr rfl _) _; ext; simp [h0, mem_support_iff] end @[simp] lemma content_monomial {r : R} {k : ℕ} : content (monomial k r) = normalize r := by { rw [monomial_eq_C_mul_X, content_C_mul, content_X_pow, mul_one] } lemma content_eq_zero_iff {p : polynomial R} : content p = 0 ↔ p = 0 := begin rw [content, finset.gcd_eq_zero_iff], split; intro h, { ext n, by_cases h0 : n ∈ p.support, { rw [h n h0, coeff_zero], }, { rw mem_support_iff at h0, push_neg at h0, simp [h0] } }, { intros x h0, simp [h] } end @[simp] lemma normalize_content {p : polynomial R} : normalize p.content = p.content := finset.normalize_gcd lemma content_eq_gcd_range_of_lt (p : polynomial R) (n : ℕ) (h : p.nat_degree < n) : p.content = (finset.range n).gcd p.coeff := begin apply dvd_antisymm_of_normalize_eq normalize_content finset.normalize_gcd, { rw finset.dvd_gcd_iff, intros i hi, apply content_dvd_coeff _ }, { apply finset.gcd_mono, intro i, simp only [nat.lt_succ_iff, mem_support_iff, ne.def, finset.mem_range], contrapose!, intro h1, apply coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le h h1), } end lemma content_eq_gcd_range_succ (p : polynomial R) : p.content = (finset.range p.nat_degree.succ).gcd p.coeff := content_eq_gcd_range_of_lt _ _ (nat.lt_succ_self _) lemma content_eq_gcd_leading_coeff_content_erase_lead (p : polynomial R) : p.content = gcd_monoid.gcd p.leading_coeff (erase_lead p).content := begin by_cases h : p = 0, { simp [h] }, rw [← leading_coeff_eq_zero, leading_coeff, ← ne.def, ← mem_support_iff] at h, rw [content, ← finset.insert_erase h, finset.gcd_insert, leading_coeff, content, erase_lead_support], refine congr rfl (finset.gcd_congr rfl (λ i hi, _)), rw finset.mem_erase at hi, rw [erase_lead_coeff, if_neg hi.1], end lemma dvd_content_iff_C_dvd {p : polynomial R} {r : R} : r ∣ p.content ↔ C r ∣ p := begin rw C_dvd_iff_dvd_coeff, split, { intros h i, apply dvd_trans h (content_dvd_coeff _) }, { intro h, rw [content, finset.dvd_gcd_iff], intros i hi, apply h i } end lemma C_content_dvd (p : polynomial R) : C p.content ∣ p := dvd_content_iff_C_dvd.1 (dvd_refl _) lemma is_primitive_iff_content_eq_one {p : polynomial R} : p.is_primitive ↔ p.content = 1 := begin rw [←normalize_content, normalize_eq_one, is_primitive], simp_rw [←dvd_content_iff_C_dvd], exact ⟨λ h, h p.content (dvd_refl p.content), λ h r hdvd, is_unit_of_dvd_unit hdvd h⟩, end lemma is_primitive.content_eq_one {p : polynomial R} (hp : p.is_primitive) : p.content = 1 := is_primitive_iff_content_eq_one.mp hp open_locale classical noncomputable theory section prim_part /-- The primitive part of a polynomial `p` is the primitive polynomial gained by dividing `p` by `p.content`. If `p = 0`, then `p.prim_part = 1`. -/ def prim_part (p : polynomial R) : polynomial R := if p = 0 then 1 else classical.some (C_content_dvd p) lemma eq_C_content_mul_prim_part (p : polynomial R) : p = C p.content * p.prim_part := begin by_cases h : p = 0, { simp [h] }, rw [prim_part, if_neg h, ← classical.some_spec (C_content_dvd p)], end @[simp] lemma prim_part_zero : prim_part (0 : polynomial R) = 1 := if_pos rfl lemma is_primitive_prim_part (p : polynomial R) : p.prim_part.is_primitive := begin by_cases h : p = 0, { simp [h] }, rw ← content_eq_zero_iff at h, rw is_primitive_iff_content_eq_one, apply mul_left_cancel' h, conv_rhs { rw [p.eq_C_content_mul_prim_part, mul_one, content_C_mul, normalize_content] } end lemma content_prim_part (p : polynomial R) : p.prim_part.content = 1 := p.is_primitive_prim_part.content_eq_one lemma prim_part_ne_zero (p : polynomial R) : p.prim_part ≠ 0 := p.is_primitive_prim_part.ne_zero lemma nat_degree_prim_part (p : polynomial R) : p.prim_part.nat_degree = p.nat_degree := begin by_cases h : C p.content = 0, { rw [C_eq_zero, content_eq_zero_iff] at h, simp [h] }, conv_rhs { rw [p.eq_C_content_mul_prim_part, nat_degree_mul h p.prim_part_ne_zero, nat_degree_C, zero_add] }, end @[simp] lemma is_primitive.prim_part_eq {p : polynomial R} (hp : p.is_primitive) : p.prim_part = p := by rw [← one_mul p.prim_part, ← C_1, ← hp.content_eq_one, ← p.eq_C_content_mul_prim_part] lemma is_unit_prim_part_C (r : R) : is_unit (C r).prim_part := begin by_cases h0 : r = 0, { simp [h0] }, unfold is_unit, refine ⟨⟨C ↑(norm_unit r)⁻¹, C ↑(norm_unit r), by rw [← ring_hom.map_mul, units.inv_mul, C_1], by rw [← ring_hom.map_mul, units.mul_inv, C_1]⟩, _⟩, rw [← normalize_eq_zero, ← C_eq_zero] at h0, apply mul_left_cancel' h0, conv_rhs { rw [← content_C, ← (C r).eq_C_content_mul_prim_part], }, simp only [units.coe_mk, normalize_apply, ring_hom.map_mul], rw [mul_assoc, ← ring_hom.map_mul, units.mul_inv, C_1, mul_one], end lemma prim_part_dvd (p : polynomial R) : p.prim_part ∣ p := dvd.intro_left (C p.content) p.eq_C_content_mul_prim_part.symm end prim_part lemma gcd_content_eq_of_dvd_sub {a : R} {p q : polynomial R} (h : C a ∣ p - q) : gcd_monoid.gcd a p.content = gcd_monoid.gcd a q.content := begin rw content_eq_gcd_range_of_lt p (max p.nat_degree q.nat_degree).succ (lt_of_le_of_lt (le_max_left _ _) (nat.lt_succ_self _)), rw content_eq_gcd_range_of_lt q (max p.nat_degree q.nat_degree).succ (lt_of_le_of_lt (le_max_right _ _) (nat.lt_succ_self _)), apply finset.gcd_eq_of_dvd_sub, intros x hx, cases h with w hw, use w.coeff x, rw [← coeff_sub, hw, coeff_C_mul] end lemma content_mul_aux {p q : polynomial R} : gcd_monoid.gcd (p * q).erase_lead.content p.leading_coeff = gcd_monoid.gcd (p.erase_lead * q).content p.leading_coeff := begin rw [gcd_comm (content _) _, gcd_comm (content _) _], apply gcd_content_eq_of_dvd_sub, rw [← self_sub_C_mul_X_pow, ← self_sub_C_mul_X_pow, sub_mul, sub_sub, add_comm, sub_add, sub_sub_cancel, leading_coeff_mul, ring_hom.map_mul, mul_assoc, mul_assoc], apply dvd_sub (dvd.intro _ rfl) (dvd.intro _ rfl), end @[simp] theorem content_mul {p q : polynomial R} : (p * q).content = p.content * q.content := begin classical, suffices h : ∀ (n : ℕ) (p q : polynomial R), ((p * q).degree < n) → (p * q).content = p.content * q.content, { apply h, apply (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_succ_self _))) }, intro n, induction n with n ih, { intros p q hpq, rw [with_bot.coe_zero, nat.with_bot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq, rcases hpq with rfl | rfl; simp }, intros p q hpq, by_cases p0 : p = 0, { simp [p0] }, by_cases q0 : q = 0, { simp [q0] }, rw [degree_eq_nat_degree (mul_ne_zero p0 q0), with_bot.coe_lt_coe, nat.lt_succ_iff_lt_or_eq, ← with_bot.coe_lt_coe, ← degree_eq_nat_degree (mul_ne_zero p0 q0), nat_degree_mul p0 q0] at hpq, rcases hpq with hlt | heq, { apply ih _ _ hlt }, rw [← p.nat_degree_prim_part, ← q.nat_degree_prim_part, ← with_bot.coe_eq_coe, with_bot.coe_add, ← degree_eq_nat_degree p.prim_part_ne_zero, ← degree_eq_nat_degree q.prim_part_ne_zero] at heq, rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part], suffices h : (q.prim_part * p.prim_part).content = 1, { rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.prim_part, mul_assoc, content_C_mul, content_C_mul, h, mul_one, content_prim_part, content_prim_part, mul_one, mul_one] }, rw [← normalize_content, normalize_eq_one, is_unit_iff_dvd_one, content_eq_gcd_leading_coeff_content_erase_lead, leading_coeff_mul, gcd_comm], apply dvd_trans (gcd_mul_dvd_mul_gcd _ _ _), rw [content_mul_aux, ih, content_prim_part, mul_one, gcd_comm, ← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part, one_mul, mul_comm q.prim_part, content_mul_aux, ih, content_prim_part, mul_one, gcd_comm, ← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part], { rw [← heq, degree_mul, with_bot.add_lt_add_iff_right], { apply degree_erase_lt p.prim_part_ne_zero }, { rw [bot_lt_iff_ne_bot, ne.def, degree_eq_bot], apply q.prim_part_ne_zero } }, { rw [mul_comm, ← heq, degree_mul, with_bot.add_lt_add_iff_left], { apply degree_erase_lt q.prim_part_ne_zero }, { rw [bot_lt_iff_ne_bot, ne.def, degree_eq_bot], apply p.prim_part_ne_zero } } end theorem is_primitive.mul {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) : (p * q).is_primitive := by rw [is_primitive_iff_content_eq_one, content_mul, hp.content_eq_one, hq.content_eq_one, mul_one] @[simp] theorem prim_part_mul {p q : polynomial R} (h0 : p * q ≠ 0) : (p * q).prim_part = p.prim_part * q.prim_part := begin rw [ne.def, ← content_eq_zero_iff, ← C_eq_zero] at h0, apply mul_left_cancel' h0, conv_lhs { rw [← (p * q).eq_C_content_mul_prim_part, p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part] }, rw [content_mul, ring_hom.map_mul], ring, end lemma is_primitive.is_primitive_of_dvd {p q : polynomial R} (hp : p.is_primitive) (hdvd : q ∣ p) : q.is_primitive := begin rcases hdvd with ⟨r, rfl⟩, rw [is_primitive_iff_content_eq_one, ← normalize_content, normalize_eq_one, is_unit_iff_dvd_one], apply dvd.intro r.content, rwa [is_primitive_iff_content_eq_one, content_mul] at hp, end lemma is_primitive.dvd_prim_part_iff_dvd {p q : polynomial R} (hp : p.is_primitive) (hq : q ≠ 0) : p ∣ q.prim_part ↔ p ∣ q := begin refine ⟨λ h, dvd.trans h (dvd.intro_left _ q.eq_C_content_mul_prim_part.symm), λ h, _⟩, rcases h with ⟨r, rfl⟩, apply dvd.intro _, rw [prim_part_mul hq, hp.prim_part_eq], end theorem exists_primitive_lcm_of_is_primitive {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) : ∃ r : polynomial R, r.is_primitive ∧ (∀ s : polynomial R, p ∣ s ∧ q ∣ s ↔ r ∣ s) := begin classical, have h : ∃ (n : ℕ) (r : polynomial R), r.nat_degree = n ∧ r.is_primitive ∧ p ∣ r ∧ q ∣ r := ⟨(p * q).nat_degree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩, rcases nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩, refine ⟨r, rprim, λ s, ⟨_, λ rs, ⟨dvd.trans pr rs, dvd.trans qr rs⟩⟩⟩, suffices hs : ∀ (n : ℕ) (s : polynomial R), s.nat_degree = n → (p ∣ s ∧ q ∣ s → r ∣ s), { apply hs s.nat_degree s rfl }, clear s, by_contra con, push_neg at con, rcases nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩, have s0 : s ≠ 0, { contrapose! rs, simp [rs] }, have hs := nat.find_min' h ⟨_, s.nat_degree_prim_part, s.is_primitive_prim_part, (hp.dvd_prim_part_iff_dvd s0).2 ps, (hq.dvd_prim_part_iff_dvd s0).2 qs⟩, rw ← rdeg at hs, by_cases sC : s.nat_degree ≤ 0, { rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), is_primitive_iff_content_eq_one, content_C, normalize_eq_one] at rprim, rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs, apply rs rprim.dvd }, have hcancel := nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree hs (lt_of_not_ge sC), rw sdeg at hcancel, apply nat.find_min con hcancel, refine ⟨_, rfl, ⟨dvd_cancel_leads_of_dvd_of_dvd pr ps, dvd_cancel_leads_of_dvd_of_dvd qr qs⟩, λ rcs, rs _⟩, rw ← rprim.dvd_prim_part_iff_dvd s0, rw [cancel_leads, nat.sub_eq_zero_of_le hs, pow_zero, mul_one] at rcs, have h := dvd_add rcs (dvd.intro_left _ rfl), have hC0 := rprim.ne_zero, rw [ne.def, ← leading_coeff_eq_zero, ← C_eq_zero] at hC0, rw [sub_add_cancel, ← rprim.dvd_prim_part_iff_dvd (mul_ne_zero hC0 s0)] at h, rcases is_unit_prim_part_C r.leading_coeff with ⟨u, hu⟩, apply dvd.trans h (dvd_of_associated (associated.symm ⟨u, _⟩)), rw [prim_part_mul (mul_ne_zero hC0 s0), hu, mul_comm], end lemma dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part {p q : polynomial R} (hq : q ≠ 0) : p ∣ q ↔ p.content ∣ q.content ∧ p.prim_part ∣ q.prim_part := begin split; intro h, { rcases h with ⟨r, rfl⟩, rw [content_mul, p.is_primitive_prim_part.dvd_prim_part_iff_dvd hq], exact ⟨dvd.intro _ rfl, dvd.trans p.prim_part_dvd (dvd.intro _ rfl)⟩ }, { rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part], exact mul_dvd_mul (ring_hom.map_dvd C h.1) h.2 } end @[priority 100] instance gcd_monoid : gcd_monoid (polynomial R) := gcd_monoid_of_exists_lcm $ λ p q, begin rcases exists_primitive_lcm_of_is_primitive p.is_primitive_prim_part q.is_primitive_prim_part with ⟨r, rprim, hr⟩, refine ⟨C (lcm p.content q.content) * r, λ s, _⟩, by_cases hs : s = 0, { simp [hs] }, by_cases hpq : C (lcm p.content q.content) = 0, { rw [C_eq_zero, lcm_eq_zero_iff, content_eq_zero_iff, content_eq_zero_iff] at hpq, rcases hpq with hpq | hpq; simp [hpq, hs] }, iterate 3 { rw dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part hs }, rw [content_mul, rprim.content_eq_one, mul_one, content_C, normalize_lcm, lcm_dvd_iff, prim_part_mul (mul_ne_zero hpq rprim.ne_zero), rprim.prim_part_eq, is_unit.mul_left_dvd _ _ _ (is_unit_prim_part_C (lcm p.content q.content)), ← hr s.prim_part], tauto, end end gcd_monoid end polynomial
57357a131feba95d66af729b783ef714102ed26d
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/analysis/calculus/specific_functions.lean
cafcda83f2009d48666a625c5168e0314f021253
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,060
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.extend_deriv import analysis.calculus.iterated_deriv import analysis.special_functions.exp_log import analysis.normed_space.inner_product import topology.algebra.polynomial /-! # Infinitely smooth bump function In this file we construct several infinitely smooth functions with properties that an analytic function cannot have: * `exp_neg_inv_glue` is equal to zero for `x ≤ 0` and is strictly positive otherwise; it is given by `x ↦ exp (-1/x)` for `x > 0`; * `smooth_transition` is equal to zero for `x ≤ 0` and is equal to one for `x ≥ 1`; it is given by `exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))`; * `smooth_bump_function` is equal to one on the closed ball of radius `1` and is equal to `0` outside of the open ball of radius `2`. -/ noncomputable theory open_locale classical topological_space open polynomial real filter set /-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0` for `x ≤ 0`. It is a basic building block to construct smooth partitions of unity. Its main property is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in `exp_neg_inv_glue.smooth`. -/ def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹) namespace exp_neg_inv_glue /-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`, where `P_aux n` is computed inductively. -/ noncomputable def P_aux : ℕ → polynomial ℝ | 0 := 1 | (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n) /-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/ def f_aux (n : ℕ) (x : ℝ) : ℝ := if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n) /-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/ lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue := begin ext x, by_cases h : x ≤ 0, { simp [exp_neg_inv_glue, f_aux, h] }, { simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] } end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` (given in this statement in unfolded form) is the `n+1`-th auxiliary function, since the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/ lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) : has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin have A : ∀k:ℕ, 2 * (k + 1) - 1 = 2 * k + 1, { assume k, rw nat.sub_eq_iff_eq_add, { ring }, { simpa [mul_add] using add_le_add (zero_le (2 * k)) one_le_two } }, convert (((P_aux n).has_deriv_at x).mul (((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div (has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1, field_simp [hx, P_aux], -- `ring_exp` can't solve `p ∨ q` goal generated by `mul_eq_mul_right_iff` cases n; simp [nat.succ_eq_add_one, A, -mul_eq_mul_right_iff]; ring_exp end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` is the `n+1`-th auxiliary function. -/ lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) : has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq, filter_upwards [lt_mem_nhds hx], assume y hy, simp [f_aux, hy.not_le] end /-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit is `0`, to be able to apply general differentiability extension theorems. This limit is checked in this lemma. -/ lemma f_aux_limit (n : ℕ) : tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0) := begin have A : tendsto (λx, (P_aux n).eval x) (𝓝[Ioi 0] 0) (𝓝 ((P_aux n).eval 0)) := (P_aux n).continuous_within_at, have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0), { convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top, ext x, field_simp }, convert A.mul B; simp [mul_div_assoc] end /-- Deduce from the limiting behavior at `0` of its derivative and general differentiability extension theorems that the auxiliary function `f_aux n` is differentiable at `0`, with derivative `0`. -/ lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 := begin -- we check separately differentiability on the left and on the right have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0, { apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr, { assume y hy, simp at hy, simp [f_aux, hy] }, { simp [f_aux, le_refl] } }, have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0, { have diff : differentiable_on ℝ (f_aux n) (Ioi 0) := λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within, { refine (f_aux_limit (n+1)).congr' _, apply mem_sets_of_superset self_mem_nhds_within (λx hx, _), simp [(f_aux_deriv_pos n x hx).deriv] }, { have : f_aux n 0 = 0, by simp [f_aux, le_refl], simp only [continuous_within_at, this], refine (f_aux_limit n).congr' _, apply mem_sets_of_superset self_mem_nhds_within (λx hx, _), have : ¬(x ≤ 0), by simpa using hx, simp [f_aux, this] } }, simpa using A.union B, end /-- At every point, the auxiliary function `f_aux n` has a derivative which is equal to `f_aux (n+1)`. -/ lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x := begin -- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done -- in `f_aux_deriv_pos`, and for `x = 0`, done in -- `f_aux_deriv_zero`. rcases lt_trichotomy x 0 with hx|hx|hx, { have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx], rw this, apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq, filter_upwards [gt_mem_nhds hx], assume y hy, simp [f_aux, hy.le] }, { have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl], rw [hx, this], exact f_aux_deriv_zero n }, { have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)), by simp [f_aux, not_le_of_gt hx], rw this, exact f_aux_deriv_pos n x hx }, end /-- The successive derivatives of the auxiliary function `f_aux 0` are the functions `f_aux n`, by induction. -/ lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n := begin induction n with n IH, { simp }, { simp [iterated_deriv_succ, IH], ext x, exact (f_aux_has_deriv_at n x).deriv } end /-- The function `exp_neg_inv_glue` is smooth. -/ protected theorem times_cont_diff {n} : times_cont_diff ℝ n exp_neg_inv_glue := begin rw ← f_aux_zero_eq, apply times_cont_diff_of_differentiable_iterated_deriv (λ m hm, _), rw f_aux_iterated_deriv m, exact λ x, (f_aux_has_deriv_at m x).differentiable_at end /-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/ lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 := by simp [exp_neg_inv_glue, hx] /-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/ lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x := by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos] /-- The function exp_neg_inv_glue` is nonnegative. -/ lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x := begin cases le_or_gt x 0, { exact ge_of_eq (zero_of_nonpos h) }, { exact le_of_lt (pos_of_pos h) } end end exp_neg_inv_glue /-- An infinitely smooth function `f : ℝ → ℝ` such that `f x = 0` for `x ≤ 0`, `f x = 1` for `1 ≤ x`, and `0 < f x < 1` for `0 < x < 1`. -/ def smooth_transition (x : ℝ) : ℝ := exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x)) namespace smooth_transition variables {x : ℝ} open exp_neg_inv_glue lemma pos_denom (x) : 0 < exp_neg_inv_glue x + exp_neg_inv_glue (1 - x) := ((@zero_lt_one ℝ _ _).lt_or_lt x).elim (λ hx, add_pos_of_pos_of_nonneg (pos_of_pos hx) (nonneg _)) (λ hx, add_pos_of_nonneg_of_pos (nonneg _) (pos_of_pos $ sub_pos.2 hx)) lemma one_of_one_le (h : 1 ≤ x) : smooth_transition x = 1 := (div_eq_one_iff_eq $ (pos_denom x).ne').2 $ by rw [zero_of_nonpos (sub_nonpos.2 h), add_zero] lemma zero_of_nonpos (h : x ≤ 0) : smooth_transition x = 0 := by rw [smooth_transition, zero_of_nonpos h, zero_div] lemma le_one (x : ℝ) : smooth_transition x ≤ 1 := (div_le_one (pos_denom x)).2 $ le_add_of_nonneg_right (nonneg _) lemma nonneg (x : ℝ) : 0 ≤ smooth_transition x := div_nonneg (exp_neg_inv_glue.nonneg _) (pos_denom x).le lemma lt_one_of_lt_one (h : x < 1) : smooth_transition x < 1 := (div_lt_one $ pos_denom x).2 $ lt_add_of_pos_right _ $ pos_of_pos $ sub_pos.2 h lemma pos_of_pos (h : 0 < x) : 0 < smooth_transition x := div_pos (exp_neg_inv_glue.pos_of_pos h) (pos_denom x) protected lemma times_cont_diff {n} : times_cont_diff ℝ n smooth_transition := exp_neg_inv_glue.times_cont_diff.div (exp_neg_inv_glue.times_cont_diff.add $ exp_neg_inv_glue.times_cont_diff.comp $ times_cont_diff_const.sub times_cont_diff_id) $ λ x, (pos_denom x).ne' protected lemma times_cont_diff_at {x n} : times_cont_diff_at ℝ n smooth_transition x := smooth_transition.times_cont_diff.times_cont_diff_at end smooth_transition variables {E : Type*} /-- A function `f : E → ℝ` defined on a real inner product space with the following properties: - `f` is infinitely smooth on `E`; - `f` is positive on `ball 0 2` and equals zero otherwise; - `f` is equal to `1` on `closed_ball 0 1`. -/ def smooth_bump_function [inner_product_space ℝ E] (x : E) := smooth_transition (2 - ∥x∥) namespace smooth_bump_function variable [inner_product_space ℝ E] open smooth_transition lemma one_of_norm_le_one {x : E} (hx : ∥x∥ ≤ 1) : smooth_bump_function x = 1 := one_of_one_le (le_sub.2 $ by { norm_num1, assumption }) lemma nonneg (x : E) : 0 ≤ smooth_bump_function x := nonneg _ lemma le_one (x : E) : smooth_bump_function x ≤ 1 := le_one _ lemma pos_of_norm_lt_two {x : E} (hx : ∥x∥ < 2) : 0 < smooth_bump_function x := pos_of_pos $ sub_pos.2 hx lemma lt_one_of_one_lt_norm {x : E} (hx : 1 < ∥x∥) : smooth_bump_function x < 1 := lt_one_of_lt_one $ sub_lt.2 $ by norm_num [hx] lemma zero_of_two_le_norm {x : E} (hx : 2 ≤ ∥x∥) : smooth_bump_function x = 0 := zero_of_nonpos $ sub_nonpos.2 hx lemma support_eq : function.support (smooth_bump_function : E → ℝ) = metric.ball 0 2 := begin ext x, suffices : smooth_bump_function x ≠ 0 ↔ ∥x∥ < 2, by simpa [function.mem_support], cases lt_or_le (∥x∥) 2 with hx hx, { simp [hx, (pos_of_norm_lt_two hx).ne'] }, { simp [hx.not_lt, zero_of_two_le_norm hx] } end lemma eventually_eq_one_of_norm_lt_one {x : E} (hx : ∥x∥ < 1) : smooth_bump_function =ᶠ[𝓝 x] (λ _, 1) := ((is_open_lt continuous_norm continuous_const).eventually_mem hx).mono $ λ y hy, one_of_norm_le_one (le_of_lt hy) lemma eventually_eq_one : smooth_bump_function =ᶠ[𝓝 (0 : E)] (λ _, 1) := eventually_eq_one_of_norm_lt_one (by simp only [norm_zero, zero_lt_one]) protected lemma times_cont_diff_at {x : E} {n} : times_cont_diff_at ℝ n smooth_bump_function x := begin rcases em (x = 0) with rfl|hx, { exact times_cont_diff_at.congr_of_eventually_eq times_cont_diff_at_const eventually_eq_one }, { exact smooth_transition.times_cont_diff_at.comp x (times_cont_diff_at_const.sub $ times_cont_diff_at_norm hx) } end protected lemma times_cont_diff {n} : times_cont_diff ℝ n (smooth_bump_function : E → ℝ) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, smooth_bump_function.times_cont_diff_at protected lemma times_cont_diff_within_at {x : E} {s n} : times_cont_diff_within_at ℝ n smooth_bump_function s x := smooth_bump_function.times_cont_diff_at.times_cont_diff_within_at end smooth_bump_function open function finite_dimensional metric /-- If `E` is a finite dimensional normed space over `ℝ`, then for any point `x : E` and its neighborhood `s` there exists an infinitely smooth function with the following properties: * `f y = 1` in a neighborhood of `x`; * `f y = 0` outside of `s`; * moreover, `closure (support f) ⊆ s` and `closure (support f)` is a compact set; * `f y ∈ [0, 1]` for all `y`. -/ lemma exists_times_cont_diff_bump_function_of_mem_nhds [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {x : E} {s : set E} (hs : s ∈ 𝓝 x) : ∃ f : E → ℝ, f =ᶠ[𝓝 x] 1 ∧ (∀ y, f y ∈ Icc (0 : ℝ) 1) ∧ times_cont_diff ℝ ⊤ f ∧ is_compact (closure $ support f) ∧ closure (support f) ⊆ s := begin have e : E ≃L[ℝ] euclidean_space ℝ (fin $ findim ℝ E) := continuous_linear_equiv.of_findim_eq findim_euclidean_space_fin.symm, have : e '' s ∈ 𝓝 (e x) := e.to_homeomorph.is_open_map.image_mem_nhds hs, rcases nhds_basis_closed_ball.mem_iff.1 this with ⟨ε, ε0 : 0 < ε, hε⟩, set g : E → euclidean_space ℝ (fin $ findim ℝ E) := λ y, (2 / ε) • (e y - e x), have hg : times_cont_diff ℝ ⊤ g, from times_cont_diff_const.smul (e.times_cont_diff.sub times_cont_diff_const), have hg0 : g x = 0 := by { simp only [g], simp }, -- `simp [g]` fails have hsupp : closure (support (smooth_bump_function ∘ g)) ⊆ e.symm '' closed_ball (e x) ε, { simp only [support_comp_eq_preimage, smooth_bump_function.support_eq, preimage, ball_0_eq, mem_set_of_eq, e.image_symm_eq_preimage], refine subset.trans (closure_lt_subset_le hg.continuous.norm continuous_const) _, intros y hy, have : 2 / ε * ∥e y - e x∥ ≤ 2, by simpa [g, norm_smul, real.norm_of_nonneg ε0.le] using hy, rwa [mul_comm, ← mul_div_assoc, div_le_iff ε0, mul_comm, mul_le_mul_left (@zero_lt_two ℝ _ _), ← dist_eq_norm] at this }, refine ⟨smooth_bump_function ∘ g, _, _, _, _, _⟩, { exact (hg.continuous.tendsto' _ _ hg0).eventually smooth_bump_function.eventually_eq_one }, { exact λ y, ⟨smooth_bump_function.nonneg _, smooth_bump_function.le_one _⟩ }, { exact smooth_bump_function.times_cont_diff.comp hg }, { exact compact_of_is_closed_subset ((proper_space.compact_ball _ _).image e.symm.continuous) is_closed_closure hsupp }, { refine subset.trans hsupp _, rwa [image_subset_iff, ← e.image_eq_preimage] } end
8b0c9abd1ad4c357147f19b70a9370d99edbb5e6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/preadditive/projective_resolution.lean
f13e48671389a1e5ebaa3601d002ee8eaec8580c
[ "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
12,928
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.projective import algebra.homology.single import algebra.homology.homotopy_category /-! # Projective resolutions A projective resolution `P : ProjectiveResolution Z` of an object `Z : C` consists of a `ℕ`-indexed chain complex `P.complex` of projective objects, along with a chain map `P.π` from `C` to the chain complex consisting just of `Z` in degree zero, so that the augmented chain complex is exact. When `C` is abelian, this exactness condition is equivalent to `π` being a quasi-isomorphism. It turns out that this formulation allows us to set up the basic theory of derived functors without even assuming `C` is abelian. (Typically, however, to show `has_projective_resolutions C` one will assume `enough_projectives C` and `abelian C`. This construction appears in `category_theory.abelian.projectives`.) We show that given `P : ProjectiveResolution X` and `Q : ProjectiveResolution Y`, any morphism `X ⟶ Y` admits a lift to a chain map `P.complex ⟶ Q.complex`. (It is a lift in the sense that the projection maps `P.π` and `Q.π` intertwine the lift and the original morphism.) Moreover, we show that any two such lifts are homotopic. As a consequence, if every object admits a projective resolution, we can construct a functor `projective_resolutions C : C ⥤ homotopy_category C`. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] open projective section variables [has_zero_object C] [has_zero_morphisms C] [has_equalizers C] [has_images C] /-- A `ProjectiveResolution Z` consists of a bundled `ℕ`-indexed chain complex of projective objects, along with a quasi-isomorphism to the complex consisting of just `Z` supported in degree `0`. (We don't actually ask here that the chain map is a quasi-iso, just exactness everywhere: that `π` is a quasi-iso is a lemma when the category is abelian. Should we just ask for it here?) Except in situations where you want to provide a particular projective resolution (for example to compute a derived functor), you will not typically need to use this bundled object, and will instead use * `projective_resolution Z`: the `ℕ`-indexed chain complex (equipped with `projective` and `exact` instances) * `projective_resolution.π Z`: the chain map from `projective_resolution Z` to `(single C _ 0).obj Z` (all the components are equipped with `epi` instances, and when the category is `abelian` we will show `π` is a quasi-iso). -/ @[nolint has_inhabited_instance] structure ProjectiveResolution (Z : C) := (complex : chain_complex C ℕ) (π : homological_complex.hom complex ((chain_complex.single₀ C).obj Z)) (projective : ∀ n, projective (complex.X n) . tactic.apply_instance) (exact₀ : exact (complex.d 1 0) (π.f 0) . tactic.apply_instance) (exact : ∀ n, exact (complex.d (n+2) (n+1)) (complex.d (n+1) n) . tactic.apply_instance) (epi : epi (π.f 0) . tactic.apply_instance) attribute [instance] ProjectiveResolution.projective ProjectiveResolution.exact₀ ProjectiveResolution.exact ProjectiveResolution.epi /-- An object admits a projective resolution. -/ class has_projective_resolution (Z : C) : Prop := (out [] : nonempty (ProjectiveResolution Z)) section variables (C) /-- You will rarely use this typeclass directly: it is implied by the combination `[enough_projectives C]` and `[abelian C]`. By itself it's enough to set up the basic theory of derived functors. -/ class has_projective_resolutions : Prop := (out : ∀ Z : C, has_projective_resolution Z) attribute [instance, priority 100] has_projective_resolutions.out end namespace ProjectiveResolution @[simp] lemma π_f_succ {Z : C} (P : ProjectiveResolution Z) (n : ℕ) : P.π.f (n+1) = 0 := begin apply zero_of_target_iso_zero, dsimp, refl, end instance {Z : C} (P : ProjectiveResolution Z) (n : ℕ) : category_theory.epi (P.π.f n) := by cases n; apply_instance /-- A projective object admits a trivial projective resolution: itself in degree 0. -/ def self (Z : C) [category_theory.projective Z] : ProjectiveResolution Z := { complex := (chain_complex.single₀ C).obj Z, π := 𝟙 ((chain_complex.single₀ C).obj Z), projective := λ n, begin cases n, { dsimp, apply_instance, }, { dsimp, apply_instance, }, end, exact₀ := by { dsimp, apply_instance, }, exact := λ n, by { dsimp, apply_instance, }, epi := by { dsimp, apply_instance, }, } /-- Auxiliary construction for `lift`. -/ def lift_f_zero {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 0 ⟶ Q.complex.X 0 := factor_thru (P.π.f 0 ≫ f) (Q.π.f 0) /-- Auxiliary construction for `lift`. -/ def lift_f_one {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 1 ⟶ Q.complex.X 1 := exact.lift (P.complex.d 1 0 ≫ lift_f_zero f P Q) (Q.complex.d 1 0) (Q.π.f 0) (by simp [lift_f_zero]) /-- Auxiliary lemma for `lift`. -/ @[simp] lemma lift_f_one_zero_comm {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift_f_one f P Q ≫ Q.complex.d 1 0 = P.complex.d 1 0 ≫ lift_f_zero f P Q := begin dsimp [lift_f_zero, lift_f_one], simp, end /-- Auxiliary construction for `lift`. -/ def lift_f_succ {Y Z : C} (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X n) (g' : P.complex.X (n+1) ⟶ Q.complex.X (n+1)) (w : g' ≫ Q.complex.d (n+1) n = P.complex.d (n+1) n ≫ g) : Σ' g'' : P.complex.X (n+2) ⟶ Q.complex.X (n+2), g'' ≫ Q.complex.d (n+2) (n+1) = P.complex.d (n+2) (n+1) ≫ g' := ⟨exact.lift (P.complex.d (n+2) (n+1) ≫ g') ((Q.complex.d (n+2) (n+1))) (Q.complex.d (n+1) n) (by simp [w]), (by simp)⟩ /-- A morphism in `C` lifts to a chain map between projective resolutions. -/ def lift {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex ⟶ Q.complex := begin fapply chain_complex.mk_hom, apply lift_f_zero f, apply lift_f_one f, apply lift_f_one_zero_comm f, rintro n ⟨g, g', w⟩, exact lift_f_succ P Q n g g' w, end /-- The resolution maps interwine the lift of a morphism and that morphism. -/ @[simp, reassoc] lemma lift_commutes {Y Z : C} (f : Y ⟶ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift f P Q ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f := begin ext n, rcases n with (_|_|n), { dsimp [lift, lift_f_zero], simp, }, { dsimp [lift, lift_f_one], simp, }, { dsimp, simp, }, end -- Now that we've checked this property of the lift, -- we can seal away the actual definition. attribute [irreducible] lift end ProjectiveResolution end namespace ProjectiveResolution variables [has_zero_object C] [preadditive C] [has_equalizers C] [has_images C] /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_zero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : P.complex.X 0 ⟶ Q.complex.X 1 := exact.lift (f.f 0) (Q.complex.d 1 0) (Q.π.f 0) (congr_fun (congr_arg homological_complex.hom.f comm) 0) /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_one {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : P.complex.X 1 ⟶ Q.complex.X 2 := exact.lift (f.f 1 - P.complex.d 1 0 ≫ lift_homotopy_zero_zero f comm) (Q.complex.d 2 1) (Q.complex.d 1 0) (by simp [lift_homotopy_zero_zero]) /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_succ {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (n : ℕ) (g : P.complex.X n ⟶ Q.complex.X (n + 1)) (g' : P.complex.X (n + 1) ⟶ Q.complex.X (n + 2)) (w : f.f (n + 1) = P.complex.d (n + 1) n ≫ g + g' ≫ Q.complex.d (n + 2) (n + 1)) : P.complex.X (n + 2) ⟶ Q.complex.X (n + 3) := exact.lift (f.f (n+2) - P.complex.d (n+2) (n+1) ≫ g') (Q.complex.d (n+3) (n+2)) (Q.complex.d (n+2) (n+1)) (by simp [w]) /-- Any lift of the zero morphism is homotopic to zero. -/ def lift_homotopy_zero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟶ Q.complex) (comm : f ≫ Q.π = 0) : homotopy f 0 := begin fapply homotopy.mk_inductive, { exact lift_homotopy_zero_zero f comm, }, { simp [lift_homotopy_zero_zero], }, { exact lift_homotopy_zero_one f comm, }, { simp [lift_homotopy_zero_one], }, { rintro n ⟨g, g', w⟩, fsplit, { exact lift_homotopy_zero_succ f n g g' w, }, { simp [lift_homotopy_zero_succ, w], }, } end /-- Two lifts of the same morphism are homotopic. -/ def lift_homotopy {Y Z : C} (f : Y ⟶ Z) {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (g h : P.complex ⟶ Q.complex) (g_comm : g ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) (h_comm : h ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) : homotopy g h := begin apply homotopy.equiv_sub_zero.inv_fun, apply lift_homotopy_zero, simp [g_comm, h_comm], end /-- The lift of the identity morphism is homotopic to the identity chain map. -/ def lift_id_homotopy (X : C) (P : ProjectiveResolution X) : homotopy (lift (𝟙 X) P P) (𝟙 P.complex) := by { apply lift_homotopy (𝟙 X); simp, } /-- The lift of a composition is homotopic to the composition of the lifts. -/ def lift_comp_homotopy {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) (R : ProjectiveResolution Z) : homotopy (lift (f ≫ g) P R) (lift f P Q ≫ lift g Q R) := by { apply lift_homotopy (f ≫ g); simp, } -- We don't care about the actual definitions of these homotopies. attribute [irreducible] lift_homotopy_zero lift_homotopy lift_id_homotopy lift_comp_homotopy /-- Any two projective resolutions are homotopy equivalent. -/ def homotopy_equiv {X : C} (P Q : ProjectiveResolution X) : homotopy_equiv P.complex Q.complex := { hom := lift (𝟙 X) P Q, inv := lift (𝟙 X) Q P, homotopy_hom_inv_id := begin refine (lift_comp_homotopy (𝟙 X) (𝟙 X) P Q P).symm.trans _, simp [category.id_comp], apply lift_id_homotopy, end, homotopy_inv_hom_id := begin refine (lift_comp_homotopy (𝟙 X) (𝟙 X) Q P Q).symm.trans _, simp [category.id_comp], apply lift_id_homotopy, end, } @[simp, reassoc] lemma homotopy_equiv_hom_π {X : C} (P Q : ProjectiveResolution X) : (homotopy_equiv P Q).hom ≫ Q.π = P.π := by simp [homotopy_equiv] @[simp, reassoc] lemma homotopy_equiv_inv_π {X : C} (P Q : ProjectiveResolution X) : (homotopy_equiv P Q).inv ≫ P.π = Q.π := by simp [homotopy_equiv] end ProjectiveResolution section variables [has_zero_morphisms C] [has_zero_object C] [has_equalizers C] [has_images C] /-- An arbitrarily chosen projective resolution of an object. -/ abbreviation projective_resolution (Z : C) [has_projective_resolution Z] : chain_complex C ℕ := (has_projective_resolution.out Z).some.complex /-- The chain map from the arbitrarily chosen projective resolution `projective_resolution Z` back to the chain complex consisting of `Z` supported in degree `0`. -/ abbreviation projective_resolution.π (Z : C) [has_projective_resolution Z] : projective_resolution Z ⟶ (chain_complex.single₀ C).obj Z := (has_projective_resolution.out Z).some.π /-- The lift of a morphism to a chain map between the arbitrarily chosen projective resolutions. -/ abbreviation projective_resolution.lift {X Y : C} (f : X ⟶ Y) [has_projective_resolution X] [has_projective_resolution Y] : projective_resolution X ⟶ projective_resolution Y := ProjectiveResolution.lift f _ _ end variables (C) [preadditive C] [has_zero_object C] [has_equalizers C] [has_images C] [has_projective_resolutions C] /-- Taking projective resolutions is functorial, if considered with target the homotopy category (`ℕ`-indexed chain complexes and chain maps up to homotopy). -/ def projective_resolutions : C ⥤ homotopy_category C (complex_shape.down ℕ) := { obj := λ X, (homotopy_category.quotient _ _).obj (projective_resolution X), map := λ X Y f, (homotopy_category.quotient _ _).map (projective_resolution.lift f), map_id' := λ X, begin rw ←(homotopy_category.quotient _ _).map_id, apply homotopy_category.eq_of_homotopy, apply ProjectiveResolution.lift_id_homotopy, end, map_comp' := λ X Y Z f g, begin rw ←(homotopy_category.quotient _ _).map_comp, apply homotopy_category.eq_of_homotopy, apply ProjectiveResolution.lift_comp_homotopy, end, } end category_theory
5bd5324605cf8a313c73641bc49cfeb97fda4755
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/src/refinement/tableau_class.lean
1a01d9fdea8c3cf6b76423602c4e6cdd090cc7f0
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
1,239
lean
import simplex class is_tableau (ftableau : ℕ → ℕ → Type) : Type := (to_tableau {m n : ℕ} : ftableau m n → tableau m n) (pivot {m n : ℕ} : ftableau m n → fin m → fin n → ftableau m n) (pivot_col {m n : ℕ} (T : ftableau m n) (obj : fin m) : option (fin n)) (pivot_row {m n : ℕ} (T : ftableau m n) (obj : fin m) : fin n → option (fin m)) (to_tableau_pivot {m n : ℕ} (T : ftableau m n) (i : fin m) (j : fin n) : to_tableau (pivot T i j) = (to_tableau T).pivot i j) (to_tableau_pivot_col {m n : ℕ} (T : ftableau m n) : pivot_col T = (to_tableau T).pivot_col) (to_tableau_pivot_row {m n : ℕ} (T : ftableau m n) : pivot_row T = (to_tableau T).pivot_row) namespace is_tableau section parameters {m n : ℕ} {ftableau : ℕ → ℕ → Type} variable [is_tableau ftableau] def to_matrix (T : ftableau m n) : matrix (fin m) (fin n) ℚ := (to_tableau T).to_matrix def const (T : ftableau m n) : matrix (fin m) (fin 1) ℚ := (to_tableau T).const def to_partition (T : ftableau m n) : partition m n := (to_tableau T).to_partition def restricted (T : ftableau m n) : finset (fin (m + n)) := (to_tableau T).restricted def dead (T : ftableau m n) : finset (fin n) := (to_tableau T).dead end end is_tableau
ab4506db54fda87564ccae516d8f63fe162d59a7
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/algebra/ordered.lean
236c2fcc3370b9ef8615988956d5689ec72bcc6f
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
44,686
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 -- TODO: use "open_locale classical" open_locale topological_space 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 (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : {b | f b ≤ g b} ∈ b) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (𝓝 (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 (𝓝 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 (𝓝 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 lemma is_open_Ioi {a : α} : is_open (Ioi a) := is_open_lt continuous_const continuous_id end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [t : ordered_topology α] {f g : β → α} include t section variables [topological_space β] (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 (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (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 (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (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} ∈ 𝓝 b := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : {b | a ≤ b} ∈ 𝓝 b := (𝓝 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} ∈ 𝓝 a := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : {a | a ≤ b} ∈ 𝓝 a := (𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_orderable {a : α} : 𝓝 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 (𝓝 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 (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : {b | g b ≤ f b} ∈ b) (hfh : {b | f b ≤ h b} ∈ b) : tendsto f b (𝓝 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) : 𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal {x | l < x ∧ x < u }) := let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in calc 𝓝 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 (𝓝 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 α] : 𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), principal {x | l < x}) := by rw [@nhds_eq_orderable α _ _]; simp [(>)] lemma nhds_bot_orderable [topological_space α] [order_bot α] [orderable_topology α] : 𝓝 (⊥:α) = (⨅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 ∈ 𝓝 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 ∈ 𝓝 a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have 𝓝 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 a₁ a₂ 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 ∈ 𝓝 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) ∧ 𝓝 a ⊓ principal t = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := h₂ h in match dense_or_discrete l a 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 $ (𝓝 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 $ (𝓝 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) ∧ 𝓝 a ⊓ principal t = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := h₁ h in match dense_or_discrete a u 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 $ (𝓝 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 $ (𝓝 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 α] [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 ≠ ∅) : 𝓝 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 ≠ ∅ → 𝓝 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 ⊓ 𝓝 a ≠ ⊥) : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ 𝓝 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 ⊓ 𝓝 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 (𝓝 a ⊓ principal s) (𝓝 b)) : is_lub (f '' s) b := have hnbot : (𝓝 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'} ∈ 𝓝 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} ∈ 𝓝 a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ 𝓝 a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ 𝓝 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 (𝓝 a ⊓ principal s) (𝓝 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 (𝓝 a ⊓ principal s) (𝓝 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 (𝓝 a ⊓ principal s) (𝓝 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 : α) : (𝓝 a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, show {x : α | x ≤ a} ∈ 𝓝 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 (𝓝 a)) : f.is_bounded_under (≤) u := is_bounded_of_le h (is_bounded_le_nhds a) lemma is_cobounded_ge_nhds (a : α) : (𝓝 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 (𝓝 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 : α) : (𝓝 a).is_bounded (≥) := match forall_le_or_exists_lt_inf a with | or.inl h := ⟨a, show {x : α | a ≤ x} ∈ 𝓝 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 (𝓝 a)) : f.is_bounded_under (≥) u := is_bounded_of_le h (is_bounded_ge_nhds a) lemma is_cobounded_le_nhds (a : α) : (𝓝 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 (𝓝 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 α] 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 α) _ variables [topological_space α] [orderable_topology α] /-- 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 ≤ 𝓝 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 (𝓝 a) = a := cInf_intro (ne_empty_iff_exists_mem.2 $ is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 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 ≤ 𝓝 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 ... ≤ (𝓝 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 = (𝓝 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 ≤ 𝓝 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 (𝓝 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 (𝓝 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 (𝓝 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:α, 𝓝 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 (𝓝 (⨆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 (𝓝 (⨅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 (𝓝 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 (𝓝 a) → infi f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_infi_nat f hf)
283120d67d681427f7263f8c8e713809af33266c
a338c3e75cecad4fb8d091bfe505f7399febfd2b
/src/group_theory/perm/basic.lean
8caa9c07b663805d5ffdcb225a96d50d79633dc0
[ "Apache-2.0" ]
permissive
bacaimano/mathlib
88eb7911a9054874fba2a2b74ccd0627c90188af
f2edc5a3529d95699b43514d6feb7eb11608723f
refs/heads/master
1,686,410,075,833
1,625,497,070,000
1,625,497,070,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,055
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import algebra.group.pi import algebra.group_power /-! # The group of permutations (self-equivalences) of a type `α` This file defines the `group` structure on `equiv.perm α`. -/ universes u v namespace equiv variables {α : Type u} {β : Type v} namespace perm instance perm_group : group (perm α) := { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv := equiv.symm, mul_assoc := λ f g h, (trans_assoc _ _ _).symm, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := trans_symm } theorem mul_apply (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ theorem one_apply (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self (f : perm α) (x) : f⁻¹ (f x) = x := f.symm_apply_apply x @[simp] lemma apply_inv_self (f : perm α) (x) : f (f⁻¹ x) = x := f.apply_symm_apply x lemma one_def : (1 : perm α) = equiv.refl α := rfl lemma mul_def (f g : perm α) : f * g = g.trans f := rfl lemma inv_def (f : perm α) : f⁻¹ = f.symm := rfl @[simp] lemma coe_mul (f g : perm α) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : perm α) = id := rfl lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := f.eq_symm_apply lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := f.symm_apply_eq lemma gpow_apply_comm {α : Type*} (σ : equiv.perm α) (m n : ℤ) {x : α} : (σ ^ m) ((σ ^ n) x) = (σ ^ n) ((σ ^ m) x) := by rw [←equiv.perm.mul_apply, ←equiv.perm.mul_apply, gpow_mul_comm] /-! Lemmas about mixing `perm` with `equiv`. Because we have multiple ways to express `equiv.refl`, `equiv.symm`, and `equiv.trans`, we want simp lemmas for every combination. The assumption made here is that if you're using the group structure, you want to preserve it after simp. -/ @[simp] lemma trans_one {α : Sort*} {β : Type*} (e : α ≃ β) : e.trans (1 : perm β) = e := equiv.trans_refl e @[simp] lemma mul_refl (e : perm α) : e * equiv.refl α = e := equiv.trans_refl e @[simp] lemma one_symm : (1 : perm α).symm = 1 := equiv.refl_symm @[simp] lemma refl_inv : (equiv.refl α : perm α)⁻¹ = 1 := equiv.refl_symm @[simp] lemma one_trans {α : Type*} {β : Sort*} (e : α ≃ β) : (1 : perm α).trans e = e := equiv.refl_trans e @[simp] lemma refl_mul (e : perm α) : equiv.refl α * e = e := equiv.refl_trans e @[simp] lemma inv_trans (e : perm α) : e⁻¹.trans e = 1 := equiv.symm_trans e @[simp] lemma mul_symm (e : perm α) : e * e.symm = 1 := equiv.symm_trans e @[simp] lemma trans_inv (e : perm α) : e.trans e⁻¹ = 1 := equiv.trans_symm e @[simp] lemma symm_mul (e : perm α) : e.symm * e = 1 := equiv.trans_symm e /-! Lemmas about `equiv.perm.sum_congr` re-expressed via the group structure. -/ @[simp] lemma sum_congr_mul {α β : Type*} (e : perm α) (f : perm β) (g : perm α) (h : perm β) : sum_congr e f * sum_congr g h = sum_congr (e * g) (f * h) := sum_congr_trans g h e f @[simp] lemma sum_congr_inv {α β : Type*} (e : perm α) (f : perm β) : (sum_congr e f)⁻¹ = sum_congr e⁻¹ f⁻¹ := sum_congr_symm e f @[simp] lemma sum_congr_one {α β : Type*} : sum_congr (1 : perm α) (1 : perm β) = 1 := sum_congr_refl /-- `equiv.perm.sum_congr` as a `monoid_hom`, with its two arguments bundled into a single `prod`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between `α` and `β`. -/ @[simps] def sum_congr_hom (α β : Type*) : perm α × perm β →* perm (α ⊕ β) := { to_fun := λ a, sum_congr a.1 a.2, map_one' := sum_congr_one, map_mul' := λ a b, (sum_congr_mul _ _ _ _).symm} lemma sum_congr_hom_injective {α β : Type*} : function.injective (sum_congr_hom α β) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i, { simpa using equiv.congr_fun h (sum.inl i), }, { simpa using equiv.congr_fun h (sum.inr i), }, end @[simp] lemma sum_congr_swap_one {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : α) : sum_congr (equiv.swap i j) (1 : perm β) = equiv.swap (sum.inl i) (sum.inl j) := sum_congr_swap_refl i j @[simp] lemma sum_congr_one_swap {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : β) : sum_congr (1 : perm α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := sum_congr_refl_swap i j /-! Lemmas about `equiv.perm.sigma_congr_right` re-expressed via the group structure. -/ @[simp] lemma sigma_congr_right_mul {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : sigma_congr_right F * sigma_congr_right G = sigma_congr_right (F * G) := sigma_congr_right_trans G F @[simp] lemma sigma_congr_right_inv {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) : (sigma_congr_right F)⁻¹ = sigma_congr_right (λ a, (F a)⁻¹) := sigma_congr_right_symm F @[simp] lemma sigma_congr_right_one {α : Type*} {β : α → Type*} : (sigma_congr_right (1 : Π a, equiv.perm $ β a)) = 1 := sigma_congr_right_refl /-- `equiv.perm.sigma_congr_right` as a `monoid_hom`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between fibers. -/ @[simps] def sigma_congr_right_hom {α : Type*} (β : α → Type*) : (Π a, perm (β a)) →* perm (Σ a, β a) := { to_fun := sigma_congr_right, map_one' := sigma_congr_right_one, map_mul' := λ a b, (sigma_congr_right_mul _ _).symm } lemma sigma_congr_right_hom_injective {α : Type*} {β : α → Type*} : function.injective (sigma_congr_right_hom β) := begin intros x y h, ext a b, simpa using equiv.congr_fun h ⟨a, b⟩, end /-- `equiv.perm.subtype_congr` as a `monoid_hom`. -/ @[simps] def subtype_congr_hom (p : α → Prop) [decidable_pred p] : (perm {a // p a}) × (perm {a // ¬ p a}) →* perm α := { to_fun := λ pair, perm.subtype_congr pair.fst pair.snd, map_one' := perm.subtype_congr.refl, map_mul' := λ _ _, (perm.subtype_congr.trans _ _ _ _).symm } lemma subtype_congr_hom_injective (p : α → Prop) [decidable_pred p] : function.injective (subtype_congr_hom p) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i; simpa using equiv.congr_fun h i end /-- If `e` is also a permutation, we can write `perm_congr` completely in terms of the group structure. -/ @[simp] lemma perm_congr_eq_mul (e p : perm α) : e.perm_congr p = e * p * e⁻¹ := rfl section extend_domain /-! Lemmas about `equiv.perm.extend_domain` re-expressed via the group structure. -/ variables (e : perm α) {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) @[simp] lemma extend_domain_one : extend_domain 1 f = 1 := extend_domain_refl f @[simp] lemma extend_domain_inv : (e.extend_domain f)⁻¹ = e⁻¹.extend_domain f := rfl @[simp] lemma extend_domain_mul (e e' : perm α) : (e.extend_domain f) * (e'.extend_domain f) = (e * e').extend_domain f := extend_domain_trans _ _ _ /-- `extend_domain` as a group homomorphism -/ @[simps] def extend_domain_hom : perm α →* perm β := { to_fun := λ e, extend_domain e f, map_one' := extend_domain_one f, map_mul' := λ e e', (extend_domain_mul f e e').symm } lemma extend_domain_hom_injective : function.injective (extend_domain_hom f) := ((extend_domain_hom f).injective_iff).mpr (λ e he, ext (λ x, f.injective (subtype.ext ((extend_domain_apply_image e f x).symm.trans (ext_iff.mp he (f x)))))) end extend_domain /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_apply (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) (x : {x // p x}) : subtype_perm f h x = ⟨f x, (h _).1 x.2⟩ := rfl @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp only [h, h₂, coe_fn_mk, perm.mul_apply, dif_pos, subtype.coe_eta] }, { simp only [h, coe_fn_mk, perm.mul_apply, dif_neg, not_false_iff] } end } lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp only [hx, coe_fn_mk, dif_pos, monoid_hom.coe_mk, subtype.coe_mk]}, { haveI := classical.prop_decidable, simp only [hx, not_not.mp (mt (h₂ x) hx), coe_fn_mk, dif_neg, not_false_iff, monoid_hom.coe_mk] } end lemma of_subtype_apply_of_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : p x) : of_subtype f x = f ⟨x, hx⟩ := dif_pos hx @[simp] lemma of_subtype_apply_coe {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : subtype p) : of_subtype f x = f x := subtype.cases_on x $ λ _, of_subtype_apply_of_mem f lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by simpa only [of_subtype, h, coe_fn_mk, dif_pos, true_iff, monoid_hom.coe_mk] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by { dsimp [subtype_perm, of_subtype], simp only [show p x, from hx, dif_pos, subtype.coe_eta] } instance perm_unique {n : Type*} [unique n] : unique (equiv.perm n) := { default := 1, uniq := λ σ, equiv.ext (λ i, subsingleton.elim _ _) } @[simp] lemma default_perm {n : Type*} : default (equiv.perm n) = 1 := rfl variables (e : perm α) (ι : α ↪ β) open_locale classical /-- Noncomputable version of `equiv.perm.via_fintype_embedding` that does not assume `fintype` -/ noncomputable def via_embedding : perm β := extend_domain e (of_injective ι.1 ι.2) lemma via_embedding_apply (x : α) : e.via_embedding ι (ι x) = ι (e x) := extend_domain_apply_image e (of_injective ι.1 ι.2) x lemma via_embedding_apply_of_not_mem (x : β) (hx : x ∉ _root_.set.range ι) : e.via_embedding ι x = x := extend_domain_apply_not_subtype e (of_injective ι.1 ι.2) hx /-- `via_embedding` as a group homomorphism -/ noncomputable def via_embedding_hom : perm α →* perm β:= extend_domain_hom (of_injective ι.1 ι.2) lemma via_embedding_hom_apply : via_embedding_hom ι e = via_embedding e ι := rfl lemma via_embedding_hom_injective : function.injective (via_embedding_hom ι) := extend_domain_hom_injective (of_injective ι.1 ι.2) end perm section swap variables [decidable_eq α] @[simp] lemma swap_inv (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma swap_mul_self (i j : α) : swap i j * swap i j = 1 := swap_swap i j lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp only [perm.mul_apply, swap_apply_def], split_ifs; simp only [perm.apply_inv_self, *, perm.eq_inv_iff_eq, eq_self_iff_true, not_true] at * end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, perm.inv_apply_self, perm.inv_apply_self] lemma swap_apply_apply (f : perm α) (x y : α) : swap (f x) (f y) = f * swap x y * f⁻¹ := by rw [mul_swap_eq_swap_mul, mul_inv_cancel_right] /-- Left-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc, swap_mul_self, one_mul] /-- Right-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma mul_swap_mul_self (i j : α) (σ : perm α) : (σ * equiv.swap i j) * equiv.swap i j = σ := by rw [mul_assoc, swap_mul_self, mul_one] /-- A stronger version of `mul_right_injective` -/ @[simp] lemma swap_mul_involutive (i j : α) : function.involutive ((*) (equiv.swap i j)) := swap_mul_self_mul i j /-- A stronger version of `mul_left_injective` -/ @[simp] lemma mul_swap_involutive (i j : α) : function.involutive (* (equiv.swap i j)) := mul_swap_mul_self i j @[simp] lemma swap_eq_one_iff {i j : α} : swap i j = (1 : perm α) ↔ i = j := swap_eq_refl_iff lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma mul_swap_eq_iff {i j : α} {σ : perm α} : σ * swap i j = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_left_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, mul_one])⟩ lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by { simp only [swap_apply_def, perm.mul_apply], split_ifs; cc } end swap end equiv
d700a90e8f871dc1e4942e43c5c59f034cf49817
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/punit_auto.lean
d94e585168a9eeaa48d778dcdbe059afd785dc45
[]
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,670
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.punit import Mathlib.category_theory.limits.limits import Mathlib.PostPort universes v u_1 namespace Mathlib /-! # `discrete punit` has limits and colimits Mostly for the sake of constructing trivial examples, we show all (co)cones into `discrete punit` are (co)limit (co)cones, and `discrete punit` has all (co)limits. -/ namespace category_theory.limits /-- Any cone over a functor into `punit` is a limit cone. -/ def punit_cone_is_limit {J : Type v} [small_category J] {F : J ⥤ discrete PUnit} {c : cone F} : is_limit c := is_limit.mk sorry /-- Any cocone over a functor into `punit` is a colimit cocone. -/ def punit_cocone_is_colimit {J : Type v} [small_category J] {F : J ⥤ discrete PUnit} {c : cocone F} : is_colimit c := is_colimit.mk sorry protected instance category_theory.discrete.has_limits : has_limits (discrete PUnit) := has_limits.mk fun (J : Type u_1) (𝒥 : small_category J) => has_limits_of_shape.mk fun (F : J ⥤ discrete PUnit) => has_limit.mk' (Nonempty.intro (limit_cone.mk sorry (is_limit.mk sorry))) protected instance category_theory.discrete.has_colimits : has_colimits (discrete PUnit) := has_colimits.mk fun (J : Type u_1) (𝒥 : small_category J) => has_colimits_of_shape.mk fun (F : J ⥤ discrete PUnit) => has_colimit.mk' (Nonempty.intro (colimit_cocone.mk sorry (is_colimit.mk sorry))) end Mathlib
8cf7ccee0a05918e1d7b2cfeefb1ee5cce189b60
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world3/level3.lean
5c95ec818bb37b9417eeb16b53f82dd8852219ac
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
812
lean
import game.world3.level2 -- hide import mynat.mul -- hide namespace mynat -- hide /- # Multiplication World ## Level 3: `one_mul` These proofs from addition world might be useful here: * `one_eq_succ_zero : 1 = succ(0)` * `succ_eq_add_one a : succ(a) = a + 1` We just proved `mul_one`, now let's prove `one_mul`. Then we will have proved, in fancy terms, that 1 is a "left and right identity" for multiplication (just like we showed that 0 is a left and right identity for addition with `add_zero` and `zero_add`). -/ /- Lemma For any natural number $m$, we have $$ 1 \times m = m. $$ -/ lemma one_mul (m : mynat) : 1 * m = m := begin [less_leaky] induction m with d hd, { rw mul_zero, refl, }, { rw mul_succ, rw hd, rw succ_eq_add_one, refl, } end end mynat -- hide
b5c9d128cefc87ee7168e382625c237ad5a71b69
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/game/state_auto.lean
8a8be5f2a41e33d8d37c4bb474ed3369986ee462
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,858
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.game.short import Mathlib.PostPort universes u l namespace Mathlib /-! # Games described via "the state of the board". We provide a simple mechanism for constructing combinatorial (pre-)games, by describing "the state of the board", and providing an upper bound on the number of turns remaining. ## Implementation notes We're very careful to produce a computable definition, so small games can be evaluated using `dec_trivial`. To achieve this, I've had to rely solely on induction on natural numbers: relying on general well-foundedness seems to be poisonous to computation? See `set_theory/game/domineering` for an example using this construction. -/ namespace pgame /-- `pgame_state S` describes how to interpret `s : S` as a state of a combinatorial game. Use `pgame.of s` or `game.of s` to construct the game. `pgame_state.L : S → finset S` and `pgame_state.R : S → finset S` describe the states reachable by a move by Left or Right. `pgame_state.turn_bound : S → ℕ` gives an upper bound on the number of possible turns remaining from this state. -/ class state (S : Type u) where turn_bound : S → ℕ L : S → finset S R : S → finset S left_bound : ∀ {s t : S}, t ∈ L s → turn_bound t < turn_bound s right_bound : ∀ {s t : S}, t ∈ R s → turn_bound t < turn_bound s theorem turn_bound_ne_zero_of_left_move {S : Type u} [state S] {s : S} {t : S} (m : t ∈ state.L s) : state.turn_bound s ≠ 0 := sorry theorem turn_bound_ne_zero_of_right_move {S : Type u} [state S] {s : S} {t : S} (m : t ∈ state.R s) : state.turn_bound s ≠ 0 := sorry theorem turn_bound_of_left {S : Type u} [state S] {s : S} {t : S} (m : t ∈ state.L s) (n : ℕ) (h : state.turn_bound s ≤ n + 1) : state.turn_bound t ≤ n := nat.le_of_lt_succ (nat.lt_of_lt_of_le (state.left_bound m) h) theorem turn_bound_of_right {S : Type u} [state S] {s : S} {t : S} (m : t ∈ state.R s) (n : ℕ) (h : state.turn_bound s ≤ n + 1) : state.turn_bound t ≤ n := nat.le_of_lt_succ (nat.lt_of_lt_of_le (state.right_bound m) h) /-- Construct a `pgame` from a state and a (not necessarily optimal) bound on the number of turns remaining. -/ def of_aux {S : Type u} [state S] (n : ℕ) (s : S) (h : state.turn_bound s ≤ n) : pgame := sorry /-- Two different (valid) turn bounds give equivalent games. -/ def of_aux_relabelling {S : Type u} [state S] (s : S) (n : ℕ) (m : ℕ) (hn : state.turn_bound s ≤ n) (hm : state.turn_bound s ≤ m) : relabelling (of_aux n s hn) (of_aux m s hm) := sorry /-- Construct a combinatorial `pgame` from a state. -/ def of {S : Type u} [state S] (s : S) : pgame := of_aux (state.turn_bound s) s sorry /-- The equivalence between `left_moves` for a `pgame` constructed using `of_aux _ s _`, and `L s`. -/ def left_moves_of_aux {S : Type u} [state S] (n : ℕ) {s : S} (h : state.turn_bound s ≤ n) : left_moves (of_aux n s h) ≃ Subtype fun (t : S) => t ∈ state.L s := Nat.rec (fun (h : state.turn_bound s ≤ 0) => equiv.refl (left_moves (of_aux 0 s h))) (fun (n_n : ℕ) (n_ih : (h : state.turn_bound s ≤ n_n) → left_moves (of_aux n_n s h) ≃ Subtype fun (t : S) => t ∈ state.L s) (h : state.turn_bound s ≤ Nat.succ n_n) => equiv.refl (left_moves (of_aux (Nat.succ n_n) s h))) n h /-- The equivalence between `left_moves` for a `pgame` constructed using `of s`, and `L s`. -/ def left_moves_of {S : Type u} [state S] (s : S) : left_moves (of s) ≃ Subtype fun (t : S) => t ∈ state.L s := left_moves_of_aux (state.turn_bound s) (of._proof_1 s) /-- The equivalence between `right_moves` for a `pgame` constructed using `of_aux _ s _`, and `R s`. -/ def right_moves_of_aux {S : Type u} [state S] (n : ℕ) {s : S} (h : state.turn_bound s ≤ n) : right_moves (of_aux n s h) ≃ Subtype fun (t : S) => t ∈ state.R s := Nat.rec (fun (h : state.turn_bound s ≤ 0) => equiv.refl (right_moves (of_aux 0 s h))) (fun (n_n : ℕ) (n_ih : (h : state.turn_bound s ≤ n_n) → right_moves (of_aux n_n s h) ≃ Subtype fun (t : S) => t ∈ state.R s) (h : state.turn_bound s ≤ Nat.succ n_n) => equiv.refl (right_moves (of_aux (Nat.succ n_n) s h))) n h /-- The equivalence between `right_moves` for a `pgame` constructed using `of s`, and `R s`. -/ def right_moves_of {S : Type u} [state S] (s : S) : right_moves (of s) ≃ Subtype fun (t : S) => t ∈ state.R s := right_moves_of_aux (state.turn_bound s) (of._proof_1 s) /-- The relabelling showing `move_left` applied to a game constructed using `of_aux` has itself been constructed using `of_aux`. -/ def relabelling_move_left_aux {S : Type u} [state S] (n : ℕ) {s : S} (h : state.turn_bound s ≤ n) (t : left_moves (of_aux n s h)) : relabelling (move_left (of_aux n s h) t) (of_aux (n - 1) (↑(coe_fn (left_moves_of_aux n h) t)) (relabelling_move_left_aux._proof_1 n h t)) := Nat.rec (fun (h : state.turn_bound s ≤ 0) (t : left_moves (of_aux 0 s h)) => False._oldrec sorry) (fun (n_n : ℕ) (n_ih : (h : state.turn_bound s ≤ n_n) → (t : left_moves (of_aux n_n s h)) → relabelling (move_left (of_aux n_n s h) t) (of_aux (n_n - 1) ↑(coe_fn (left_moves_of_aux n_n h) t) sorry)) (h : state.turn_bound s ≤ Nat.succ n_n) (t : left_moves (of_aux (Nat.succ n_n) s h)) => relabelling.refl (move_left (of_aux (Nat.succ n_n) s h) t)) n h t /-- The relabelling showing `move_left` applied to a game constructed using `of` has itself been constructed using `of`. -/ def relabelling_move_left {S : Type u} [state S] (s : S) (t : left_moves (of s)) : relabelling (move_left (of s) t) (of ↑(equiv.to_fun (left_moves_of s) t)) := relabelling.trans (relabelling_move_left_aux (state.turn_bound s) (of._proof_1 s) t) (of_aux_relabelling (↑(coe_fn (left_moves_of_aux (state.turn_bound s) (of._proof_1 s)) t)) (state.turn_bound s - 1) (state.turn_bound ↑(equiv.to_fun (left_moves_of s) t)) sorry sorry) /-- The relabelling showing `move_right` applied to a game constructed using `of_aux` has itself been constructed using `of_aux`. -/ def relabelling_move_right_aux {S : Type u} [state S] (n : ℕ) {s : S} (h : state.turn_bound s ≤ n) (t : right_moves (of_aux n s h)) : relabelling (move_right (of_aux n s h) t) (of_aux (n - 1) (↑(coe_fn (right_moves_of_aux n h) t)) (relabelling_move_right_aux._proof_1 n h t)) := Nat.rec (fun (h : state.turn_bound s ≤ 0) (t : right_moves (of_aux 0 s h)) => False._oldrec sorry) (fun (n_n : ℕ) (n_ih : (h : state.turn_bound s ≤ n_n) → (t : right_moves (of_aux n_n s h)) → relabelling (move_right (of_aux n_n s h) t) (of_aux (n_n - 1) ↑(coe_fn (right_moves_of_aux n_n h) t) sorry)) (h : state.turn_bound s ≤ Nat.succ n_n) (t : right_moves (of_aux (Nat.succ n_n) s h)) => relabelling.refl (move_right (of_aux (Nat.succ n_n) s h) t)) n h t /-- The relabelling showing `move_right` applied to a game constructed using `of` has itself been constructed using `of`. -/ def relabelling_move_right {S : Type u} [state S] (s : S) (t : right_moves (of s)) : relabelling (move_right (of s) t) (of ↑(equiv.to_fun (right_moves_of s) t)) := relabelling.trans (relabelling_move_right_aux (state.turn_bound s) (of._proof_1 s) t) (of_aux_relabelling (↑(coe_fn (right_moves_of_aux (state.turn_bound s) (of._proof_1 s)) t)) (state.turn_bound s - 1) (state.turn_bound ↑(equiv.to_fun (right_moves_of s) t)) sorry sorry) protected instance fintype_left_moves_of_aux {S : Type u} [state S] (n : ℕ) (s : S) (h : state.turn_bound s ≤ n) : fintype (left_moves (of_aux n s h)) := fintype.of_equiv (Subtype fun (t : S) => t ∈ state.L s) (equiv.symm (left_moves_of_aux n h)) protected instance fintype_right_moves_of_aux {S : Type u} [state S] (n : ℕ) (s : S) (h : state.turn_bound s ≤ n) : fintype (right_moves (of_aux n s h)) := fintype.of_equiv (Subtype fun (t : S) => t ∈ state.R s) (equiv.symm (right_moves_of_aux n h)) protected instance short_of_aux {S : Type u} [state S] (n : ℕ) {s : S} (h : state.turn_bound s ≤ n) : short (of_aux n s h) := sorry protected instance short_of {S : Type u} [state S] (s : S) : short (of s) := id (pgame.short_of_aux (state.turn_bound s) (of._proof_1 s)) end pgame namespace game /-- Construct a combinatorial `game` from a state. -/ def of {S : Type u} [pgame.state S] (s : S) : game := quotient.mk (pgame.of s) end Mathlib
46c001d8cec49d2c9e6456f9e128c8f42db4872c
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/basic.lean
5157eeaa4310cde0dee6d1485586ac0999305406
[ "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
63,246
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import algebra.support /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable theory open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] 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 /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] 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 topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ 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_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * 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 -/ class is_closed (s : set α) : Prop := (is_open_compl : is_open sᶜ) @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := ⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set α) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by { rw [← is_open_compl_iff] at *, 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 simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) : is_closed (⋂ i ∈ s, f i) := is_closed_Inter $ λ i, is_closed_Inter $ h i @[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.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ := is_closed_compl_iff.2 hs lemma is_open.sdiff {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_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ } lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) := is_closed.inter h₁ (is_closed_compl_iff.mpr h₂) lemma is_closed_bUnion {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_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {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_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- 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 is_open.interior_eq {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, is_open.interior_eq⟩ 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₁⟩ @[mono] 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 α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[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) @[simp] lemma finset.interior_Inter {ι : Type*} (s : finset ι) (f : ι → set α) : interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma interior_Inter_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) : interior (⋂ i, f i) = ⋂ i, interior (f i) := by { convert finset.univ.interior_Inter f; simp, } 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.sdiff 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] /-! ### Closure of a set -/ /-- 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 not_mem_of_not_mem_closure {s : set α} {P : α} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ @[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma diff_subset_closure_iff {s t : set α} : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[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) ((monotone_closure α).le_map_sup s t) @[simp] lemma finset.closure_Union {ι : Type*} (s : finset ι) (f : ι → set α) : closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma closure_Union_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) : closure (⋃ i, f i) = ⋃ i, closure (f i) := by { convert finset.univ.closure_Union f; simp, } 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 rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], 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).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h lemma interior_eq_empty_iff_dense_compl {s : set α} : interior s = ∅ ↔ dense sᶜ := by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff] lemma dense.interior_compl {s : set α} (h : dense s) : interior sᶜ = ∅ := interior_eq_empty_iff_dense_compl.2 $ by rwa compl_compl /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.exists_mem_open {s : set α} (hs : dense s) {U : set α} (ho : is_open U) (hne : U.nonempty) : ∃ x ∈ s, x ∈ U := let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne in ⟨x, hx.2, hx.1⟩ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-- Complement to a singleton is dense if and only if the singleton is not an open set. -/ lemma dense_compl_singleton_iff_not_open {x : α} : dense ({x}ᶜ : set α) ↔ ¬is_open ({x} : set α) := begin fsplit, { intros hd ho, exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) }, { refine λ ho, dense_iff_inter_open.2 (λ U hU hne, inter_compl_nonempty_iff.2 $ λ hUx, _), obtain rfl : U = {x}, from eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩, exact ho hU } end /-! ### Frontier of a set -/ /-- 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] lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _ /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier] @[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm lemma is_open.inter_frontier_eq_empty_of_disjoint {s t : set α} (ht : is_open t) (hd : disjoint s t) : t ∩ frontier s = ∅ := begin rw [inter_comm, ← subset_compl_iff_disjoint], exact subset.trans frontier_subset_closure (closure_minimal (λ _, disjoint_left.1 hd) (is_closed_compl_iff.2 ht)) end lemma frontier_eq_inter_compl_interior {s : set α} : frontier s = (interior s)ᶜ ∩ (interior (sᶜ))ᶜ := by { rw [←frontier_compl, ←closure_compl], refl } lemma compl_frontier_eq_union_interior {s : set α} : (frontier s)ᶜ = interior s ∪ interior sᶜ := begin rw frontier_eq_inter_compl_interior, simp only [compl_inter, compl_compl], end /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := begin rw nhds_def, exact has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_mem_nhds h lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_closed.compl_mem_nhds {a : α} {s : set α} (hs : is_closed s) (ha : a ∉ s) : sᶜ ∈ 𝓝 a := hs.is_open_compl.mem_nhds (mem_compl ha) lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := is_open.mem_nhds hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_mem_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨is_open.mem_nhds s_op a_in, s_op⟩ }, end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := begin have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx), choose! Z hZ hZ' using this, refine ⟨⋃ x ∈ s, Z x, _, _, bUnion_subset hZ'⟩, { intros x hx, simp only [mem_Union], exact ⟨x, hx, (hZ x hx).1⟩ }, { apply is_open_Union, intros x, by_cases hx : x ∈ s ; simp [hx], exact (hZ x hx).2 } end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem' $ assume _, ha lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure.2 $ mem_of_mem_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α} {pF : ιF → Prop} {sF : ιF → set α} {F : filter α} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set α} {a : α} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_of_superset h interior_subset, λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ ne_bot (𝓝[s] x) := mem_closure_iff_cluster_pt /-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole space. -/ lemma dense_compl_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : dense ({x}ᶜ : set α) := begin intro y, unfreezingI { rcases eq_or_ne y x with rfl|hne }, { rwa mem_closure_iff_nhds_within_ne_bot }, { exact subset_closure hne } end /-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole space. -/ @[simp] lemma closure_compl_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : closure {x}ᶜ = (univ : set α) := (dense_compl_singleton x).closure_eq /-- If `x` is not an isolated point of a topological space, then the interior of `{x}ᶜ` is empty. -/ @[simp] lemma interior_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : interior {x} = (∅ : set α) := interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x) lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis' {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := begin rintro a ⟨hs, ht⟩, have : s ∈ 𝓝 a := is_open.mem_nhds h hs, rw mem_closure_iff_nhds_ne_bot at ht ⊢, rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)], end lemma closure_inter_open' {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm] using closure_inter_open h lemma dense.open_subset_closure_inter {s t : set α} (hs : dense s) (ht : is_open t) : t ⊆ closure (t ∩ s) := calc t = t ∩ closure s : by rw [hs.closure_eq, inter_univ] ... ⊆ closure (t ∩ s) : closure_inter_open ht lemma mem_closure_of_mem_closure_union {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ := begin rw mem_closure_iff_nhds_ne_bot at *, rwa ← calc 𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal ... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : inf_sup_left ... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot.mpr h₁ ... = 𝓝 x ⊓ principal s₂ : bot_sup_eq end /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩ 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 filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- 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 ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite.point_finite {f : β → set α} (hf : locally_finite f) (x : α) : finite {b | x ∈ f b} := let ⟨t, hxt, ht⟩ := hf x in ht.subset $ λ b hb, ⟨x, hb, mem_of_mem_nhds hxt⟩ lemma locally_finite_of_fintype [fintype β] (f : β → set α) : locally_finite f := assume x, ⟨univ, univ_mem, finite.of_fintype _⟩ 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₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma locally_finite.comp_injective {ι} {f : β → set α} {g : ι → β} (hf : locally_finite f) (hg : function.injective g) : locally_finite (f ∘ g) := λ x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩ lemma locally_finite.closure {f : β → set α} (hf : locally_finite f) : locally_finite (λ i, closure (f i)) := begin intro x, rcases hf x with ⟨s, hsx, hsf⟩, refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ λ i hi, _⟩, exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono (inter_subset_inter_right _ interior_subset) end lemma locally_finite.is_closed_Union {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := begin simp only [← is_open_compl_iff, compl_Union, is_open_iff_mem_nhds, mem_Inter], intros a ha, replace ha : ∀ i, (f i)ᶜ ∈ 𝓝 a := λ i, (h₂ i).is_open_compl.mem_nhds (ha i), rcases h₁ a with ⟨t, h_nhds, h_fin⟩, have : t ∩ (⋂ i ∈ {i | (f i ∩ t).nonempty}, (f i)ᶜ) ∈ 𝓝 a, from inter_mem h_nhds ((bInter_mem h_fin).2 (λ i _, ha i)), filter_upwards [this], simp only [mem_inter_eq, mem_Inter], rintros b ⟨hbt, hn⟩ i hfb, exact hn i ⟨b, hfb, hbt⟩ hfb end lemma locally_finite.closure_Union {f : β → set α} (h : locally_finite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := subset.antisymm (closure_minimal (Union_subset_Union $ λ _, subset_closure) $ h.closure.is_closed_Union $ λ _, is_closed_closure) (Union_subset $ λ i, closure_mono $ subset_Union _ _) end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} : f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) := by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ /-- See also `interior_preimage_subset_preimage_interior`. -/ lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, is_open.mem_nhds hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := tendsto_const_nhds lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma filter.eventually_eq.continuous_at {x : α} {f : α → β} {y : β} (h : f =ᶠ[𝓝 x] (λ _, y)) : continuous_at f x := (continuous_at_congr h).2 tendsto_const_nhds lemma continuous_of_const {f : α → β} (h : ∀ x y, f x = f y) : continuous f := continuous_iff_continuous_at.mpr $ λ x, filter.eventually_eq.continuous_at $ eventually_of_forall (λ y, h y x) lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma mem_closure_image {f : α → β} {x : α} {s : set α} (hf : continuous_at f x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := begin rw [mem_closure_iff_nhds_ne_bot] at hx ⊢, rw ← bot_lt_iff_ne_bot, haveI : ne_bot _ := ⟨hx⟩, calc ⊥ < map f (𝓝 x ⊓ principal s) : bot_lt_iff_ne_bot.mpr ne_bot.ne' ... ≤ (map f $ 𝓝 x) ⊓ (map f $ principal s) : map_inf_le ... = (map f $ 𝓝 x) ⊓ (principal $ f '' s) : by rw map_principal ... ≤ 𝓝 (f x) ⊓ (principal $ f '' s) : inf_le_inf hf le_rfl end lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] lemma continuous.closure_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : closure (f ⁻¹' t) ⊆ f ⁻¹' (closure t) := begin rw ← (is_closed_closure.preimage hf).closure_eq, exact closure_mono (preimage_mono subset_closure), end lemma continuous.frontier_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : frontier (f ⁻¹' t) ⊆ f ⁻¹' (frontier t) := diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf) /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) : closure s ⊆ f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma dense.dense_range_coe {s : set α} (h : dense s) : dense_range (coe : s → α) := by simpa only [dense_range, subtype.range_coe_subtype] lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the preimage of `s` under `f` is dense in `s`. -/ lemma dense_range.subset_closure_image_preimage_of_is_open (hf : dense_range f) {s : set β} (hs : is_open s) : s ⊆ closure (f '' (f ⁻¹' s)) := by { rw image_preimage_eq_inter_range, exact hf.open_subset_closure_inter hs } /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ lemma dense_range.exists_mem_open (hf : dense_range f) {s : set β} (ho : is_open s) (hs : s.nonempty) : ∃ a, f a ∈ s := exists_range_iff.1 $ hf.exists_mem_open ho hs lemma dense_range.mem_nhds {f : κ → β} (h : dense_range f) {b : β} {U : set β} (U_in : U ∈ nhds b) : ∃ a, f a ∈ U := begin rcases (mem_closure_iff_nhds.mp ((dense_range_iff_closure_range.mp h).symm ▸ mem_univ b : b ∈ closure (range f)) U U_in) with ⟨_, h, a, rfl⟩, exact ⟨a, h⟩ end end dense_range end continuous
725ff11ff0f775d969db7f2defa3279bfbfd75ba
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/data/ordering/default.lean
e3f5fdf672fd9277eeb192c48c326ccc524bbf0b
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
186
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import .basic
d7835cad5336b73d61c7a9b3c95fe05e9cc2cecb
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category/traversable/derive.lean
d9e4bd014aabe904a903999736c2fdf1555bc6e5
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
17,105
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Automation to construct `traversable` instances -/ import category.traversable.basic category.traversable.lemmas category.basic data.list.basic import tactic.basic tactic.cache 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, _⟩ ← mk_local_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 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 ff (rules ``(functor.map_comp_map)) [] goal), return () meta def simp_functor (rs : list simp_arg_type := []) : tactic unit := simp 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 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 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
72670a3c8c9519e5f20c2ffa2cff067c67544f77
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/undergraduate/MAS114/Semester 1/Q09.lean
eec9a80d8cf760e082f2fb2e6fae2fd3503bd79f
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
642
lean
import data.int.basic import tactic.ring namespace MAS114 namespace exercises_1 namespace Q09 def even (n : ℤ) := ∃ k : ℤ, n = 2 * k def odd (n : ℤ) := ∃ k : ℤ, n = 2 * k + 1 lemma L1 (n : ℤ) : even n → even (n ^ 2) := begin rintro ⟨k,e⟩, use n * k, rw[e,pow_two],ring, end lemma L2 (n m : ℤ) : even n → even m → even (n + m) := begin rintros ⟨k,ek⟩ ⟨l,el⟩, use k + l, rw[ek,el], ring, end lemma L3 (n m : ℤ) : odd n → odd m → odd (n * m) := begin rintros ⟨k,ek⟩ ⟨l,el⟩, use k + l + 2 * k * l, rw[ek,el], ring, end /- Do the converses -/ end Q09 end exercises_1 end MAS114
fee07a65e1c9b9b108fdcbe4011e789430043243
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/precategory.hlean
71652857c20b674f4b0eca769e27f7b659c829a9
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
12,187
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import types.trunc types.pi arity open eq is_trunc pi equiv equiv.ops namespace category /- Just as in Coq-HoTT we add two redundant fields to precategories: assoc' and id_id. The first is to make (Cᵒᵖ)ᵒᵖ = C definitionally when C is a constructor. The second is to ensure that the functor from the terminal category 1 ⇒ Cᵒᵖ is opposite to the functor 1 ⇒ C. -/ structure precategory [class] (ob : Type) : Type := mk' :: (hom : ob → ob → Type) (comp : Π⦃a b c : ob⦄, hom b c → hom a b → hom a c) (ID : Π (a : ob), hom a a) (assoc : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b), comp h (comp g f) = comp (comp h g) f) (assoc' : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b), comp (comp h g) f = comp h (comp g f)) (id_left : Π ⦃a b : ob⦄ (f : hom a b), comp !ID f = f) (id_right : Π ⦃a b : ob⦄ (f : hom a b), comp f !ID = f) (id_id : Π (a : ob), comp !ID !ID = ID a) (is_hset_hom : Π(a b : ob), is_hset (hom a b)) -- attribute precategory [multiple-instances] --this is not used anywhere attribute precategory.is_hset_hom [instance] infixr ∘ := precategory.comp -- input ⟶ using \--> (this is a different arrow than \-> (→)) infixl [parsing_only] ` ⟶ `:60 := precategory.hom namespace hom infixl ` ⟶ `:60 := precategory.hom -- if you open this namespace, hom a b is printed as a ⟶ b end hom abbreviation hom [unfold 2] := @precategory.hom abbreviation comp [unfold 2] := @precategory.comp abbreviation ID [unfold 2] := @precategory.ID abbreviation assoc [unfold 2] := @precategory.assoc abbreviation assoc' [unfold 2] := @precategory.assoc' abbreviation id_left [unfold 2] := @precategory.id_left abbreviation id_right [unfold 2] := @precategory.id_right abbreviation id_id [unfold 2] := @precategory.id_id abbreviation is_hset_hom [unfold 2] := @precategory.is_hset_hom definition is_hprop_hom_eq {ob : Type} [C : precategory ob] {x y : ob} (f g : x ⟶ y) : is_hprop (f = g) := _ -- the constructor you want to use in practice protected definition precategory.mk [constructor] {ob : Type} (hom : ob → ob → Type) [hset : Π (a b : ob), is_hset (hom a b)] (comp : Π ⦃a b c : ob⦄, hom b c → hom a b → hom a c) (ID : Π (a : ob), hom a a) (ass : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b), comp h (comp g f) = comp (comp h g) f) (idl : Π ⦃a b : ob⦄ (f : hom a b), comp (ID b) f = f) (idr : Π ⦃a b : ob⦄ (f : hom a b), comp f (ID a) = f) : precategory ob := precategory.mk' hom comp ID ass (λa b c d h g f, !ass⁻¹) idl idr (λa, !idl) hset section basic_lemmas variables {ob : Type} [C : precategory ob] variables {a b c d : ob} {h : c ⟶ d} {g : hom b c} {f f' : hom a b} {i : a ⟶ a} include C definition id [reducible] [unfold 2] := ID a definition id_leftright (f : hom a b) : id ∘ f ∘ id = f := !id_left ⬝ !id_right definition comp_id_eq_id_comp (f : hom a b) : f ∘ id = id ∘ f := !id_right ⬝ !id_left⁻¹ definition id_comp_eq_comp_id (f : hom a b) : id ∘ f = f ∘ id := !id_left ⬝ !id_right⁻¹ definition left_id_unique (H : Π{b} {f : hom b a}, i ∘ f = f) : i = id := calc i = i ∘ id : by rewrite id_right ... = id : by rewrite H definition right_id_unique (H : Π{b} {f : hom a b}, f ∘ i = f) : i = id := calc i = id ∘ i : by rewrite id_left ... = id : by rewrite H definition homset [reducible] [constructor] (x y : ob) : hset := hset.mk (hom x y) _ end basic_lemmas section squares parameters {ob : Type} [C : precategory ob] local infixl ` ⟶ `:25 := @precategory.hom ob C local infixr ∘ := @precategory.comp ob C _ _ _ definition compose_squares {xa xb xc ya yb yc : ob} {xg : xb ⟶ xc} {xf : xa ⟶ xb} {yg : yb ⟶ yc} {yf : ya ⟶ yb} {wa : xa ⟶ ya} {wb : xb ⟶ yb} {wc : xc ⟶ yc} (xyab : wb ∘ xf = yf ∘ wa) (xybc : wc ∘ xg = yg ∘ wb) : wc ∘ (xg ∘ xf) = (yg ∘ yf) ∘ wa := calc wc ∘ (xg ∘ xf) = (wc ∘ xg) ∘ xf : by rewrite assoc ... = (yg ∘ wb) ∘ xf : by rewrite xybc ... = yg ∘ (wb ∘ xf) : by rewrite assoc ... = yg ∘ (yf ∘ wa) : by rewrite xyab ... = (yg ∘ yf) ∘ wa : by rewrite assoc definition compose_squares_2x2 {xa xb xc ya yb yc za zb zc : ob} {xg : xb ⟶ xc} {xf : xa ⟶ xb} {yg : yb ⟶ yc} {yf : ya ⟶ yb} {zg : zb ⟶ zc} {zf : za ⟶ zb} {va : ya ⟶ za} {vb : yb ⟶ zb} {vc : yc ⟶ zc} {wa : xa ⟶ ya} {wb : xb ⟶ yb} {wc : xc ⟶ yc} (xyab : wb ∘ xf = yf ∘ wa) (xybc : wc ∘ xg = yg ∘ wb) (yzab : vb ∘ yf = zf ∘ va) (yzbc : vc ∘ yg = zg ∘ vb) : (vc ∘ wc) ∘ (xg ∘ xf) = (zg ∘ zf) ∘ (va ∘ wa) := calc (vc ∘ wc) ∘ (xg ∘ xf) = vc ∘ (wc ∘ (xg ∘ xf)) : by rewrite (assoc vc wc _) ... = vc ∘ ((yg ∘ yf) ∘ wa) : by rewrite (compose_squares xyab xybc) ... = (vc ∘ (yg ∘ yf)) ∘ wa : by rewrite assoc ... = ((zg ∘ zf) ∘ va) ∘ wa : by rewrite (compose_squares yzab yzbc) ... = (zg ∘ zf) ∘ (va ∘ wa) : by rewrite assoc definition square_precompose {xa xb xc yb yc : ob} {xg : xb ⟶ xc} {yg : yb ⟶ yc} {wb : xb ⟶ yb} {wc : xc ⟶ yc} (H : wc ∘ xg = yg ∘ wb) (xf : xa ⟶ xb) : wc ∘ xg ∘ xf = yg ∘ wb ∘ xf := calc wc ∘ xg ∘ xf = (wc ∘ xg) ∘ xf : by rewrite assoc ... = (yg ∘ wb) ∘ xf : by rewrite H ... = yg ∘ wb ∘ xf : by rewrite assoc definition square_postcompose {xb xc yb yc yd : ob} {xg : xb ⟶ xc} {yg : yb ⟶ yc} {wb : xb ⟶ yb} {wc : xc ⟶ yc} (H : wc ∘ xg = yg ∘ wb) (yh : yc ⟶ yd) : (yh ∘ wc) ∘ xg = (yh ∘ yg) ∘ wb := calc (yh ∘ wc) ∘ xg = yh ∘ wc ∘ xg : by rewrite assoc ... = yh ∘ yg ∘ wb : by rewrite H ... = (yh ∘ yg) ∘ wb : by rewrite assoc definition square_prepostcompose {xa xb xc yb yc yd : ob} {xg : xb ⟶ xc} {yg : yb ⟶ yc} {wb : xb ⟶ yb} {wc : xc ⟶ yc} (H : wc ∘ xg = yg ∘ wb) (yh : yc ⟶ yd) (xf : xa ⟶ xb) : (yh ∘ wc) ∘ (xg ∘ xf) = (yh ∘ yg) ∘ (wb ∘ xf) := square_precompose (square_postcompose H yh) xf end squares structure Precategory : Type := (carrier : Type) (struct : precategory carrier) definition precategory.Mk [reducible] [constructor] {ob} (C) : Precategory := Precategory.mk ob C definition precategory.MK [reducible] [constructor] (a b c d e f g h) : Precategory := Precategory.mk a (@precategory.mk a b c d e f g h) abbreviation carrier [unfold 1] := @Precategory.carrier attribute Precategory.carrier [coercion] attribute Precategory.struct [instance] [priority 10000] [coercion] -- definition precategory.carrier [coercion] [reducible] := Precategory.carrier -- definition precategory.struct [instance] [coercion] [reducible] := Precategory.struct notation g ` ∘[`:60 C:0 `] `:0 f:60 := @comp (Precategory.carrier C) (Precategory.struct C) _ _ _ g f -- TODO: make this left associative definition Precategory.eta (C : Precategory) : Precategory.mk C C = C := Precategory.rec (λob c, idp) C /-Characterization of paths between precategories-/ -- introduction tule for paths between precategories definition precategory_eq {ob : Type} {C D : precategory ob} (p : Π{a b}, @hom ob C a b = @hom ob D a b) (q : Πa b c g f, cast p (@comp ob C a b c g f) = @comp ob D a b c (cast p g) (cast p f)) : C = D := begin induction C with hom1 comp1 ID1 a b il ir, induction D with hom2 comp2 ID2 a' b' il' ir', esimp at *, revert q, eapply homotopy2.rec_on @p, esimp, clear p, intro p q, induction p, esimp at *, assert H : comp1 = comp2, { apply eq_of_homotopy3, intros, apply eq_of_homotopy2, intros, apply q}, induction H, assert K : ID1 = ID2, { apply eq_of_homotopy, intro a, exact !ir'⁻¹ ⬝ !il}, induction K, apply ap0111111 (precategory.mk' hom1 comp1 ID1): apply is_hprop.elim end definition precategory_eq_of_equiv {ob : Type} {C D : precategory ob} (p : Π⦃a b⦄, @hom ob C a b ≃ @hom ob D a b) (q : Π{a b c} g f, p (@comp ob C a b c g f) = @comp ob D a b c (p g) (p f)) : C = D := begin fapply precategory_eq, { intro a b, exact ua !@p}, { intros, refine !cast_ua ⬝ !q ⬝ _, apply ap011 !@comp !cast_ua⁻¹ !cast_ua⁻¹}, end /- if we need to prove properties about precategory_eq, it might be easier with the following proof: begin induction C with hom1 comp1 ID1, induction D with hom2 comp2 ID2, esimp at *, assert H : Σ(s : hom1 = hom2), (λa b, equiv_of_eq (apd100 s a b)) = p, { fconstructor, { apply eq_of_homotopy2, intros, apply ua, apply p}, { apply eq_of_homotopy2, intros, rewrite [to_right_inv !eq_equiv_homotopy2, equiv_of_eq_ua]}}, induction H with H1 H2, induction H1, esimp at H2, assert K : (λa b, equiv.refl) = p, { refine _ ⬝ H2, apply eq_of_homotopy2, intros, exact !equiv_of_eq_refl⁻¹}, induction K, clear H2, esimp at *, assert H : comp1 = comp2, { apply eq_of_homotopy3, intros, apply eq_of_homotopy2, intros, apply q}, assert K : ID1 = ID2, { apply eq_of_homotopy, intros, apply r}, induction H, induction K, apply ap0111111 (precategory.mk' hom1 comp1 ID1): apply is_hprop.elim end -/ definition Precategory_eq {C D : Precategory} (p : carrier C = carrier D) (q : Π{a b : C}, a ⟶ b = cast p a ⟶ cast p b) (r : Π{a b c : C} (g : b ⟶ c) (f : a ⟶ b), cast q (g ∘ f) = cast q g ∘ cast q f) : C = D := begin induction C with X C, induction D with Y D, esimp at *, induction p, esimp at *, apply ap (Precategory.mk X), apply precategory_eq @q @r end definition Precategory_eq_of_equiv {C D : Precategory} (p : carrier C ≃ carrier D) (q : Π⦃a b : C⦄, a ⟶ b ≃ p a ⟶ p b) (r : Π{a b c : C} (g : b ⟶ c) (f : a ⟶ b), q (g ∘ f) = q g ∘ q f) : C = D := begin induction C with X C, induction D with Y D, esimp at *, revert q r, eapply equiv.rec_on_ua p, clear p, intro p, induction p, esimp, intros, apply ap (Precategory.mk X), apply precategory_eq_of_equiv @q @r end -- elimination rules for paths between precategories. -- The first elimination rule is "ap carrier" definition Precategory_eq_hom [unfold 3] {C D : Precategory} (p : C = D) (a b : C) : hom a b = hom (cast (ap carrier p) a) (cast (ap carrier p) b) := by induction p; reflexivity --(ap10 (ap10 (apd (λx, @hom (carrier x) (Precategory.struct x)) p⁻¹ᵖ) a) b)⁻¹ᵖ ⬝ _ -- beta/eta rules definition ap_Precategory_eq' {C D : Precategory} (p : carrier C = carrier D) (q : Π{a b : C}, a ⟶ b = cast p a ⟶ cast p b) (r : Π{a b c : C} (g : b ⟶ c) (f : a ⟶ b), cast q (g ∘ f) = cast q g ∘ cast q f) (s : Πa, cast q (ID a) = ID (cast p a)) : ap carrier (Precategory_eq p @q @r) = p := begin induction C with X C, induction D with Y D, esimp at *, induction p, rewrite [↑Precategory_eq, -ap_compose,↑function.compose,ap_constant] end /- theorem Precategory_eq'_eta {C D : Precategory} (p : C = D) : Precategory_eq (ap carrier p) (Precategory_eq_hom p) (by induction p; intros; reflexivity) = p := begin induction p, induction C with X C, unfold Precategory_eq, induction C, unfold precategory_eq, exact sorry end -/ /- theorem Precategory_eq2 {C D : Precategory} (p q : C = D) (r : ap carrier p = ap carrier q) (s : Precategory_eq_hom p =[r] Precategory_eq_hom q) : p = q := begin end -/ end category
a53ee710816ad09f7e0777a6d9024e412595dc64
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/function/floor.lean
a14bb132cedf776a21640be4567482d94c2eb59f
[ "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
2,850
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.constructions.borel_space /-! # Measurability of `⌊x⌋` etc In this file we prove that `int.floor`, `int.ceil`, `int.fract`, `nat.floor`, and `nat.ceil` are measurable under some assumptions on the (semi)ring. -/ open set section floor_ring variables {α R : Type*} [measurable_space α] [linear_ordered_ring R] [floor_ring R] [topological_space R] [order_topology R] [measurable_space R] lemma int.measurable_floor [opens_measurable_space R] : measurable (int.floor : R → ℤ) := measurable_to_encodable $ λ x, by simpa only [int.preimage_floor_singleton] using measurable_set_Ico @[measurability] lemma measurable.floor [opens_measurable_space R] {f : α → R} (hf : measurable f) : measurable (λ x, ⌊f x⌋) := int.measurable_floor.comp hf lemma int.measurable_ceil [opens_measurable_space R] : measurable (int.ceil : R → ℤ) := measurable_to_encodable $ λ x, by simpa only [int.preimage_ceil_singleton] using measurable_set_Ioc @[measurability] lemma measurable.ceil [opens_measurable_space R] {f : α → R} (hf : measurable f) : measurable (λ x, ⌈f x⌉) := int.measurable_ceil.comp hf lemma measurable_fract [borel_space R] : measurable (int.fract : R → R) := begin intros s hs, rw int.preimage_fract, exact measurable_set.Union (λ z, measurable_id.sub_const _ (hs.inter measurable_set_Ico)) end @[measurability] lemma measurable.fract [borel_space R] {f : α → R} (hf : measurable f) : measurable (λ x, int.fract (f x)) := measurable_fract.comp hf lemma measurable_set.image_fract [borel_space R] {s : set R} (hs : measurable_set s) : measurable_set (int.fract '' s) := begin simp only [int.image_fract, sub_eq_add_neg, image_add_right'], exact measurable_set.Union (λ m, (measurable_add_const _ hs).inter measurable_set_Ico) end end floor_ring section floor_semiring variables {α R : Type*} [measurable_space α] [linear_ordered_semiring R] [floor_semiring R] [topological_space R] [order_topology R] [measurable_space R] [opens_measurable_space R] {f : α → R} lemma nat.measurable_floor : measurable (nat.floor : R → ℕ) := measurable_to_encodable $ λ n, by cases eq_or_ne ⌊n⌋₊ 0; simp [*, nat.preimage_floor_of_ne_zero] @[measurability] lemma measurable.nat_floor (hf : measurable f) : measurable (λ x, ⌊f x⌋₊) := nat.measurable_floor.comp hf lemma nat.measurable_ceil : measurable (nat.ceil : R → ℕ) := measurable_to_encodable $ λ n, by cases eq_or_ne ⌈n⌉₊ 0; simp [*, nat.preimage_ceil_of_ne_zero] @[measurability] lemma measurable.nat_ceil (hf : measurable f) : measurable (λ x, ⌈f x⌉₊) := nat.measurable_ceil.comp hf end floor_semiring
9f25117ab2c4d81504efd4a11264981af66d12da
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/inter_union.lean
15d8a64d9739c19f76a3cda6265e500539aca924
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
6,592
lean
import category_theory.category import category_theory.colimits import category_theory.colimit_lemmas import category_theory.types import .homeomorphism import .subspace open set open category_theory local notation f ` ∘ `:80 g:80 := g ≫ f universe u namespace homotopy_theory.topological_spaces namespace Set local notation `Set` := Type u def mk_ob (α : Set) : Set := α def incl' {α : Set} (A B : set α) (h : A ⊆ B) : mk_ob A ⟶ mk_ob B := λ p, ⟨p.val, h p.property⟩ section inter_union variables {X : Set} {A₀ A₁ : set X} local notation `A₀₁` := A₀ ∩ A₁ local notation `A` := (A₀ ∪ A₁ : set X) local notation `i₀` := incl' A₀₁ A₀ (set.inter_subset_left A₀ A₁) local notation `i₁` := incl' A₀₁ A₁ (set.inter_subset_right A₀ A₁) local notation `j₀` := incl' A₀ A (set.subset_union_left A₀ A₁) local notation `j₁` := incl' A₁ A (set.subset_union_right A₀ A₁) section glue variables ⦃β : Set⦄ (h₀ : mk_ob A₀ ⟶ β) (h₁ : mk_ob A₁ ⟶ β) variable (e : h₀ ∘ i₀ = h₁ ∘ i₁) include e local attribute [instance] classical.prop_decidable noncomputable def glue : mk_ob A ⟶ β := λ a, if h : a.val ∈ A₀ then h₀ ⟨a.val, h⟩ else h₁ ⟨a.val, a.property.resolve_left h⟩ lemma glue_commutes₀ : glue h₀ h₁ e ∘ j₀ = h₀ := by funext a; have := a.property; simp [glue, incl', this] lemma glue_commutes₁ : glue h₀ h₁ e ∘ j₁ = h₁ := begin funext a, change (if h : _ then _ else _) = h₁ a, cases a with v p, split_ifs, { exact congr_fun e ⟨v, h, p⟩ }, { refl } end end glue lemma uniqueness ⦃β : Set⦄ (k k' : mk_ob A ⟶ β) (e₀ : k ∘ j₀ = k' ∘ j₀) (e₁ : k ∘ j₁ = k' ∘ j₁) : k = k' := begin funext a, rcases a with ⟨v, p₀|p₁⟩, { exact @@congr_fun _ _ _ e₀ ⟨v, p₀⟩ }, { exact @@congr_fun _ _ _ e₁ ⟨v, p₁⟩ } end variables (A₀ A₁) include A₀ A₁ noncomputable def Is_pushout_inter_union : Is_pushout i₀ i₁ j₀ j₁ := Is_pushout.mk' rfl glue glue_commutes₀ glue_commutes₁ uniqueness end inter_union end «Set» namespace Top local notation `Top` := Top.{u} section inter_union variables {X : Top} {A₀ A₁ : set X} (ha₀ : is_closed A₀) (ha₁ : is_closed A₁) -- Other assumptions are possible, e.g., A₀, A₁ both open. local notation `A₀₁` := A₀ ∩ A₁ local notation `A` := (A₀ ∪ A₁ : set X) local notation `i₀` := incl' A₀₁ A₀ (set.inter_subset_left A₀ A₁) local notation `i₁` := incl' A₀₁ A₁ (set.inter_subset_right A₀ A₁) local notation `j₀` := incl' A₀ A (set.subset_union_left A₀ A₁) local notation `j₁` := incl' A₁ A (set.subset_union_right A₀ A₁) local notation `i'₀` := Set.incl' A₀₁ A₀ (set.inter_subset_left A₀ A₁) local notation `i'₁` := Set.incl' A₀₁ A₁ (set.inter_subset_right A₀ A₁) local notation `j'₀` := Set.incl' A₀ A (set.subset_union_left A₀ A₁) local notation `j'₁` := Set.incl' A₁ A (set.subset_union_right A₀ A₁) local notation [parsing_only] a ` ~~ ` b := Bij_on _ a b instance Set.mk_ob.topological_space (α : Type*) [t : topological_space α] : topological_space (Set.mk_ob α) := t lemma continuous_iff {Z : Top} (k : A → Z) : continuous k ↔ continuous (k ∘ j'₀) ∧ continuous (k ∘ j'₁) := iff.intro (assume h, ⟨by continuity!, by continuity!⟩) (assume ⟨h₀, h₁⟩, let c : bool → set A := λ i, bool.rec_on i {a | a.val ∈ A₀} {a | a.val ∈ A₁} in have h_lf : locally_finite c := locally_finite_of_finite ⟨fintype.of_equiv _ (equiv.set.univ bool).symm⟩, have h_is_closed : ∀ i, is_closed (c i) := assume i, bool.rec_on i (continuous_iff_is_closed.mp continuous_subtype_val _ ha₀) (continuous_iff_is_closed.mp continuous_subtype_val _ ha₁), have h_cover : ∀ a, ∃ i, a ∈ c i := assume a, a.property.elim (λ h, ⟨ff, h⟩) (λ h, ⟨tt, h⟩), have f_cont : ∀ i, continuous (λ (x : subtype (c i)), k x.val) := assume i, bool.rec_on i (have continuous (function.comp (k ∘ j'₀) (λ (x : subtype (c ff)), ⟨x.val.val, x.property⟩)), by continuity, begin convert this, funext x, rcases x with ⟨⟨_, _⟩, _⟩, refl end) (have continuous (function.comp (k ∘ j'₁) (λ (x : subtype (c tt)), ⟨x.val.val, x.property⟩)), by continuity, begin convert this, funext x, rcases x with ⟨⟨_, _⟩, _⟩, refl end), continuous_subtype_is_closed_cover c h_lf h_is_closed h_cover f_cont) variables (A₀ A₁) include A₀ A₁ noncomputable def Is_pushout_inter_union : Is_pushout i₀ i₁ j₀ j₁ := Is_pushout.mk $ λ Z, calc univ ~~ {k : {k : A → Z // continuous k} | true} : Bij_on.of_equiv (Top.hom_equiv_subtype (Top.mk_ob A) Z) ... ~~ {k : {k : A → Z // continuous (k ∘ j'₀) ∧ continuous (k ∘ j'₁)} | true} : Bij_on.congr_subtype (ext (continuous_iff ha₀ ha₁)) ... ~~ {p : {p : (A₀ → Z) × (A₁ → Z) // continuous p.1 ∧ continuous p.2} | p.val.1 ∘ i'₀ = p.val.2 ∘ i'₁} : ((Set.Is_pushout_inter_union A₀ A₁).universal Z).restrict_to_subtype (λ p, continuous p.1 ∧ continuous p.2) ... ~~ {p : {f₀ : Top.mk_ob A₀ → Z // continuous f₀} × {f₁ : Top.mk_ob A₁ → Z // continuous f₁} | (Top.hom_equiv_subtype _ _).symm p.1 ∘ i₀ = (Top.hom_equiv_subtype _ _).symm p.2 ∘ i₁} : by { convert Bij_on.restrict_equiv equiv.subtype_prod_subtype_equiv_subtype.symm _, ext, simp only [Top.hom_eq2], refl } ... ~~ {p : (Top.mk_ob A₀ ⟶ Z) × (Top.mk_ob A₁ ⟶ Z) | p.1 ∘ i₀ = p.2 ∘ i₁} : by { convert Bij_on.restrict_equiv ((Top.hom_equiv_subtype (Top.mk_ob A₀) Z).prod_congr (Top.hom_equiv_subtype (Top.mk_ob A₁) Z)).symm _, ext ⟨_, _⟩, refl } local notation `k₀` := incl A₀ local notation `k₁` := incl A₁ variables (h : A₀ ∪ A₁ = univ) include h def union_is_X : homeomorphism (Top.mk_ob A) X := { hom := incl _, inv := Top.mk_hom (λ x, ⟨x, by rw h; exact trivial⟩) (by continuity), hom_inv_id' := by ext p; cases p; refl, inv_hom_id' := by ext p; refl } noncomputable def Is_pushout_inter_of_cover : Is_pushout i₀ i₁ k₀ k₁ := Is_pushout_of_isomorphic' (Is_pushout_inter_union A₀ A₁ ha₀ ha₁) (union_is_X A₀ A₁ h) end inter_union end «Top» end homotopy_theory.topological_spaces
38cc1e9768a5d2e09db752ade03b8023a93f1f95
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/filter/ultrafilter.lean
0d528f34e26f795e9e7099e24f758af7df07a6b2
[ "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
17,191
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.cofinite import order.zorn_atoms /-! # Ultrafilters > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters; * `hyperfilter`: the ultrafilter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} {γ : Type*} open set filter function open_locale classical filter /-- `filter α` is an atomic type: for every filter there exists an ultrafilter that is less than or equal to this filter. -/ instance : is_atomic (filter α) := is_atomic.of_is_chain_bounded $ λ c hc hne hb, ⟨Inf c, (Inf_ne_bot_of_directed' hne (show is_chain (≥) c, from hc.symm).directed_on hb).ne, λ x hx, Inf_le hx⟩ /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ @[protect_proj] structure ultrafilter (α : Type*) extends filter α := (ne_bot' : ne_bot to_filter) (le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g) namespace ultrafilter variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop} instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩ instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩ lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f) (hne : ne_bot g . tactic.apply_instance) : g = f := le_antisymm h $ f.le_of_le g hne h instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot' protected lemma is_atom (f : ultrafilter α) : is_atom (f : filter α) := ⟨f.ne_bot.ne, λ g hgf, by_contra $ λ hg, hgf.ne $ f.unique hgf.le ⟨hg⟩⟩ @[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl lemma coe_injective : injective (coe : ultrafilter α → filter α) | ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr lemma eq_of_le {f g : ultrafilter α} (h : (f : filter α) ≤ g) : f = g := coe_injective (g.unique h) @[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g := ⟨λ h, eq_of_le h, λ h, h ▸ le_rfl⟩ @[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff @[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g := coe_injective $ filter.ext h lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g := le_of_inf_eq (f.unique inf_le_left hg) lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g := f.le_of_inf_ne_bot $ by rwa inf_comm lemma inf_ne_bot_iff {f : ultrafilter α} {g : filter α} : ne_bot (↑f ⊓ g) ↔ ↑f ≤ g := ⟨le_of_inf_ne_bot f, λ h, (inf_of_le_left h).symm ▸ f.ne_bot⟩ lemma disjoint_iff_not_le {f : ultrafilter α} {g : filter α} : disjoint ↑f g ↔ ¬↑f ≤ g := by rw [← inf_ne_bot_iff, ne_bot_iff, ne.def, not_not, disjoint_iff] @[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f := ⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot ⟨λ h, hsc $ mem_of_eq_bot$ by rwa compl_compl⟩, compl_not_mem⟩ @[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x := compl_not_mem_iff alias frequently_iff_eventually ↔ _root_.filter.frequently.eventually _ lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl] lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f := inter_mem_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem /-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by `ultrafilter.compl_not_mem_iff`. -/ def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨λ hf, by simpa [hf] using h⟩, le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem hs (hgf hsc) } /-- If `f : filter α` is an atom, then it is an ultrafilter. -/ def of_atom (f : filter α) (hf : is_atom f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨hf.1⟩, le_of_le := λ g hg, (_root_.is_atom_iff.1 hf).2 g hg.ne } lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem hs lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty @[simp] lemma empty_not_mem : ∅ ∉ f := empty_not_mem f @[simp] lemma le_sup_iff {u : ultrafilter α} {f g : filter α} : ↑u ≤ f ⊔ g ↔ ↑u ≤ f ∨ ↑u ≤ g := not_iff_not.1 $ by simp only [← disjoint_iff_not_le, not_or_distrib, disjoint_sup_right] @[simp] lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := by simp only [← mem_coe, ← le_principal_iff, ← sup_principal, le_sup_iff] lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f := or_iff_not_imp_left.2 compl_mem_iff_not_mem.2 protected lemma em (f : ultrafilter α) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := f.mem_or_compl_mem {x | p x} lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := union_mem_iff lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, eventually_or, eventually_not] lemma finite_sUnion_mem_iff {s : set (set α)} (hs : s.finite) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f := finite.induction_on hs (by simp) $ λ a s ha hs his, by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib] lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : is.finite) : (⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f := by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff] /-- Pushforward for ultrafilters. -/ def map (m : α → β) (f : ultrafilter α) : ultrafilter β := of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s) @[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) : (map m f : filter β) = filter.map m ↑f := rfl @[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} : s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl @[simp] lemma map_id (f : ultrafilter α) : f.map id = f := coe_injective map_id @[simp] lemma map_id' (f : ultrafilter α) : f.map (λ x, x) = f := map_id _ @[simp] lemma map_map (f : ultrafilter α) (m : α → β) (n : β → γ) : (f.map m).map n = f.map (n ∘ m) := coe_injective map_map /-- The pullback of an ultrafilter along an injection whose range is large with respect to the given ultrafilter. -/ def comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : ultrafilter α := { to_filter := comap m u, ne_bot' := u.ne_bot'.comap_of_range_mem large, le_of_le := λ g hg hgu, by { resetI, simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } } @[simp] lemma mem_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) {s : set α} : s ∈ u.comap inj large ↔ m '' s ∈ u := mem_comap_iff inj large @[simp, norm_cast] lemma coe_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : (u.comap inj large : filter α) = filter.comap m u := rfl @[simp] lemma comap_id (f : ultrafilter α) (h₀ : injective (id : α → α) := injective_id) (h₁ : range id ∈ f := by { rw range_id, exact univ_mem}) : f.comap h₀ h₁ = f := coe_injective comap_id @[simp] lemma comap_comap (f : ultrafilter γ) {m : α → β} {n : β → γ} (inj₀ : injective n) (large₀ : range n ∈ f) (inj₁ : injective m) (large₁ : range m ∈ f.comap inj₀ large₀) (inj₂ : injective (n ∘ m) := inj₀.comp inj₁) (large₂ : range (n ∘ m) ∈ f := by { rw range_comp, exact image_mem_of_mem_comap large₀ large₁ }) : (f.comap inj₀ large₀).comap inj₁ large₁ = f.comap inj₂ large₂ := coe_injective comap_comap /-- The principal ultrafilter associated to a point `x`. -/ instance : has_pure ultrafilter := ⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩ @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl @[simp] lemma coe_pure (a : α) : ↑(pure a : ultrafilter α) = (pure a : filter α) := rfl @[simp] lemma map_pure (m : α → β) (a : α) : map m (pure a) = pure (m a) := rfl @[simp] lemma comap_pure {m : α → β} (a : α) (inj : injective m) (large) : comap (pure $ m a) inj large = pure a := coe_injective $ comap_pure.trans $ by rw [coe_pure, ←principal_singleton, ←image_singleton, preimage_image_eq _ inj] lemma pure_injective : injective (pure : α → ultrafilter α) := λ a b h, filter.pure_injective (congr_arg ultrafilter.to_filter h : _) instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure default⟩ instance [nonempty α] : nonempty (ultrafilter α) := nonempty.map pure infer_instance lemma eq_pure_of_finite_mem (h : s.finite) (h' : s ∈ f) : ∃ x ∈ s, f = pure x := begin rw ← bUnion_of_singleton s at h', rcases (ultrafilter.finite_bUnion_mem_iff h).mp h' with ⟨a, has, haf⟩, exact ⟨a, has, eq_of_le (filter.le_pure_iff.2 haf)⟩ end lemma eq_pure_of_finite [finite α] (f : ultrafilter α) : ∃ a, f = pure a := (eq_pure_of_finite_mem finite_univ univ_mem).imp $ λ a ⟨_, ha⟩, ha lemma le_cofinite_or_eq_pure (f : ultrafilter α) : (f : filter α) ≤ cofinite ∨ ∃ a, f = pure a := or_iff_not_imp_left.2 $ λ h, let ⟨s, hs, hfin⟩ := filter.disjoint_cofinite_right.1 (disjoint_iff_not_le.2 h), ⟨a, has, hf⟩ := eq_pure_of_finite_mem hfin hs in ⟨a, hf⟩ /-- Monadic bind for ultrafilters, coming from the one on filters defined in terms of map and join.-/ def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s, by simp only [mem_bind', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl] instance has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance functor : functor ultrafilter := { map := @ultrafilter.map } instance monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, coe_injective (id_map f.1), pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)), bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) } end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_le (f : filter α) [h : ne_bot f] : ∃ u : ultrafilter α, ↑u ≤ f := let ⟨u, hu, huf⟩ := (eq_bot_or_exists_atom_le f).resolve_left h.ne in ⟨of_atom u hu, huf⟩ alias exists_le ← _root_.filter.exists_ultrafilter_le /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α := classical.some (exists_le f) lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f) lemma of_coe (f : ultrafilter α) : of ↑f = f := coe_inj.1 $ f.unique (of_le f) lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α)) (cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) : ∃ F : ultrafilter α, S ⊆ F.sets := begin haveI : ne_bot (generate S) := generate_ne_bot_iff.2 (λ t hts ht, ht.coe_to_finset ▸ cond ht.to_finset (ht.coe_to_finset.symm ▸ hts)), exact ⟨of (generate S), λ t ht, (of_le $ generate S) $ generate_sets.basic ht⟩ end end ultrafilter namespace filter variables {f : filter α} {s : set α} {a : α} open ultrafilter lemma is_atom_pure : is_atom (pure a : filter α) := (pure a : ultrafilter α).is_atom protected lemma ne_bot.le_pure_iff (hf : f.ne_bot) : f ≤ pure a ↔ f = pure a := ⟨ultrafilter.unique (pure a), le_of_eq⟩ @[simp] lemma lt_pure_iff : f < pure a ↔ f = ⊥ := is_atom_pure.lt_iff lemma le_pure_iff' : f ≤ pure a ↔ f = ⊥ ∨ f = pure a := is_atom_pure.le_iff @[simp] lemma Iic_pure (a : α) : Iic (pure a : filter α) = {⊥, pure a} := is_atom_pure.Iic_eq lemma mem_iff_ultrafilter : s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g := begin refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩, set g : filter ↥sᶜ := comap coe f, haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]), simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g)) end lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ := ⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩ /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma supr_ultrafilter_le_eq (f : filter α) : (⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f := eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter] /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ := by simpa only [tendsto_iff_comap] using le_iff_ultrafilter lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f := ⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩ lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) : (∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f := begin refine ⟨λ H f hf, H f f.ne_bot hf, _⟩, introsI H f hf hfg, exact hp (of_le f) (H _ ((of_le f).trans hfg)) end section hyperfilter variables (α) [infinite α] /-- The ultrafilter extending the cofinite filter. -/ noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite variable {α} lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α := ultrafilter.of_le cofinite @[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α := (by apply_instance : ne_bot ↑(hyperfilter α)).1.symm theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α := λ hy, compl_not_mem hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite alias nmem_hyperfilter_of_finite ← _root_.set.finite.nmem_hyperfilter theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) : sᶜ ∈ hyperfilter α := compl_mem_iff_not_mem.2 hf.nmem_hyperfilter alias compl_mem_hyperfilter_of_finite ← _root_.set.finite.compl_mem_hyperfilter theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) : s ∈ hyperfilter α := compl_compl s ▸ hf.compl_mem_hyperfilter end hyperfilter end filter namespace ultrafilter open filter variables {m : α → β} {s : set α} {g : ultrafilter β} lemma comap_inf_principal_ne_bot_of_image_mem (h : m '' s ∈ g) : (filter.comap m g ⊓ 𝓟 s).ne_bot := filter.comap_inf_principal_ne_bot_of_image_mem g.ne_bot h /-- Ultrafilter extending the inf of a comapped ultrafilter and a principal ultrafilter. -/ noncomputable def of_comap_inf_principal (h : m '' s ∈ g) : ultrafilter α := @of _ (filter.comap m g ⊓ 𝓟 s) (comap_inf_principal_ne_bot_of_image_mem h) lemma of_comap_inf_principal_mem (h : m '' s ∈ g) : s ∈ of_comap_inf_principal h := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, have : s ∈ f := mem_inf_of_right (mem_principal_self s), exact le_def.mp (of_le _) s this end lemma of_comap_inf_principal_eq_of_map (h : m '' s ∈ g) : (of_comap_inf_principal h).map m = g := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, apply eq_of_le, calc filter.map m (of f) ≤ filter.map m f : map_mono (of_le _) ... ≤ (filter.map m $ filter.comap m g) ⊓ filter.map m (𝓟 s) : map_inf_le ... = (filter.map m $ filter.comap m g) ⊓ (𝓟 $ m '' s) : by rw map_principal ... ≤ g ⊓ (𝓟 $ m '' s) : inf_le_inf_right _ map_comap_le ... = g : inf_of_le_left (le_principal_iff.mpr h) end end ultrafilter
35ad0f7bd15cc7c930c257cf264f67521b5f8468
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_1/Part_D_relations.lean
397088cdc5b25b3c7ffa5240e1363f482f1358fc
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
8,278
lean
import tactic /-! # Equivalence relations are the same as partitions In this file we prove that there's a bijection between the equivalence relations on a type, and the partitions of a type. Three sections: 1) partitions 2) equivalence classes 3) the proof ## Overview Say `α` is a type, and `R : α → α → Prop` is a binary relation on `α`. The following things are already in Lean: `reflexive R := ∀ (x : α), R x x` `symmetric R := ∀ ⦃x y : α⦄, R x y → R y x` `transitive R := ∀ ⦃x y z : α⦄, R x y → R y z → R x z` `equivalence R := reflexive R ∧ symmetric R ∧ transitive R` In the file below, we will define partitions of `α` and "build some interface" (i.e. prove some propositions). We will define equivalence classes and do the same thing. Finally, we will prove that there's a bijection between equivalence relations on `α` and partitions of `α`. -/ /- # 1) Partitions We define a partition, and prove some lemmas about partitions. Some I prove myself (not always using tactics) and some I leave for you. ## Definition of a partition Let `α` be a type. A *partition* on `α` is defined to be the following data: 1) A set C of subsets of α, called "blocks". 2) A hypothesis (i.e. a proof!) that all the blocks are non-empty. 3) A hypothesis that every term of type α is in one of the blocks. 4) A hypothesis that two blocks with non-empty intersection are equal. -/ /-- The structure of a partition on a Type α. -/ @[ext] structure partition (α : Type) := (C : set (set α)) (Hnonempty : ∀ X ∈ C, (X : set α).nonempty) (Hcover : ∀ a, ∃ X ∈ C, a ∈ X) (Hdisjoint : ∀ X Y ∈ C, (X ∩ Y : set α).nonempty → X = Y) /- ## Basic interface for partitions Here's the way notation works. If `α` is a type (i.e. a set) then a term `P` of type `partition α` is a partition of `α`, that is, a set of disjoint nonempty subsets of `α` whose union is `α`. The collection of sets underlying `P` is `P.C`, the proof that they're all nonempty is `P.Hnonempty` and so on. -/ namespace partition -- let α be a type, and fix a partition P on α. Let X and Y be subsets of α. variables {α : Type} {P : partition α} {X Y : set α} /-- If X and Y are blocks, and a is in X and Y, then X = Y. -/ theorem eq_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a : α} (haX : a ∈ X) (haY : a ∈ Y) : X = Y := -- Proof: follows immediately from the disjointness hypothesis. P.Hdisjoint _ _ hX hY ⟨a, haX, haY⟩ /-- If a is in two blocks X and Y, and if b is in X, then b is in Y (as X=Y) -/ theorem mem_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a b : α} (haX : a ∈ X) (haY : a ∈ Y) (hbX : b ∈ X) : b ∈ Y := begin -- you might want to start with `have hXY : X = Y` -- and prove it from the previous lemma sorry, end /-- Every term of type `α` is in one of the blocks for a partition `P`. -/ theorem mem_block (a : α) : ∃ X : set α, X ∈ P.C ∧ a ∈ X := begin -- an interesting way to start is -- `obtain ⟨X, hX, haX⟩ := P.Hcover a,` sorry, end end partition /- # 2) Equivalence classes. We define equivalence classes and prove a few basic results about them. -/ section equivalence_classes /-! ## Definition of equivalence classes -/ -- Notation and variables for the equivalence class section: -- let α be a type, and let R be a binary relation on R. variables {α : Type} (R : α → α → Prop) /-- The equivalence class of `a` is the set of `b` related to `a`. -/ def cl (a : α) := {b : α | R b a} /-! ## Basic lemmas about equivalence classes -/ /-- Useful for rewriting -- `b` is in the equivalence class of `a` iff `b` is related to `a`. True by definition. -/ theorem mem_cl_iff {a b : α} : b ∈ cl R a ↔ R b a := begin -- true by definition refl end -- Assume now that R is an equivalence relation. variables {R} (hR : equivalence R) include hR /-- x is in cl(x) -/ lemma mem_cl_self (a : α) : a ∈ cl R a := begin -- Note that `hR : equivalence R` is a package of three things. -- You can extract the things with -- `rcases hR with ⟨hrefl, hsymm, htrans⟩,` or -- `obtain ⟨hrefl, hsymm, htrans⟩ := hR,` sorry, end lemma cl_sub_cl_of_mem_cl {a b : α} : a ∈ cl R b → cl R a ⊆ cl R b := begin -- remember `set.subset_def` says `X ⊆ Y ↔ ∀ a, a ∈ X → a ∈ Y sorry, end lemma cl_eq_cl_of_mem_cl {a b : α} : a ∈ cl R b → cl R a = cl R b := begin -- remember `set.subset.antisymm` says `X ⊆ Y → Y ⊆ X → X = Y` sorry end end equivalence_classes -- section /-! # 3) The theorem Let `α` be a type (i.e. a collection of stucff). There is a bijection between equivalence relations on `α` and partitions of `α`. We prove this by writing down constructions in each direction and proving that the constructions are two-sided inverses of one another. -/ open partition example (α : Type) : {R : α → α → Prop // equivalence R} ≃ partition α := -- We define constructions (functions!) in both directions and prove that -- one is a two-sided inverse of the other { -- Here is the first construction, from equivalence -- relations to partitions. -- Let R be an equivalence relation. to_fun := λ R, { -- Let C be the set of equivalence classes for R. C := { B : set α | ∃ x : α, B = cl R.1 x}, -- I claim that C is a partition. We need to check the three -- hypotheses for a partition (`Hnonempty`, `Hcover` and `Hdisjoint`), -- so we need to supply three proofs. Hnonempty := begin cases R with R hR, -- If X is an equivalence class then X is nonempty. show ∀ (X : set α), (∃ (a : α), X = cl R a) → X.nonempty, sorry, end, Hcover := begin cases R with R hR, -- The equivalence classes cover α show ∀ (a : α), ∃ (X : set α) (H : ∃ (b : α), X = cl R b), a ∈ X, sorry, end, Hdisjoint := begin cases R with R hR, -- If two equivalence classes overlap, they are equal. show ∀ (X Y : set α), (∃ (a : α), X = cl R a) → (∃ (b : α), Y = cl _ b) → (X ∩ Y).nonempty → X = Y, sorry, end }, -- Conversely, say P is an partition. inv_fun := λ P, -- Let's define a binary relation `R` thus: -- `R a b` iff *every* block containing `a` also contains `b`. -- Because only one block contains a, this will work, -- and it turns out to be a nice way of thinking about it. ⟨λ a b, ∀ X ∈ P.C, a ∈ X → b ∈ X, begin -- I claim this is an equivalence relation. split, { -- It's reflexive show ∀ (a : α) (X : set α), X ∈ P.C → a ∈ X → a ∈ X, sorry, }, split, { -- it's symmetric show ∀ (a b : α), (∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) → ∀ (X : set α), X ∈ P.C → b ∈ X → a ∈ X, sorry, }, { -- it's transitive unfold transitive, show ∀ (a b c : α), (∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) → (∀ (X : set α), X ∈ P.C → b ∈ X → c ∈ X) → ∀ (X : set α), X ∈ P.C → a ∈ X → c ∈ X, sorry, } end⟩, -- If you start with the equivalence relation, and then make the partition -- and a new equivalence relation, you get back to where you started. left_inv := begin rintro ⟨R, hR⟩, -- Tidying up the mess... suffices : (λ (a b : α), ∀ (c : α), a ∈ cl R c → b ∈ cl R c) = R, simpa, -- ... you have to prove two binary relations are equal. ext a b, -- so you have to prove an if and only if. show (∀ (c : α), a ∈ cl R c → b ∈ cl R c) ↔ R a b, sorry, end, -- Similarly, if you start with the partition, and then make the -- equivalence relation, and then construct the corresponding partition -- into equivalence classes, you have the same partition you started with. right_inv := begin -- Let P be a partition intro P, -- It suffices to prove that a subset X is in the original partition -- if and only if it's in the one made from the equivalence relation. ext X, show (∃ (a : α), X = cl _ a) ↔ X ∈ P.C, dsimp only, sorry, end }
db017e2d3d00c4c2874bdacf6b17ea1bb0430036
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/thin.lean
967837e24a7df8ec79aa25c8284831aa807cecb6
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,042
lean
/- Copyright (c) 2019 Scott Morrison, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.functor_category import category_theory.isomorphism /-! # Thin categories A thin category (also known as a sparse category) is a category with at most one morphism between each pair of objects. Examples include posets, but also some indexing categories (diagrams) for special shapes of (co)limits. To construct a category instance one only needs to specify the `category_struct` part, as the axioms hold for free. If `C` is thin, then the category of functors to `C` is also thin. Further, to show two objects are isomorphic in a thin category, it suffices only to give a morphism in each direction. -/ universes v₁ v₂ u₁ u₂ namespace category_theory variables {C : Type u₁} section variables [category_struct.{v₁} C] [∀ X Y : C, subsingleton (X ⟶ Y)] /-- Construct a category instance from a category_struct, using the fact that hom spaces are subsingletons to prove the axioms. -/ def thin_category : category C := {}. end -- We don't assume anything about where the category instance on `C` came from. -- In particular this allows `C` to be a preorder, with the category instance inherited from the -- preorder structure. variables [category.{v₁} C] {D : Type u₂} [category.{v₂} D] variable [∀ X Y : C, subsingleton (X ⟶ Y)] /-- If `C` is a thin category, then `D ⥤ C` is a thin category. -/ instance functor_thin (F₁ F₂ : D ⥤ C) : subsingleton (F₁ ⟶ F₂) := ⟨λ α β, nat_trans.ext α β (funext (λ _, subsingleton.elim _ _))⟩ /-- To show `X ≅ Y` in a thin category, it suffices to just give any morphism in each direction. -/ def iso_of_both_ways {X Y : C} (f : X ⟶ Y) (g : Y ⟶ X) : X ≅ Y := { hom := f, inv := g } instance subsingleton_iso {X Y : C} : subsingleton (X ≅ Y) := ⟨by { intros i₁ i₂, ext1, apply subsingleton.elim }⟩ end category_theory
12f818359688dcbf79edd91891d87835078d21a4
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.8.lean
401df5aeb6963684ff4fbc5b33875bf20282f0d6
[]
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
931
lean
/- page 79 -/ import standard inductive weekday : Type := | sunday : weekday | monday : weekday | tuesday : weekday | wednesday : weekday | thursday : weekday | friday : weekday | saturday : weekday namespace weekday definition next (d : weekday) : weekday := weekday.cases_on d monday tuesday wednesday thursday friday saturday sunday definition previous (d : weekday) : weekday := weekday.cases_on d saturday sunday monday tuesday wednesday thursday friday -- BEGIN theorem next_previous (d: weekday) : next (previous d) = d := weekday.cases_on d (show next (previous sunday) = sunday, from rfl) (show next (previous monday) = monday, from rfl) (show next (previous tuesday) = tuesday, from rfl) (show next (previous wednesday) = wednesday, from rfl) (show next (previous thursday) = thursday, from rfl) (show next (previous friday) = friday, from rfl) (show next (previous saturday) = saturday, from rfl) -- END end weekday
fcb24e409b789221a88e8b3842a83b893472cc64
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/limits/shapes/zero.lean
cf61dfca9e4f95c2e655c714655cd775467ddbc8
[ "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
15,934
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.products import category_theory.limits.shapes.images import category_theory.isomorphism_classes /-! # Zero morphisms and zero objects A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra structure, not merely a property.) A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object. ## References * https://en.wikipedia.org/wiki/Zero_morphism * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u open category_theory open category_theory.category namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. -/ class has_zero_morphisms := [has_zero : Π X Y : C, has_zero (X ⟶ Y)] (comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously) (zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously) attribute [instance] has_zero_morphisms.has_zero restate_axiom has_zero_morphisms.comp_zero' restate_axiom has_zero_morphisms.zero_comp' variables {C} @[simp] lemma comp_zero [has_zero_morphisms C] {X Y : C} {f : X ⟶ Y} {Z : C} : f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) := has_zero_morphisms.comp_zero f Z @[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y ⟶ Z} : (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) := has_zero_morphisms.zero_comp X f instance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) := { has_zero := by tidy } instance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) := { has_zero := by tidy } namespace has_zero_morphisms variables {C} /-- This lemma will be immediately superseded by `ext`, below. -/ private lemma ext_aux (I J : has_zero_morphisms C) (w : ∀ X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero = (@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J := begin casesI I, casesI J, congr, { ext X Y, exact w X Y }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, } end /-- If you're tempted to use this lemma "in the wild", you should probably carefully consider whether you've made a mistake in allowing two instances of `has_zero_morphisms` to exist at all. See, particularly, the note on `zero_morphisms_of_zero_object` below. -/ lemma ext (I J : has_zero_morphisms C) : I = J := begin apply ext_aux, intros X Y, rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero, rw @has_zero_morphisms.zero_comp _ _ J, end instance : subsingleton (has_zero_morphisms C) := ⟨ext⟩ end has_zero_morphisms open has_zero_morphisms section variables {C} [has_zero_morphisms C] lemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} (g : Y ⟶ Z) [mono g] (h : f ≫ g = 0) : f = 0 := by { rw [←zero_comp, cancel_mono] at h, exact h } lemma zero_of_epi_comp {X Y Z : C} (f : X ⟶ Y) {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 := by { rw [←comp_zero, cancel_epi] at h, exact h } lemma eq_zero_of_image_eq_zero {X Y : C} {f : X ⟶ Y} [has_image f] (w : image.ι f = 0) : f = 0 := by rw [←image.fac f, w, has_zero_morphisms.comp_zero] lemma nonzero_image_of_nonzero {X Y : C} {f : X ⟶ Y} [has_image f] (w : f ≠ 0) : image.ι f ≠ 0 := λ h, w (eq_zero_of_image_eq_zero h) end section universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms C] [has_zero_morphisms D] lemma equivalence_preserves_zero_morphisms (F : C ≌ D) (X Y : C) : F.functor.map (0 : X ⟶ Y) = (0 : F.functor.obj X ⟶ F.functor.obj Y) := begin have t : F.functor.map (0 : X ⟶ Y) = F.functor.map (0 : X ⟶ Y) ≫ (0 : F.functor.obj Y ⟶ F.functor.obj Y), { apply faithful.map_injective (F.inverse), rw [functor.map_comp, equivalence.inv_fun_map], dsimp, rw [zero_comp, comp_zero, zero_comp], }, exact t.trans (by simp) end @[simp] lemma is_equivalence_preserves_zero_morphisms (F : C ⥤ D) [is_equivalence F] (X Y : C) : F.map (0 : X ⟶ Y) = 0 := by rw [←functor.as_equivalence_functor F, equivalence_preserves_zero_morphisms] end variables (C) /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object := (zero : C) (unique_to : Π X : C, unique (zero ⟶ X)) (unique_from : Π X : C, unique (X ⟶ zero)) instance has_zero_object_punit : has_zero_object (discrete punit) := { zero := punit.star, unique_to := by tidy, unique_from := by tidy, } variables {C} namespace has_zero_object variables [has_zero_object C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero : has_zero C := { zero := has_zero_object.zero } local attribute [instance] has_zero_object.has_zero local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from @[ext] lemma to_zero_ext {X : C} (f g : X ⟶ 0) : f = g := by rw [(has_zero_object.unique_from X).uniq f, (has_zero_object.unique_from X).uniq g] @[ext] lemma from_zero_ext {X : C} (f g : 0 ⟶ X) : f = g := by rw [(has_zero_object.unique_to X).uniq f, (has_zero_object.unique_to X).uniq g] instance (X : C) : subsingleton (X ≅ 0) := by tidy instance {X : C} (f : 0 ⟶ X) : mono f := { right_cancellation := λ Z g h w, by ext, } instance {X : C} (f : X ⟶ 0) : epi f := { left_cancellation := λ Z g h w, by ext, } /-- A category with a zero object has zero morphisms. It is rarely a good idea to use this. Many categories that have a zero object have zero morphisms for some other reason, for example from additivity. Library code that uses `zero_morphisms_of_zero_object` will then be incompatible with these categories because the `has_zero_morphisms` instances will not be definitionally equal. For this reason library code should generally ask for an instance of `has_zero_morphisms` separately, even if it already asks for an instance of `has_zero_objects`. -/ def zero_morphisms_of_zero_object : has_zero_morphisms C := { has_zero := λ X Y, { zero := inhabited.default (X ⟶ 0) ≫ inhabited.default (0 ⟶ Y) }, zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, }, comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }} /-- A zero object is in particular initial. -/ lemma has_initial : has_initial C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ lemma has_terminal : has_terminal C := has_terminal_of_unique 0 end has_zero_object section variables [has_zero_object C] [has_zero_morphisms C] local attribute [instance] has_zero_object.has_zero @[simp] lemma id_zero : 𝟙 (0 : C) = (0 : 0 ⟶ 0) := by ext /-- An arrow ending in the zero object is zero -/ -- This can't be a `simp` lemma because the left hand side would be a metavariable. lemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 := by ext lemma zero_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : f = 0 := begin have h : f = f ≫ i.hom ≫ 𝟙 0 ≫ i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id], simpa using h, end /-- An arrow starting at the zero object is zero -/ lemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 := by ext lemma zero_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : f = 0 := begin have h : f = i.hom ≫ 𝟙 0 ≫ i.inv ≫ f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id], simpa using h, end lemma zero_of_source_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic X 0) : f = 0 := zero_of_source_iso_zero f (nonempty.some i) lemma zero_of_target_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic Y 0) : f = 0 := zero_of_target_iso_zero f (nonempty.some i) lemma mono_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : mono f := ⟨λ Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]⟩ lemma epi_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : epi f := ⟨λ Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]⟩ /-- An object `X` has `𝟙 X = 0` if and only if it is isomorphic to the zero object. Because `X ≅ 0` contains data (even if a subsingleton), we express this `↔` as an `≃`. -/ def id_zero_equiv_iso_zero (X : C) : (𝟙 X = 0) ≃ (X ≅ 0) := { to_fun := λ h, { hom := 0, inv := 0, }, inv_fun := λ i, zero_of_target_iso_zero (𝟙 X) i, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : 𝟙 X = 0) : ((id_zero_equiv_iso_zero X) h).hom = 0 := rfl @[simp] lemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : 𝟙 X = 0) : ((id_zero_equiv_iso_zero X) h).inv = 0 := rfl /-- If an object `X` is isomorphic to 0, there's no need to use choice to construct an explicit isomorphism: the zero morphism suffices. -/ def iso_of_is_isomorphic_zero {X : C} (P : is_isomorphic X 0) : X ≅ 0 := { hom := 0, inv := 0, hom_inv_id' := begin casesI P, rw ←P.hom_inv_id, rw ←category.id_comp P.inv, simp, end, inv_hom_id' := by simp, } end section is_iso variables [has_zero_morphisms C] /-- A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if the identities on both `X` and `Y` are zero. -/ @[simps] def is_iso_zero_equiv (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (𝟙 X = 0 ∧ 𝟙 Y = 0) := { to_fun := by { introsI i, rw ←is_iso.hom_inv_id (0 : X ⟶ Y), rw ←is_iso.inv_hom_id (0 : X ⟶ Y), simp }, inv_fun := λ h, { inv := (0 : Y ⟶ X), }, left_inv := by tidy, right_inv := by tidy, } /-- A zero morphism `0 : X ⟶ X` is an isomorphism if and only if the identity on `X` is zero. -/ def is_iso_zero_self_equiv (X : C) : is_iso (0 : X ⟶ X) ≃ (𝟙 X = 0) := by simpa using is_iso_zero_equiv X X variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if `X` and `Y` are isomorphic to the zero object. -/ def is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (X ≅ 0) × (Y ≅ 0) := begin -- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`. refine (is_iso_zero_equiv X Y).trans _, symmetry, fsplit, { rintros ⟨eX, eY⟩, fsplit, exact (id_zero_equiv_iso_zero X).symm eX, exact (id_zero_equiv_iso_zero Y).symm eY, }, { rintros ⟨hX, hY⟩, fsplit, exact (id_zero_equiv_iso_zero X) hX, exact (id_zero_equiv_iso_zero Y) hY, }, { tidy, }, { tidy, }, end /-- A zero morphism `0 : X ⟶ X` is an isomorphism if and only if `X` is isomorphic to the zero object. -/ def is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X ⟶ X) ≃ (X ≅ 0) := (is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv end is_iso /-- If there are zero morphisms, any initial object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_initial_object [has_zero_morphisms C] [has_initial C] : has_zero_object C := { zero := ⊥_ C, unique_to := λ X, ⟨⟨0⟩, by tidy⟩, unique_from := λ X, ⟨⟨0⟩, λ f, calc f = f ≫ 𝟙 _ : (category.comp_id _).symm ... = f ≫ 0 : by congr ... = 0 : has_zero_morphisms.comp_zero _ _ ⟩ } /-- If there are zero morphisms, any terminal object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_terminal_object [has_zero_morphisms C] [has_terminal C] : has_zero_object C := { zero := ⊤_ C, unique_from := λ X, ⟨⟨0⟩, by tidy⟩, unique_to := λ X, ⟨⟨0⟩, λ f, calc f = 𝟙 _ ≫ f : (category.id_comp _).symm ... = 0 ≫ f : by congr ... = 0 : zero_comp ⟩ } section image variable [has_zero_morphisms C] lemma image_ι_comp_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f] [epi (factor_thru_image f)] (h : f ≫ g = 0) : image.ι f ≫ g = 0 := zero_of_epi_comp (factor_thru_image f) $ by simp [h] variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The zero morphism has a `mono_factorisation` through the zero object. -/ @[simps] def mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X ⟶ Y) := { I := 0, m := 0, e := 0, } /-- The factorisation through the zero object is an image factorisation. -/ def image_factorisation_zero (X Y : C) : image_factorisation (0 : X ⟶ Y) := { F := mono_factorisation_zero X Y, is_image := { lift := λ F', 0 } } instance has_image_zero {X Y : C} : has_image (0 : X ⟶ Y) := has_image.mk $ image_factorisation_zero _ _ /-- The image of a zero morphism is the zero object. -/ def image_zero {X Y : C} : image (0 : X ⟶ Y) ≅ 0 := is_image.iso_ext (image.is_image (0 : X ⟶ Y)) (image_factorisation_zero X Y).is_image /-- The image of a morphism which is equal to zero is the zero object. -/ def image_zero' {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image f ≅ 0 := image.eq_to_iso h ≪≫ image_zero @[simp] lemma image.ι_zero {X Y : C} [has_image (0 : X ⟶ Y)] : image.ι (0 : X ⟶ Y) = 0 := begin rw ←image.lift_fac (mono_factorisation_zero X Y), simp, end /-- If we know `f = 0`, it requires a little work to conclude `image.ι f = 0`, because `f = g` only implies `image f ≅ image g`. -/ @[simp] lemma image.ι_zero' [has_equalizers C] {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image.ι f = 0 := by { rw image.eq_fac h, simp } end image /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_sigma_ι {β : Type v} [decidable_eq β] [has_zero_morphisms C] (f : β → C) [has_colimit (discrete.functor f)] (b : β) : split_mono (sigma.ι f b) := { retraction := sigma.desc (λ b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_pi_π {β : Type v} [decidable_eq β] [has_zero_morphisms C] (f : β → C) [has_limit (discrete.functor f)] (b : β) : split_epi (pi.π f b) := { section_ := pi.lift (λ b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inl [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inl : X ⟶ X ⨿ Y) := { retraction := coprod.desc (𝟙 X) 0, } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inr [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inr : Y ⟶ X ⨿ Y) := { retraction := coprod.desc 0 (𝟙 Y), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_fst [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.fst : X ⨯ Y ⟶ X) := { section_ := prod.lift (𝟙 X) 0, } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_snd [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.snd : X ⨯ Y ⟶ Y) := { section_ := prod.lift 0 (𝟙 Y), } end category_theory.limits
900ecf54508d732a6e885a10c14e3fb74e08e3f5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/PreDefinition/WF/Fix.lean
eed16d3e65363e040030b19716b2cfdfe8d2d2cc
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
9,311
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.Util.HasConstCache import Lean.Meta.CasesOn import Lean.Meta.Match.Match import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Cleanup import Lean.Elab.Tactic.Basic import Lean.Elab.RecAppSyntax import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural.Basic import Lean.Elab.PreDefinition.Structural.BRecOn namespace Lean.Elab.WF open Meta private def applyDefaultDecrTactic (mvarId : MVarId) : TermElabM Unit := do let remainingGoals ← Tactic.run mvarId do Tactic.evalTactic (← `(tactic| decreasing_tactic)) remainingGoals.forM fun mvarId => Term.reportUnsolvedGoals [mvarId] private def mkDecreasingProof (decreasingProp : Expr) (decrTactic? : Option Syntax) : TermElabM Expr := do let mvar ← mkFreshExprSyntheticOpaqueMVar decreasingProp let mvarId := mvar.mvarId! let mvarId ← mvarId.cleanup match decrTactic? with | none => applyDefaultDecrTactic mvarId | some decrTactic => -- make info from `runTactic` available pushInfoTree (.hole mvarId) Term.runTactic mvarId decrTactic instantiateMVars mvar private partial def replaceRecApps (recFnName : Name) (fixedPrefixSize : Nat) (decrTactic? : Option Syntax) (F : Expr) (e : Expr) : TermElabM Expr := do trace[Elab.definition.wf] "replaceRecApps:{indentExpr e}" trace[Elab.definition.wf] "{F} : {← inferType F}" loop F e |>.run' {} where processRec (F : Expr) (e : Expr) : StateRefT (HasConstCache recFnName) TermElabM Expr := do if e.getAppNumArgs < fixedPrefixSize + 1 then loop F (← etaExpand e) else let args := e.getAppArgs let r := mkApp F (← loop F args[fixedPrefixSize]!) let decreasingProp := (← whnf (← inferType r)).bindingDomain! let r := mkApp r (← mkDecreasingProof decreasingProp decrTactic?) return mkAppN r (← args[fixedPrefixSize+1:].toArray.mapM (loop F)) processApp (F : Expr) (e : Expr) : StateRefT (HasConstCache recFnName) TermElabM Expr := do if e.isAppOf recFnName then processRec F e else e.withApp fun f args => return mkAppN (← loop F f) (← args.mapM (loop F)) containsRecFn (e : Expr) : StateRefT (HasConstCache recFnName) TermElabM Bool := do modifyGet (·.contains e) loop (F : Expr) (e : Expr) : StateRefT (HasConstCache recFnName) TermElabM Expr := do if !(← containsRecFn e) then return e match e with | Expr.lam n d b c => withLocalDecl n c (← loop F d) fun x => do mkLambdaFVars #[x] (← loop F (b.instantiate1 x)) | Expr.forallE n d b c => withLocalDecl n c (← loop F d) fun x => do mkForallFVars #[x] (← loop F (b.instantiate1 x)) | Expr.letE n type val body _ => withLetDecl n (← loop F type) (← loop F val) fun x => do mkLetFVars #[x] (← loop F (body.instantiate1 x)) (usedLetOnly := false) | Expr.mdata d b => if let some stx := getRecAppSyntax? e then withRef stx <| loop F b else return mkMData d (← loop F b) | Expr.proj n i e => return mkProj n i (← loop F e) | Expr.const .. => if e.isConstOf recFnName then processRec F e else return e | Expr.app .. => match (← matchMatcherApp? e) with | some matcherApp => if !Structural.recArgHasLooseBVarsAt recFnName fixedPrefixSize e then processApp F e else if let some matcherApp ← matcherApp.addArg? F then if !(← Structural.refinedArgType matcherApp F) then processApp F e else let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let FAlt := xs[numParams - 1]! mkLambdaFVars xs (← loop FAlt altBody) return { matcherApp with alts := altsNew, discrs := (← matcherApp.discrs.mapM (loop F)) }.toExpr else processApp F e | none => match (← toCasesOnApp? e) with | some casesOnApp => if !Structural.recArgHasLooseBVarsAt recFnName fixedPrefixSize e then processApp F e else if let some casesOnApp ← casesOnApp.addArg? F (checkIfRefined := true) then let altsNew ← (Array.zip casesOnApp.alts casesOnApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError "unexpected `casesOn` application alternative{indentExpr alt}\nat application{indentExpr e}" let FAlt := xs[numParams]! mkLambdaFVars xs (← loop FAlt altBody) return { casesOnApp with alts := altsNew remaining := (← casesOnApp.remaining.mapM (loop F)) }.toExpr else processApp F e | none => processApp F e | e => ensureNoRecFn recFnName e /-- Refine `F` over `PSum.casesOn` -/ private partial def processSumCasesOn (x F val : Expr) (k : (x : Expr) → (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do if x.isFVar && val.isAppOfArity ``PSum.casesOn 6 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 5).isLambda then let args := val.getAppArgs let α := args[0]! let β := args[1]! let FDecl ← F.fvarId!.getDecl let (motiveNew, u) ← lambdaTelescope args[2]! fun xs type => do let type ← mkArrow (FDecl.type.replaceFVar x xs[0]!) type return (← mkLambdaFVars xs type, ← getLevel type) let mkMinorNew (ctorName : Name) (minor : Expr) : TermElabM Expr := lambdaTelescope minor fun xs body => do let xNew := xs[0]! let valNew ← mkLambdaFVars xs[1:] body let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM ctorName #[α, β, xNew]) withLocalDeclD FDecl.userName FTypeNew fun FNew => do mkLambdaFVars #[xNew, FNew] (← processSumCasesOn xNew FNew valNew k) let minorLeft ← mkMinorNew ``PSum.inl args[4]! let minorRight ← mkMinorNew ``PSum.inr args[5]! let result := mkAppN (mkConst ``PSum.casesOn [u, (← getLevel α), (← getLevel β)]) #[α, β, motiveNew, x, minorLeft, minorRight, F] return result else k x F val /-- Refine `F` over `PSigma.casesOn` -/ private partial def processPSigmaCasesOn (x F val : Expr) (k : (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do if x.isFVar && val.isAppOfArity ``PSigma.casesOn 5 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 4).bindingBody!.isLambda then let args := val.getAppArgs let [_, u, v] := val.getAppFn.constLevels! | unreachable! let α := args[0]! let β := args[1]! let FDecl ← F.fvarId!.getDecl let (motiveNew, w) ← lambdaTelescope args[2]! fun xs type => do let type ← mkArrow (FDecl.type.replaceFVar x xs[0]!) type return (← mkLambdaFVars xs type, ← getLevel type) let minor ← lambdaTelescope args[4]! fun xs body => do let a := xs[0]! let xNew := xs[1]! let valNew ← mkLambdaFVars xs[2:] body let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM `PSigma.mk #[α, β, a, xNew]) withLocalDeclD FDecl.userName FTypeNew fun FNew => do mkLambdaFVars #[a, xNew, FNew] (← processPSigmaCasesOn xNew FNew valNew k) let result := mkAppN (mkConst ``PSigma.casesOn [w, u, v]) #[α, β, motiveNew, x, minor, F] return result else k F val def mkFix (preDef : PreDefinition) (prefixArgs : Array Expr) (wfRel : Expr) (decrTactic? : Option Syntax) : TermElabM Expr := do let type ← instantiateForall preDef.type prefixArgs let (wfFix, varName) ← forallBoundedTelescope type (some 1) fun x type => do let x := x[0]! let α ← inferType x let u ← getLevel α let v ← getLevel type let motive ← mkLambdaFVars #[x] type let rel := mkProj ``WellFoundedRelation 0 wfRel let wf := mkProj ``WellFoundedRelation 1 wfRel let varName ← x.fvarId!.getUserName -- See comment below. return (mkApp4 (mkConst ``WellFounded.fix [u, v]) α motive rel wf, varName) forallBoundedTelescope (← whnf (← inferType wfFix)).bindingDomain! (some 2) fun xs _ => do let x := xs[0]! -- Remark: we rename `x` here to make sure we preserve the variable name in the -- decreasing goals when the function has only one non fixed argument. -- This renaming is irrelevant if the function has multiple non fixed arguments. See `process*` functions above. let lctx := (← getLCtx).setUserName x.fvarId! varName withTheReader Meta.Context (fun ctx => { ctx with lctx }) do let F := xs[1]! let val := preDef.value.beta (prefixArgs.push x) let val ← processSumCasesOn x F val fun x F val => do processPSigmaCasesOn x F val (replaceRecApps preDef.declName prefixArgs.size decrTactic?) mkLambdaFVars prefixArgs (mkApp wfFix (← mkLambdaFVars #[x, F] val)) end Lean.Elab.WF
72df6e30de06de411b607e426ce1fe1f817bed7d
7453f4f6074a6d5ce92b7bee2b29c409c061fbef
/src/Interpolation/lagrange_v1.lean
7112942b8b480652666ca949eba4745d38ec46c9
[ "Apache-2.0" ]
permissive
stanescuUW/numerical-analysis-with-Lean
b7b26755b8e925279f3afc1caa16b0666fc77ef8
98e6974f8b68cc5232ceff40535d776a33444c73
refs/heads/master
1,670,371,433,242
1,598,204,960,000
1,598,204,960,000
282,081,575
0
0
null
null
null
null
UTF-8
Lean
false
false
2,036
lean
import data.polynomial import data.real.basic import algebra.big_operators noncomputable theory open_locale big_operators open polynomial -- The basic building block in the Lagrange polynomial -- this is (x - b)/(a - b) def scaled_binomial (a b : ℝ) : polynomial ℝ := ((1 : ℝ) / (a - b)) • (X - C b) @[simp] lemma scaled_binomial.def (a b : ℝ) : scaled_binomial a b = ((1 : ℝ) / (a - b)) • (X - C b) := rfl lemma bin_zero (a b : ℝ) : eval b (scaled_binomial a b) = 0 := by rw [scaled_binomial.def, eval_smul, eval_sub, eval_X, eval_C, sub_self, smul_eq_mul, mul_zero] lemma bin_one (a b : ℝ) (h : a ≠ b) : eval a (scaled_binomial a b) = 1 := by rw [scaled_binomial.def, eval_smul, eval_sub, eval_X, eval_C, smul_eq_mul, div_mul_cancel 1 (sub_ne_zero_of_ne h)] -- This version, using scalar multiplication (`smul`) seems simplest. -- Must add hypothesis that data points are distinct def lagrange_interpolant (n : ℕ) (i : ℕ) (xData : ℕ → ℝ) : polynomial ℝ := ∏ j in (finset.range (n+1)).erase i, scaled_binomial (xData i) (xData j) -- This has been PR'd into mathlib as `eval_prod` lemma eval_finset.prod {ι : Type*} (s : finset ι) (p : ι → polynomial ℝ) (x : ℝ) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := (finset.prod_hom _ _).symm -- The equivalent of the above for sums lemma eval_finset.sum {ι : Type*} (s : finset ι) (p : ι → polynomial ℝ) (x : ℝ) : eval x (∑ j in s, p j) = ∑ j in s, eval x (p j) := (finset.sum_hom _ _).symm -- The Lagrange interpolant `Lᵢ x` is one for `x = xData i` @[simp] lemma lagrange_interpolant_one (n : ℕ) (xData : ℕ → ℝ) (i : ℕ) (hinj : function.injective xData) : eval (xData i) (lagrange_interpolant n i xData) = (1:ℝ) := begin unfold lagrange_interpolant, rw eval_finset.prod, --simp only [bin_one], -- simp fails because the simplifier can't derive `a ≠ b` exact finset.prod_eq_one (λ j hj, bin_one (xData i) (xData j) (mt (@hinj i j) (finset.ne_of_mem_erase hj).symm)) end
c9e63f5b6a93026cf1b53c78028dba4f6c463644
48f4f349e1bb919d14ab7e5921d0cfe825f4c423
/folklore/polytope.lean
669e5301cd3416da2a828dd2265e2a67a3c582a4
[]
no_license
thalesant/formalabstracts-2017
fdf4ff90d30ab1dcb6d4cf16a068a997ea5ecc80
c47181342c9e41954aa8d41f5049965b5f332bca
refs/heads/master
1,584,610,453,925
1,528,277,508,000
1,528,277,508,000
136,299,625
0
0
null
null
null
null
UTF-8
Lean
false
false
3,409
lean
/- Convexity and polytopes following HOL Light generalized to a general vector space over ℝ -/ import order.filter data.set meta_data data.list data.vector .real_axiom algebra.module data.finset.basic .metric noncomputable theory namespace polytope open set filter classical nat int list vector real_axiom metric finset local attribute [instance] prop_decidable universes u v w variables {α : Type u} { β : Type u} variable [vector_space ℝ β] def hull (A : set (set α)) s := ⋂₀ { t | A t ∧ s ⊆ t} def affine (s : set β) := (∀ x y (u : ℝ) v, x ∈ s ∧ y ∈ s ∧ u + v = 1 → (u • x + v • y ∈ s)) def convex (s : set β) := (∀ x y (u : ℝ) v, x ∈ s ∧ y ∈ s ∧ 0 ≤ u ∧ 0 ≤ v ∧ u + v = 1 → (u • x + v • y) ∈ s) def conic (s : set β) := (∀ x (c : ℝ), x ∈ s ∧ 0 ≤ c → c • x ∈ s) def affine_dependent (s : set β) := (∃ x ∈ s, x ∈ hull affine (s \ {x})) def coplanar (s : set β) := (∃ u v w, s ⊆ hull affine {u,v,w}) def convex_on (f : β → ℝ) (s : set β) := (∀ x y u v, x ∈ s ∧ y ∈ s ∧ 0 ≤ u ∧ 0 ≤ v ∧ u + v = 1 → f (u • x + v • y) ≤ u * f x + v * f y) instance : has_coe (finset β) (set β) := ⟨ λ s, { x | x ∈ s} ⟩ open finset def has_aff_dim (s : set β) (d : int) := (∃ (b : finset β), hull affine ( b :set β) = hull affine s ∧ ¬ (affine_dependent (b : set β)) ∧ (card b : ℤ) = d +1) def aff_dim_exists (s : set β) : Prop := (∃ d, has_aff_dim s d) def aff_dim (s : set β) := if p : aff_dim_exists s then classical.some p else 0 def convex_cone (s : set β) := ¬ (s= ∅) ∧ convex s ∧ conic s def closed_segment (a : β) (b : β) := image (λ u, (1 - u) • a + u • b) { u | 0 ≤ u ∧ u ≤ 1} def open_segment (a : β) (b : β) := closed_segment a b \ {a,b} def starlike (s : set β) := (∃ a ∈ s, ∀ x ∈ s, closed_segment a x ⊆ s) section variables [X : topological_space β] def relative_interior (s : set β) := { x : β | ∃ t, is_open (induced_space X ((hull affine s) : set β)) t ∧ x ∈ (t : set β) ∧ (t : set β) ⊆ s } def relative_frontier (s : set β) := closure X s \ relative_interior s end -- section def face_of t (s : set β) := (t ⊆ s ∧ convex t ∧ (∀ a b x, a ∈ s ∧ b ∈ s ∧ x ∈ t ∧ x ∈ open_segment a b → a ∈ t ∧ b ∈ t)) /- -- skip needs dot product def exposed_face_of t (s : set β) := (face_of t s ∧ ∃ a b, s ⊆ -/ /- -- skip need to find sum def barycentre (s : finset β) := sum (λ (x : β), ((card s : ℝ)⁻¹ • x : β)) -/ def extreme_point_of (s : set β) x := (x ∈ s ∧ ∀ a b, a ∈ s ∧ b ∈ s → ¬(x ∈ open_segment a b)) def facet_of f (s : set β) := face_of f s ∧ ¬ ( f = ∅) ∧ aff_dim f = aff_dim s - 1 def edge_of e (s : set β) := face_of e s ∧ aff_dim e = 1 def polytope (s : set β) := (∃ (v : finset β), s = hull convex (v : set β)) -- skip polyhedron, uses dot def simplex (n : int) (s : set β) := (∃ (c : finset β), ¬(affine_dependent (c : set β)) ∧ (card c : int) = n + 1 ∧ s = hull convex (c : set β)) def simplicial_complex (c : finset (set β)) := (∀ s ∈ c, ∃ n, simplex n s) ∧ (∀ f s ∈ c, face_of f s → f ∈ c) ∧ (∀ s ∈ c, ∀ s' ∈ c, face_of (s ∩ s') s ∧ face_of (s ∩ s') s') -- skip triangulation, uses ℝ^n end polytope
bd1375cb5151eb9bd572eb3941fa310e36432dec
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/category/constructions/pushout.hlean
25cad0c228dcc72c66c95d2e822a30c81dc8ff85
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
21,444
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The pushout of categories The morphisms in the pushout of two categories is defined as a quotient on lists of composable morphisms. For this we use the notion of paths in a graph. -/ import ..category ..nat_trans hit.set_quotient algebra.relation ..groupoid algebra.graph .functor open eq is_trunc functor trunc sum set_quotient relation iso category sigma nat nat_trans /- we first define the categorical structure on paths in a graph -/ namespace paths section parameters {A : Type} {R : A → A → Type} (Q : Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type) variables ⦃a a' a₁ a₂ a₃ a₄ : A⦄ definition paths_trel [constructor] (l l' : paths R a a') : Prop := ∥paths_rel Q l l'∥ local notation `S` := @paths_trel definition paths_quotient (a a' : A) : Type := set_quotient (@S a a') local notation `mor` := paths_quotient local attribute paths_quotient [reducible] definition is_reflexive_R : is_reflexive (@S a a') := begin constructor, intro s, apply tr, constructor end local attribute is_reflexive_R [instance] definition paths_compose [unfold 7 8] (g : mor a₂ a₃) (f : mor a₁ a₂) : mor a₁ a₃ := begin refine quotient_binary_map _ _ g f, exact append, intros, refine trunc_functor2 _ r s, exact rel_respect_append end definition paths_id [constructor] (a : A) : mor a a := class_of nil local infix ` ∘∘ `:60 := paths_compose local notation `p1` := paths_id _ theorem paths_assoc (h : mor a₃ a₄) (g : mor a₂ a₃) (f : mor a₁ a₂) : h ∘∘ (g ∘∘ f) = (h ∘∘ g) ∘∘ f := begin induction h using set_quotient.rec_prop with h, induction g using set_quotient.rec_prop with g, induction f using set_quotient.rec_prop with f, rewrite [▸*, append_assoc] end theorem paths_id_left (f : mor a a') : p1 ∘∘ f = f := begin induction f using set_quotient.rec_prop with f, reflexivity end theorem paths_id_right (f : mor a a') : f ∘∘ p1 = f := begin induction f using set_quotient.rec_prop with f, rewrite [▸*, append_nil] end definition Precategory_paths [constructor] : Precategory := precategory.MK A mor _ paths_compose paths_id paths_assoc paths_id_left paths_id_right /- given a way to reverse edges and some additional properties we can extend this to a groupoid structure -/ parameters (inv : Π⦃a a' : A⦄, R a a' → R a' a) (rel_inv : Π⦃a a' : A⦄ {l l' : paths R a a'}, Q l l' → paths_rel Q (reverse inv l) (reverse inv l')) (li : Π⦃a a' : A⦄ (r : R a a'), paths_rel Q [inv r, r] nil) (ri : Π⦃a a' : A⦄ (r : R a a'), paths_rel Q [r, inv r] nil) include rel_inv li ri definition paths_inv [unfold 8] (f : mor a a') : mor a' a := begin refine quotient_unary_map (reverse inv) _ f, intros, refine trunc_functor _ _ r, esimp, intro s, apply rel_respect_reverse inv s rel_inv end local postfix `^`:max := paths_inv theorem paths_left_inv (f : mor a₁ a₂) : f^ ∘∘ f = p1 := begin induction f using set_quotient.rec_prop with f, esimp, apply eq_of_rel, apply tr, apply rel_left_inv, apply li end theorem paths_right_inv (f : mor a₁ a₂) : f ∘∘ f^ = p1 := begin induction f using set_quotient.rec_prop with f, esimp, apply eq_of_rel, apply tr, apply rel_right_inv, apply ri end definition Groupoid_paths [constructor] : Groupoid := groupoid.MK Precategory_paths (λa b f, is_iso.mk (paths_inv f) (paths_left_inv f) (paths_right_inv f)) end end paths open paths namespace category /- We also define the pushout of two groupoids with a type of basepoints, which are surjectively mapped into C (although we don't need to assume that this mapping is surjective for the definition) -/ section inductive bpushout_prehom_index {S : Type} {C D E : Precategory} (k : S → C) (F : C ⇒ D) (G : C ⇒ E) : D + E → D + E → Type := | iD : Π{d d' : D} (f : d ⟶ d'), bpushout_prehom_index k F G (inl d) (inl d') | iE : Π{e e' : E} (g : e ⟶ e'), bpushout_prehom_index k F G (inr e) (inr e') | DE : Π(s : S), bpushout_prehom_index k F G (inl (F (k s))) (inr (G (k s))) | ED : Π(s : S), bpushout_prehom_index k F G (inr (G (k s))) (inl (F (k s))) open bpushout_prehom_index definition bpushout_prehom {S : Type} {C D E : Precategory} (k : S → C) (F : C ⇒ D) (G : C ⇒ E) : D + E → D + E → Type := paths (bpushout_prehom_index k F G) inductive bpushout_hom_rel_index {S : Type} {C D E : Precategory} (k : S → C) (F : C ⇒ D) (G : C ⇒ E) : Π⦃x x' : D + E⦄, bpushout_prehom k F G x x' → bpushout_prehom k F G x x' → Type := | DD : Π{d₁ d₂ d₃ : D} (g : d₂ ⟶ d₃) (f : d₁ ⟶ d₂), bpushout_hom_rel_index k F G [iD k F G g, iD k F G f] [iD k F G (g ∘ f)] | EE : Π{e₁ e₂ e₃ : E} (g : e₂ ⟶ e₃) (f : e₁ ⟶ e₂), bpushout_hom_rel_index k F G [iE k F G g, iE k F G f] [iE k F G (g ∘ f)] | DED : Π(s : S), bpushout_hom_rel_index k F G [ED k F G s, DE k F G s] nil | EDE : Π(s : S), bpushout_hom_rel_index k F G [DE k F G s, ED k F G s] nil | idD : Π(d : D), bpushout_hom_rel_index k F G [iD k F G (ID d)] nil | idE : Π(e : E), bpushout_hom_rel_index k F G [iE k F G (ID e)] nil | cohDE : Π{s₁ s₂ : S} (h : k s₁ ⟶ k s₂), bpushout_hom_rel_index k F G [iE k F G (G h), DE k F G s₁] [DE k F G s₂, iD k F G (F h)] | cohED : Π{s₁ s₂ : S} (h : k s₁ ⟶ k s₂), bpushout_hom_rel_index k F G [ED k F G s₂, iE k F G (G h)] [iD k F G (F h), ED k F G s₁] open bpushout_hom_rel_index paths.paths_rel definition Precategory_bpushout [constructor] {S : Type} {C D E : Precategory} (k : S → C) (F : C ⇒ D) (G : C ⇒ E) : Precategory := Precategory_paths (bpushout_hom_rel_index k F G) parameters {C D E X : Precategory} (F : C ⇒ D) (G : C ⇒ E) (H : D ⇒ X) (K : E ⇒ X) (η : H ∘f F ≅ K ∘f G) definition Cpushout [constructor] : Precategory := Precategory_bpushout (λc, c) F G definition Cpushout_inl [constructor] : D ⇒ Cpushout := begin fapply functor.mk, { exact inl}, { intro d d' f, exact class_of [iD (λc, c) F G f]}, { intro d, refine eq_of_rel (tr (paths_rel_of_Q _)), apply idD}, { intro d₁ d₂ d₃ g f, refine (eq_of_rel (tr (paths_rel_of_Q _)))⁻¹, apply DD} end definition Cpushout_inr [constructor] : E ⇒ Cpushout := begin fapply functor.mk, { exact inr}, { intro e e' f, exact class_of [iE (λc, c) F G f]}, { intro e, refine eq_of_rel (tr (paths_rel_of_Q _)), apply idE}, { intro e₁ e₂ e₃ g f, refine (eq_of_rel (tr (paths_rel_of_Q _)))⁻¹, apply EE} end definition Cpushout_coh [constructor] : Cpushout_inl ∘f F ≅ Cpushout_inr ∘f G := begin fapply natural_iso.MK, { intro c, exact class_of [DE (λ c, c) F G c]}, { intro c c' f, refine eq_of_rel (tr (paths_rel_of_Q !cohDE))}, { intro c, exact class_of [ED (λ c, c) F G c]}, { intro c, refine eq_of_rel (tr (paths_rel_of_Q !DED))}, { intro c, refine eq_of_rel (tr (paths_rel_of_Q !EDE))}, end --(class_of [DE (λ c, c) F G s]) variables ⦃x x' x₁ x₂ x₃ : Cpushout⦄ include H K local notation `R` := bpushout_prehom_index (λ c, c) F G local notation `Q` := bpushout_hom_rel_index (λ c, c) F G definition Cpushout_functor_ob [unfold 9] (x : Cpushout) : X := begin induction x with d e, { exact H d}, { exact K e} end include η parameters {F G H K} definition Cpushout_functor_reduction_rule [unfold 12] (i : R x x') : Cpushout_functor_ob x ⟶ Cpushout_functor_ob x' := begin induction i, { exact H f}, { exact K g}, { exact natural_map (to_hom η) s}, { exact natural_map (to_inv η) s} end definition Cpushout_functor_list (l : paths R x x') : Cpushout_functor_ob x ⟶ Cpushout_functor_ob x' := realize _ Cpushout_functor_reduction_rule (λa, id) (λa b c g f, f ∘ g) l definition Cpushout_functor_list_nil (x : Cpushout) : Cpushout_functor_list (@nil _ _ x) = id := idp definition Cpushout_functor_list_cons (r : R x₂ x₃) (l : paths R x₁ x₂) : Cpushout_functor_list (r :: l) = Cpushout_functor_reduction_rule r ∘ Cpushout_functor_list l := idp definition Cpushout_functor_list_singleton (r : R x₁ x₂) : Cpushout_functor_list [r] = Cpushout_functor_reduction_rule r := realize_singleton (λa b f, id_right f) r definition Cpushout_functor_list_pair (r₂ : R x₂ x₃) (r₁ : R x₁ x₂) : Cpushout_functor_list [r₂, r₁] = Cpushout_functor_reduction_rule r₂ ∘ Cpushout_functor_reduction_rule r₁ := realize_pair (λa b f, id_right f) r₂ r₁ definition Cpushout_functor_list_append (l₂ : paths R x₂ x₃) (l₁ : paths R x₁ x₂) : Cpushout_functor_list (l₂ ++ l₁) = Cpushout_functor_list l₂ ∘ Cpushout_functor_list l₁ := realize_append (λa b c d h g f, assoc f g h) (λa b f, id_left f) l₂ l₁ theorem Cpushout_functor_list_rel {l l' : paths R x x'} (q : Q l l') : Cpushout_functor_list l = Cpushout_functor_list l' := begin induction q, { rewrite [Cpushout_functor_list_pair, Cpushout_functor_list_singleton], exact (respect_comp H g f)⁻¹}, { rewrite [Cpushout_functor_list_pair, Cpushout_functor_list_singleton], exact (respect_comp K g f)⁻¹}, { rewrite [Cpushout_functor_list_pair, Cpushout_functor_list_nil], exact ap010 natural_map (to_left_inverse η) s}, { rewrite [Cpushout_functor_list_pair, Cpushout_functor_list_nil], exact ap010 natural_map (to_right_inverse η) s}, { rewrite [Cpushout_functor_list_singleton, Cpushout_functor_list_nil], exact respect_id H d}, { rewrite [Cpushout_functor_list_singleton, Cpushout_functor_list_nil], exact respect_id K e}, { rewrite [+Cpushout_functor_list_pair], exact naturality (to_hom η) h}, { rewrite [+Cpushout_functor_list_pair], exact (naturality (to_inv η) h)⁻¹} end definition Cpushout_functor_hom [unfold 12] (f : x ⟶ x') : Cpushout_functor_ob x ⟶ Cpushout_functor_ob x' := begin induction f with l l l' q, { exact Cpushout_functor_list l}, { esimp at *, induction q with q, refine realize_eq _ _ _ q, { intros, apply assoc}, { intros, apply id_left}, intro a₁ a₂ l₁ l₁ q, exact Cpushout_functor_list_rel q} end definition Cpushout_functor [constructor] : Cpushout ⇒ X := begin fapply functor.mk, { exact Cpushout_functor_ob}, { exact Cpushout_functor_hom}, { intro x, reflexivity}, { intro x₁ x₂ x₃ g f, induction g using set_quotient.rec_prop with l₂, induction f using set_quotient.rec_prop with l₁, exact Cpushout_functor_list_append l₂ l₁} end definition Cpushout_functor_inl [constructor] : Cpushout_functor ∘f Cpushout_inl ≅ H := begin fapply natural_iso.mk, { fapply nat_trans.mk, { intro d, exact id}, { intro d d' f, rewrite [▸*, Cpushout_functor_list_singleton], apply comp_id_eq_id_comp}}, esimp, exact _ end definition Cpushout_functor_inr [constructor] : Cpushout_functor ∘f Cpushout_inr ≅ K := begin fapply natural_iso.mk, { fapply nat_trans.mk, { intro d, exact id}, { intro d d' f, rewrite [▸*, Cpushout_functor_list_singleton], apply comp_id_eq_id_comp}}, esimp, exact _ end definition Cpushout_functor_coh (c : C) : natural_map (to_hom Cpushout_functor_inr) (G c) ∘ Cpushout_functor (natural_map (to_hom Cpushout_coh) c) ∘ natural_map (to_inv Cpushout_functor_inl) (F c) = natural_map (to_hom η) c := !id_leftright ⬝ !Cpushout_functor_list_singleton definition Cpushout_functor_unique_ob [unfold 13] (L : Cpushout ⇒ X) (η₁ : L ∘f Cpushout_inl ≅ H) (η₂ : L ∘f Cpushout_inr ≅ K) (x : Cpushout) : L x ⟶ Cpushout_functor x := begin induction x with d e, { exact natural_map (to_hom η₁) d}, { exact natural_map (to_hom η₂) e} end definition Cpushout_functor_unique_inv_ob [unfold 13] (L : Cpushout ⇒ X) (η₁ : L ∘f Cpushout_inl ≅ H) (η₂ : L ∘f Cpushout_inr ≅ K) (x : Cpushout) : Cpushout_functor x ⟶ L x := begin induction x with d e, { exact natural_map (to_inv η₁) d}, { exact natural_map (to_inv η₂) e} end definition Cpushout_functor_unique_nat_singleton (L : Cpushout ⇒ X) (η₁ : L ∘f Cpushout_inl ≅ H) (η₂ : L ∘f Cpushout_inr ≅ K) (p : Πs, natural_map (to_hom η₂) (to_fun_ob G s) ∘ to_fun_hom L (natural_map (to_hom Cpushout_coh) s) ∘ natural_map (to_inv η₁) (to_fun_ob F s) = natural_map (to_hom η) s) (r : R x x') : Cpushout_functor_reduction_rule r ∘ Cpushout_functor_unique_ob L η₁ η₂ x = Cpushout_functor_unique_ob L η₁ η₂ x' ∘ L (class_of [r]) := begin induction r, { exact naturality (to_hom η₁) f}, { exact naturality (to_hom η₂) g}, { refine ap (λx, x ∘ _) (p s)⁻¹ ⬝ _, refine !assoc' ⬝ _, apply ap (λx, _ ∘ x), refine !assoc' ⬝ _ ⬝ !id_right, apply ap (λx, _ ∘ x), exact ap010 natural_map (to_left_inverse η₁) (F s)}, { apply comp.cancel_left (to_hom (componentwise_iso η s)), refine !assoc ⬝ _ ⬝ ap (λx, x ∘ _) (p s), refine ap (λx, x ∘ _) (ap010 natural_map (to_right_inverse η) s) ⬝ _ ⬝ !assoc, refine !id_left ⬝ !id_right⁻¹ ⬝ _, apply ap (λx, _ ∘ x), refine _ ⬝ ap (λx, _ ∘ x) (ap (λx, x ∘ _) _⁻¹ ⬝ !assoc') ⬝ !assoc, rotate 2, exact ap010 natural_map (to_left_inverse η₁) (F s), refine _⁻¹ ⬝ ap (λx, _ ∘ x) !id_left⁻¹, refine (respect_comp L _ _)⁻¹ ⬝ _ ⬝ respect_id L _, apply ap (to_fun_hom L), refine eq_of_rel (tr (paths_rel_of_Q _)), apply EDE}, end definition Cpushout_functor_unique [constructor] (L : Cpushout ⇒ X) (η₁ : L ∘f Cpushout_inl ≅ H) (η₂ : L ∘f Cpushout_inr ≅ K) (p : Πs, natural_map (to_hom η₂) (to_fun_ob G s) ∘ to_fun_hom L (natural_map (to_hom Cpushout_coh) s) ∘ natural_map (to_inv η₁) (to_fun_ob F s) = natural_map (to_hom η) s) : L ≅ Cpushout_functor := begin fapply natural_iso.MK, { exact Cpushout_functor_unique_ob L η₁ η₂}, { intro x x' f, induction f using set_quotient.rec_prop with l, esimp, induction l with x x₁ x₂ x₃ r l IH, { refine !id_left ⬝ !id_right⁻¹ ⬝ _⁻¹, apply ap (λx, _ ∘ x), apply respect_id}, { rewrite [Cpushout_functor_list_cons, assoc', ▸*, IH, assoc, ▸*, Cpushout_functor_unique_nat_singleton L η₁ η₂ p r, ▸*, assoc', -respect_comp L]}}, { exact Cpushout_functor_unique_inv_ob L η₁ η₂}, { intro x, induction x with d e, { exact ap010 natural_map (to_left_inverse η₁) d}, { exact ap010 natural_map (to_left_inverse η₂) e}}, { intro x, induction x with d e, { exact ap010 natural_map (to_right_inverse η₁) d}, { exact ap010 natural_map (to_right_inverse η₂) e}}, end end open bpushout_prehom_index prod prod.ops is_equiv equiv definition Cpushout_universal {C D E : Precategory} {X : Category} (F : C ⇒ D) (G : C ⇒ E) (H : D ⇒ X) (K : E ⇒ X) (η : H ∘f F ≅ K ∘f G) : is_contr (Σ(L : Cpushout F G ⇒ X) (θ : L ∘f Cpushout_inl F G ≅ H × L ∘f Cpushout_inr F G ≅ K), Πs, natural_map (to_hom θ.2) (to_fun_ob G s) ∘ to_fun_hom L (class_of [DE (λ c, c) F G s]) ∘ natural_map (to_inv θ.1) (to_fun_ob F s) = natural_map (to_hom η) s) := begin fapply is_contr.mk, { exact ⟨Cpushout_functor η, (Cpushout_functor_inl η, Cpushout_functor_inr η), Cpushout_functor_coh η⟩}, intro v₁, induction v₁ with L v₂, induction v₂ with θ p, induction θ with θ₁ θ₂, fapply sigma_eq, { esimp, apply eq_of_iso, symmetry, exact Cpushout_functor_unique η L θ₁ θ₂ p}, fapply sigma_pathover, { apply prod_pathover: esimp, { apply iso_pathover, apply hom_pathover_functor_left_constant_right (precomposition_functor _ _), apply nat_trans_eq, intro d, xrewrite [↑[hom_of_eq], to_right_inv !eq_equiv_iso, ▸*], exact (ap010 natural_map (to_right_inverse θ₁) d)⁻¹}, { apply iso_pathover, apply hom_pathover_functor_left_constant_right (precomposition_functor _ _), apply nat_trans_eq, intro e, xrewrite [↑[hom_of_eq], to_right_inv !eq_equiv_iso, ▸*], exact (ap010 natural_map (to_right_inverse θ₂) e)⁻¹}}, apply is_prop.elimo end local attribute prod.eq_pr1 prod.eq_pr2 [reducible] definition Cpushout_equiv {C D E : Precategory} {X : Category} (F : C ⇒ D) (G : C ⇒ E) : (Cpushout F G ⇒ X) ≃ Σ(H : (D ⇒ X) × (E ⇒ X)), H.1 ∘f F ≅ H.2 ∘f G := begin fapply equiv.MK, { intro K, refine ⟨(K ∘f Cpushout_inl F G, K ∘f Cpushout_inr F G), _⟩, exact !assoc_iso⁻¹ⁱ ⬝i (K ∘fi Cpushout_coh F G) ⬝i !assoc_iso}, { intro v, cases v with w η, cases w with K L, exact Cpushout_functor η}, { exact abstract begin intro v, cases v with w η, cases w with K L, esimp at *, fapply sigma_eq, { fapply prod_eq: esimp; apply eq_of_iso, { exact Cpushout_functor_inl η}, { exact Cpushout_functor_inr η}}, esimp, apply iso_pathover, apply hom_pathover, rewrite [-ap_compose' _ pr₁, -ap_compose' _ pr₂, prod_eq_pr1, prod_eq_pr2], rewrite [-+respect_hom_of_eq (precomposition_functor _ _), +hom_of_eq_eq_of_iso], apply nat_trans_eq, intro c, esimp [category.to_precategory], rewrite [+id_left, +id_right, Cpushout_functor_list_singleton] end end}, { exact abstract begin intro K, esimp, refine eq_base_of_is_prop_sigma _ !is_trunc_succ _ _, rotate 1, { refine Cpushout_universal F G (K ∘f Cpushout_inl F G) (K ∘f Cpushout_inr F G) _, exact !assoc_iso⁻¹ⁱ ⬝i (K ∘fi Cpushout_coh F G) ⬝i !assoc_iso}, { esimp, fconstructor, esimp, split, { fapply natural_iso.mk', { intro c, reflexivity}, { intro c c' f, rewrite [▸*, id_right, Cpushout_functor_list_singleton, id_left]}}, { fapply natural_iso.mk', { intro c, reflexivity}, { intro c c' f, rewrite [▸*, id_right, Cpushout_functor_list_singleton, id_left]}}, intro c, rewrite [▸*, id_left, id_right, Cpushout_functor_list_singleton]}, { esimp, fconstructor, { split: reflexivity}, intro c, reflexivity} end end} end /- Pushout of groupoids with a type of basepoints -/ section variables {S : Type} {C D E : Groupoid} (k : S → C) (F : C ⇒ D) (G : C ⇒ E) variables ⦃x x' x₁ x₂ x₃ x₄ : Precategory_bpushout k F G⦄ open bpushout_prehom_index paths.paths_rel bpushout_hom_rel_index definition bpushout_index_inv [unfold 8] (i : bpushout_prehom_index k F G x x') : bpushout_prehom_index k F G x' x := begin induction i, { exact iD k F G f⁻¹}, { exact iE k F G g⁻¹}, { exact ED k F G s}, { exact DE k F G s}, end theorem bpushout_index_reverse {l l' : bpushout_prehom k F G x x'} (q : bpushout_hom_rel_index k F G l l') : paths_rel (bpushout_hom_rel_index k F G) (reverse (bpushout_index_inv k F G) l) (reverse (bpushout_index_inv k F G) l') := begin induction q: apply paths_rel_of_Q; try rewrite reverse_singleton; rewrite *reverse_pair; try rewrite reverse_nil; esimp; try rewrite [comp_inverse]; try rewrite [id_inverse]; rewrite [-*respect_inv]; constructor end theorem bpushout_index_li (i : bpushout_prehom_index k F G x x') : paths_rel (bpushout_hom_rel_index k F G) [bpushout_index_inv k F G i, i] nil := begin induction i: esimp, { refine rtrans (paths_rel_of_Q !DD) _, rewrite [comp.left_inverse], exact paths_rel_of_Q !idD}, { refine rtrans (paths_rel_of_Q !EE) _, rewrite [comp.left_inverse], exact paths_rel_of_Q !idE}, { exact paths_rel_of_Q !DED}, { exact paths_rel_of_Q !EDE} end theorem bpushout_index_ri (i : bpushout_prehom_index k F G x x') : paths_rel (bpushout_hom_rel_index k F G) [i, bpushout_index_inv k F G i] nil := begin induction i: esimp, { refine rtrans (paths_rel_of_Q !DD) _, rewrite [comp.right_inverse], exact paths_rel_of_Q !idD}, { refine rtrans (paths_rel_of_Q !EE) _, rewrite [comp.right_inverse], exact paths_rel_of_Q !idE}, { exact paths_rel_of_Q !EDE}, { exact paths_rel_of_Q !DED} end definition Groupoid_bpushout [constructor] : Groupoid := Groupoid_paths (bpushout_hom_rel_index k F G) (bpushout_index_inv k F G) (bpushout_index_reverse k F G) (bpushout_index_li k F G) (bpushout_index_ri k F G) definition Gpushout [constructor] : Groupoid := Groupoid_bpushout (λc, c) F G end end category
11cf3adfbab0c05992da998fe3816386f031a2bc
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/interactive/my_tac_class.lean
06cab4e2b2f0936a361351d2fd16a10523f26eb2
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,871
lean
meta def mytac := state_t nat tactic section local attribute [reducible] mytac meta instance : monad mytac := by apply_instance meta instance : monad_state nat mytac := by apply_instance meta instance : has_monad_lift tactic mytac := by apply_instance end meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def istep {α : Type} (line0 col0 line col : nat) (t : mytac α) : mytac unit := ⟨λ v s, result.cases_on (@scope_trace _ line col (λ_, t.run v s)) (λ ⟨a, v⟩ new_s, result.success ((), v) new_s) (λ opt_msg_thunk e new_s, match opt_msg_thunk with | some msg_thunk := let msg := λ _ : unit, msg_thunk () ++ format.line ++ to_fmt "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end)⟩ meta instance : interactive.executor mytac := { config_type := unit, execute_with := λ _ tac, tac.run 0 >> return () } meta def save_info (p : pos) : mytac unit := do v ← get, s ← tactic.read, tactic.save_info_thunk p (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor >> return () meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption meta def inc : mytac punit := modify (+1) end interactive end mytac example (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, inc, trace "test", constructor, inc, assumption, --^ "command": "info" assumption end
5c0ad09fd7676ff5a605539dd99f5abfbe0707e2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/focus_tac.lean
4126af8a161d4f0973e5aaf56cb379c70911348c
[ "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
669
lean
open tactic example (a : nat) : a = a := by do define `x (expr.const `nat []), trace "---- after assert ----", trace_state, solve1 (do trace "--- inside focus tac ---", trace_state), -- SHOULD FAIL HERE trace "---- after focus tac ----", trace_state, x ← get_local `x, mk_app `eq.refl [x] >>= exact, return () definition tst2 (a : nat) : a = a := by do define `x (expr.const `nat []), trace "---- after assert ----", trace_state, solve1 (do trace "--- inside focus tac ---", trace_state, assumption), trace "---- after focus tac ----", trace_state, x ← get_local `x, mk_app `eq.refl [x] >>= exact, return ()
4d021a600911f9ff248844a81eaba97169a285dc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sum/basic_auto.lean
33724cdcd965123fd0fa7d00a89f3f78ad1f08f0
[]
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
674
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad The sum type, aka disjoint union. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic universes u v namespace Mathlib infixr:30 " ⊕ " => Mathlib.sum protected instance sum.inhabited_left {α : Type u} {β : Type v} [h : Inhabited α] : Inhabited (α ⊕ β) := { default := sum.inl Inhabited.default } protected instance sum.inhabited_right {α : Type u} {β : Type v} [h : Inhabited β] : Inhabited (α ⊕ β) := { default := sum.inr Inhabited.default } end Mathlib
5486c0adafcba52455dcb053bbe7285648bd12e0
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0218.lean
12839645077eb273b2796a36821a41a00b35a114
[]
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
63
lean
example : 2 + 3 = 5 := begin generalize : 3 = x, sorry end
141b91643a8a79557c32371638da8f84de0f44df
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebra/linear_ordered_comm_group_with_zero.lean
5a5a0cbdaf6de3f3597468692bb252dc8ff721bd
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,967
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import algebra.ordered_group import algebra.group_with_zero import algebra.group_with_zero.power import tactic.abel /-! # Linearly ordered commutative groups and monoids with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. Note that to avoid issues with import cycles, `linear_ordered_comm_monoid_with_zero` is defined in another file. However, the lemmas about it are stated here. -/ set_option old_structure_cmd true /-- A linearly ordered commutative group with a zero element. -/ class linear_ordered_comm_group_with_zero (α : Type*) extends linear_ordered_comm_monoid_with_zero α, comm_group_with_zero α variables {α : Type*} variables {a b c d x y z : α} instance [linear_ordered_add_comm_monoid_with_top α] : linear_ordered_comm_monoid_with_zero (multiplicative (order_dual α)) := { zero := multiplicative.of_add (⊤ : α), zero_mul := top_add, mul_zero := add_top, zero_le_one := (le_top : (0 : α) ≤ ⊤), ..multiplicative.ordered_comm_monoid, ..multiplicative.linear_order } section linear_ordered_comm_monoid variables [linear_ordered_comm_monoid_with_zero α] /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ /-- Pullback a `linear_ordered_comm_monoid_with_zero` under an injective map. -/ def function.injective.linear_ordered_comm_monoid_with_zero {β : Type*} [has_zero β] [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_comm_monoid_with_zero β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, linear_ordered_comm_monoid_with_zero.zero_le_one], ..linear_order.lift f hf, ..hf.ordered_comm_monoid f one mul, ..hf.comm_monoid_with_zero f zero one mul } lemma one_le_pow_of_one_le' {n : ℕ} (H : 1 ≤ x) : 1 ≤ x^n := begin induction n with n ih, { rw pow_zero }, { rw pow_succ, exact one_le_mul H ih } end lemma pow_le_one_of_le_one {n : ℕ} (H : x ≤ 1) : x^n ≤ 1 := begin induction n with n ih, { rw pow_zero }, { rw pow_succ, exact mul_le_one' H ih } end lemma eq_one_of_pow_eq_one {n : ℕ} (hn : n ≠ 0) (H : x ^ n = 1) : x = 1 := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨n, rfl⟩, clear hn, induction n with n ih, { simpa using H }, { cases le_total x 1 with h, all_goals { have h1 := mul_le_mul_right' h (x ^ (n + 1)), rw pow_succ at H, rw [H, one_mul] at h1 }, { have h2 := pow_le_one_of_le_one h, exact ih (le_antisymm h2 h1) }, { have h2 := one_le_pow_of_one_le' h, exact ih (le_antisymm h1 h2) } } end lemma pow_eq_one_iff {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := ⟨eq_one_of_pow_eq_one hn, by { rintro rfl, exact one_pow _ }⟩ lemma one_le_pow_iff {n : ℕ} (hn : n ≠ 0) : 1 ≤ x^n ↔ 1 ≤ x := begin refine ⟨_, one_le_pow_of_one_le'⟩, contrapose!, intro h, apply lt_of_le_of_ne (pow_le_one_of_le_one (le_of_lt h)), rw [ne.def, pow_eq_one_iff hn], exact ne_of_lt h, end lemma pow_le_one_iff {n : ℕ} (hn : n ≠ 0) : x^n ≤ 1 ↔ x ≤ 1 := begin refine ⟨_, pow_le_one_of_le_one⟩, contrapose!, intro h, apply lt_of_le_of_ne (one_le_pow_of_one_le' (le_of_lt h)), rw [ne.def, eq_comm, pow_eq_one_iff hn], exact ne_of_gt h, end lemma zero_le_one' : (0 : α) ≤ 1 := linear_ordered_comm_monoid_with_zero.zero_le_one @[simp] lemma zero_le' : 0 ≤ a := by simpa only [mul_zero, mul_one] using mul_le_mul_left' (@zero_le_one' α _) a @[simp] lemma not_lt_zero' : ¬a < 0 := not_lt_of_le zero_le' @[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 := ⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_refl _⟩ lemma zero_lt_iff : 0 < a ↔ a ≠ 0 := ⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩ lemma ne_zero_of_lt (h : b < a) : a ≠ 0 := λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h lemma pow_pos_iff [no_zero_divisors α] {n : ℕ} (hn : 0 < n) : 0 < a ^ n ↔ 0 < a := by simp_rw [zero_lt_iff, pow_ne_zero_iff hn] instance : linear_ordered_add_comm_monoid_with_top (additive (order_dual α)) := { top := (0 : α), top_add' := λ a, (zero_mul a : (0 : α) * a = 0), le_top := λ _, zero_le', ..additive.ordered_add_comm_monoid, ..additive.linear_order } end linear_ordered_comm_monoid variables [linear_ordered_comm_group_with_zero α] lemma zero_lt_one'' : (0 : α) < 1 := lt_of_le_of_ne zero_le_one' zero_ne_one lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := by simpa only [mul_inv_cancel_right' h] using (mul_le_mul_right' hab c⁻¹) lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ := le_of_le_mul_right h (by simpa [h] using hab) lemma mul_inv_le_of_le_mul (h : c ≠ 0) (hab : a ≤ b * c) : a * c⁻¹ ≤ b := le_of_le_mul_right h (by simpa [h] using hab) lemma div_le_div' (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin by_cases ha : a = 0, { simp [ha] }, by_cases hc : c = 0, { simp [inv_ne_zero hb, hc, hd], }, exact @div_le_div_iff' _ _ (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd) end @[simp] lemma units.zero_lt (u : units α) : (0 : α) < u := zero_lt_iff.2 $ u.ne_zero lemma mul_lt_mul'''' (hab : a < b) (hcd : c < d) : a * c < b * d := have hb : b ≠ 0 := ne_zero_of_lt hab, have hd : d ≠ 0 := ne_zero_of_lt hcd, if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else @mul_lt_mul''' _ _ (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd) hab hcd lemma mul_inv_lt_of_lt_mul' (h : x < y * z) : x * z⁻¹ < y := have hz : z ≠ 0 := (mul_ne_zero_iff.1 $ ne_zero_of_lt h).2, by { contrapose! h, simpa only [inv_inv'] using mul_inv_le_of_le_mul (inv_ne_zero hz) h } lemma mul_lt_right' (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := by { contrapose! h, exact le_of_le_mul_right hc h } lemma pow_lt_pow_succ {x : α} {n : ℕ} (hx : 1 < x) : x ^ n < x ^ n.succ := by { rw [← one_mul (x ^ n), pow_succ], exact mul_lt_right' _ hx (pow_ne_zero _ $ ne_of_gt (lt_trans zero_lt_one'' hx)) } lemma pow_lt_pow' {x : α} {m n : ℕ} (hx : 1 < x) (hmn : m < n) : x ^ m < x ^ n := by { induction hmn with n hmn ih, exacts [pow_lt_pow_succ hx, lt_trans ih (pow_lt_pow_succ hx)] } lemma inv_lt_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a := @inv_lt_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb) lemma inv_le_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := @inv_le_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb) namespace monoid_hom variables {R : Type*} [ring R] (f : R →* α) theorem map_neg_one : f (-1) = 1 := begin apply eq_one_of_pow_eq_one (nat.succ_ne_zero 1) (_ : _ ^ 2 = _), rw [sq, ← f.map_mul, neg_one_mul, neg_neg, f.map_one], end @[simp] lemma map_neg (x : R) : f (-x) = f x := calc f (-x) = f (-1 * x) : by rw [neg_one_mul] ... = f (-1) * f x : map_mul _ _ _ ... = f x : by rw [f.map_neg_one, one_mul] lemma map_sub_swap (x y : R) : f (x - y) = f (y - x) := calc f (x - y) = f (-(y - x)) : by rw show x - y = -(y-x), by abel ... = _ : map_neg _ _ end monoid_hom
6e00977414f1e0f472ec47133d4fc6fdd11e0b1d
87fd6b43d22688237c02b87c30d2a524f53bab24
/src/game/sets/sets_level08.lean
919d42213b9bd3a59aa2c97aacce0efc8d2323d6
[ "Apache-2.0" ]
permissive
grthomson/real-number-game
66142fedf0987db90f66daed52f9c8b42b70f909
8ddc15fdddc241c246653f7bb341df36e4e880a8
refs/heads/master
1,668,059,330,605
1,592,873,454,000
1,592,873,454,000
262,025,764
0
0
null
1,588,849,107,000
1,588,849,106,000
null
UTF-8
Lean
false
false
939
lean
import kb_real_defs --hide /- # Chapter 1 : Sets ## Level 8 -/ /- This is a very basic example of working with intervals of real numbers in Lean. An interval that is closed at both endpoints $a$ and $b$ can be constructed using `set.Icc a b`. For an open-closed interval, the notation is `set.Ioc a b`, etc. The usual closed-interval notation, using square brackets, is used here as a wrapper around these definitions. After `intro hx,` the `split` tactic will showcase the conditions for membership. The inequality goals can be met with the `linarith` tactic. The latter is very useful when dealing with goals that don't involve any nonlinearity in the involved variables, in particular with inequalities. -/ notation `[` a `,` b `]` := set.Icc a b /- Lemma If $x = 2$ then $x ∈ [0,5]$ -/ lemma in_closed_interval (x:ℝ) : x = 2 → x ∈ [(0:ℝ), 5] := begin intro hx, rw mem_Icc_iff, split; linarith end
9f25e517b4dbd2fdea9cf0f3aa777a429effebaa
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/fermat4.lean
9c08682b373559f67daa7fe38b197e2a995a8e3a
[ "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
12,332
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul van Wamelen -/ import number_theory.pythagorean_triples import ring_theory.coprime.lemmas /-! # Fermat's Last Theorem for the case n = 4 There are no non-zero integers `a`, `b` and `c` such that `a ^ 4 + b ^ 4 = c ^ 4`. -/ noncomputable theory open_locale classical /-- Shorthand for three non-zero integers `a`, `b`, and `c` satisfying `a ^ 4 + b ^ 4 = c ^ 2`. We will show that no integers satisfy this equation. Clearly Fermat's Last theorem for n = 4 follows. -/ def fermat_42 (a b c : ℤ) : Prop := a ≠ 0 ∧ b ≠ 0 ∧ a ^ 4 + b ^ 4 = c ^ 2 namespace fermat_42 lemma comm {a b c : ℤ} : (fermat_42 a b c) ↔ (fermat_42 b a c) := by { delta fermat_42, rw add_comm, tauto } lemma mul {a b c k : ℤ} (hk0 : k ≠ 0) : fermat_42 a b c ↔ fermat_42 (k * a) (k * b) (k ^ 2 * c) := begin delta fermat_42, split, { intro f42, split, { exact mul_ne_zero hk0 f42.1 }, split, { exact mul_ne_zero hk0 f42.2.1 }, { calc (k * a) ^ 4 + (k * b) ^ 4 = k ^ 4 * (a ^ 4 + b ^ 4) : by ring ... = k ^ 4 * c ^ 2 : by rw f42.2.2 ... = (k ^ 2 * c) ^ 2 : by ring }}, { intro f42, split, { exact right_ne_zero_of_mul f42.1 }, split, { exact right_ne_zero_of_mul f42.2.1 }, apply (mul_right_inj' (pow_ne_zero 4 hk0)).mp, { calc k ^ 4 * (a ^ 4 + b ^ 4) = (k * a) ^ 4 + (k * b) ^ 4 : by ring ... = (k ^ 2 * c) ^ 2 : by rw f42.2.2 ... = k ^ 4 * c ^ 2 : by ring }} end lemma ne_zero {a b c : ℤ} (h : fermat_42 a b c) : c ≠ 0 := begin apply ne_zero_pow (dec_trivial : 2 ≠ 0), apply ne_of_gt, rw [← h.2.2, (by ring : a ^ 4 + b ^ 4 = (a ^ 2) ^ 2 + (b ^ 2) ^ 2)], exact add_pos (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.1)) (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.2.1)) end /-- We say a solution to `a ^ 4 + b ^ 4 = c ^ 2` is minimal if there is no other solution with a smaller `c` (in absolute value). -/ def minimal (a b c : ℤ) : Prop := (fermat_42 a b c) ∧ ∀ (a1 b1 c1 : ℤ), (fermat_42 a1 b1 c1) → int.nat_abs c ≤ int.nat_abs c1 /-- if we have a solution to `a ^ 4 + b ^ 4 = c ^ 2` then there must be a minimal one. -/ lemma exists_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) := begin let S : set ℕ := { n | ∃ (s : ℤ × ℤ × ℤ), fermat_42 s.1 s.2.1 s.2.2 ∧ n = int.nat_abs s.2.2}, have S_nonempty : S.nonempty, { use int.nat_abs c, rw set.mem_set_of_eq, use ⟨a, ⟨b, c⟩⟩, tauto }, let m : ℕ := nat.find S_nonempty, have m_mem : m ∈ S := nat.find_spec S_nonempty, rcases m_mem with ⟨s0, hs0, hs1⟩, use [s0.1, s0.2.1, s0.2.2, hs0], intros a1 b1 c1 h1, rw ← hs1, apply nat.find_min', use ⟨a1, ⟨b1, c1⟩⟩, tauto end /-- a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` must have `a` and `b` coprime. -/ lemma coprime_of_minimal {a b c : ℤ} (h : minimal a b c) : is_coprime a b := begin apply int.gcd_eq_one_iff_coprime.mp, by_contradiction hab, obtain ⟨p, hp, hpa, hpb⟩ := nat.prime.not_coprime_iff_dvd.mp hab, obtain ⟨a1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpa), obtain ⟨b1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpb), have hpc : (p : ℤ) ^ 2 ∣ c, { apply (int.pow_dvd_pow_iff (dec_trivial : 0 < 2)).mp, rw ← h.1.2.2, apply dvd.intro (a1 ^ 4 + b1 ^ 4), ring }, obtain ⟨c1, rfl⟩ := hpc, have hf : fermat_42 a1 b1 c1, exact (fermat_42.mul (int.coe_nat_ne_zero.mpr (nat.prime.ne_zero hp))).mpr h.1, apply nat.le_lt_antisymm (h.2 _ _ _ hf), rw [int.nat_abs_mul, lt_mul_iff_one_lt_left, int.nat_abs_pow, int.nat_abs_of_nat], { exact nat.one_lt_pow _ _ (show 0 < 2, from dec_trivial) (nat.prime.one_lt hp) }, { exact (nat.pos_of_ne_zero (int.nat_abs_ne_zero_of_ne_zero (ne_zero hf))) }, end /-- We can swap `a` and `b` in a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2`. -/ lemma minimal_comm {a b c : ℤ} : (minimal a b c) → (minimal b a c) := λ ⟨h1, h2⟩, ⟨fermat_42.comm.mp h1, h2⟩ /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has positive `c`. -/ lemma neg_of_minimal {a b c : ℤ} : (minimal a b c) → (minimal a b (-c)) := begin rintros ⟨⟨ha, hb, heq⟩, h2⟩, split, { apply and.intro ha (and.intro hb _), rw heq, exact (neg_sq c).symm }, rwa (int.nat_abs_neg c), end /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd. -/ lemma exists_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 := begin obtain ⟨a0, b0, c0, hf⟩ := exists_minimal h, cases int.mod_two_eq_zero_or_one a0 with hap hap, { cases int.mod_two_eq_zero_or_one b0 with hbp hbp, { exfalso, have h1 : 2 ∣ (int.gcd a0 b0 : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hap) (int.dvd_of_mod_eq_zero hbp) }, rw int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal hf) at h1, revert h1, norm_num }, { exact ⟨b0, ⟨a0, ⟨c0, minimal_comm hf, hbp⟩⟩⟩ } }, exact ⟨a0, ⟨b0, ⟨c0 , hf, hap⟩⟩⟩, end /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd and `c` positive. -/ lemma exists_pos_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 ∧ 0 < c0 := begin obtain ⟨a0, b0, c0, hf, hc⟩ := exists_odd_minimal h, rcases lt_trichotomy 0 c0 with (h1 | rfl | h1), { use [a0, b0, c0], tauto }, { exfalso, exact ne_zero hf.1 rfl}, { use [a0, b0, -c0, neg_of_minimal hf, hc], exact neg_pos.mpr h1 }, end end fermat_42 lemma int.coprime_of_sq_sum {r s : ℤ} (h2 : is_coprime s r) : is_coprime (r ^ 2 + s ^ 2) r := begin rw [sq, sq], exact (is_coprime.mul_left h2 h2).mul_add_left_left r end lemma int.coprime_of_sq_sum' {r s : ℤ} (h : is_coprime r s) : is_coprime (r ^ 2 + s ^ 2) (r * s) := begin apply is_coprime.mul_right (int.coprime_of_sq_sum (is_coprime_comm.mp h)), rw add_comm, apply int.coprime_of_sq_sum h end namespace fermat_42 -- If we have a solution to a ^ 4 + b ^ 4 = c ^ 2, we can construct a smaller one. This -- implies there can't be a smallest solution. lemma not_minimal {a b c : ℤ} (h : minimal a b c) (ha2 : a % 2 = 1) (hc : 0 < c) : false := begin -- Use the fact that a ^ 2, b ^ 2, c form a pythagorean triple to obtain m and n such that -- a ^ 2 = m ^ 2 - n ^ 2, b ^ 2 = 2 * m * n and c = m ^ 2 + n ^ 2 -- first the formula: have ht : pythagorean_triple (a ^ 2) (b ^ 2) c, { calc ((a ^ 2) * (a ^ 2)) + ((b ^ 2) * (b ^ 2)) = a ^ 4 + b ^ 4 : by ring ... = c ^ 2 : by rw h.1.2.2 ... = c * c : by rw sq }, -- coprime requirement: have h2 : int.gcd (a ^ 2) (b ^ 2) = 1 := int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal h).pow, -- in order to reduce the possibilities we get from the classification of pythagorean triples -- it helps if we know the parity of a ^ 2 (and the sign of c): have ha22 : a ^ 2 % 2 = 1, { rw [sq, int.mul_mod, ha2], norm_num }, obtain ⟨m, n, ht1, ht2, ht3, ht4, ht5, ht6⟩ := pythagorean_triple.coprime_classification' ht h2 ha22 hc, -- Now a, n, m form a pythagorean triple and so we can obtain r and s such that -- a = r ^ 2 - s ^ 2, n = 2 * r * s and m = r ^ 2 + s ^ 2 -- formula: have htt : pythagorean_triple a n m, { delta pythagorean_triple, rw [← sq, ← sq, ← sq], exact (add_eq_of_eq_sub ht1) }, -- a and n are coprime, because a ^ 2 = m ^ 2 - n ^ 2 and m and n are coprime. have h3 : int.gcd a n = 1, { apply int.gcd_eq_one_iff_coprime.mpr, apply @is_coprime.of_mul_left_left _ _ _ a, rw [← sq, ht1, (by ring : m ^ 2 - n ^ 2 = m ^ 2 + (-n) * n)], exact (int.gcd_eq_one_iff_coprime.mp ht4).pow_left.add_mul_right_left (-n) }, -- m is positive because b is non-zero and b ^ 2 = 2 * m * n and we already have 0 ≤ m. have hb20 : b ^ 2 ≠ 0 := mt pow_eq_zero h.1.2.1, have h4 : 0 < m, { apply lt_of_le_of_ne ht6, rintro rfl, revert hb20, rw ht2, simp }, obtain ⟨r, s, htt1, htt2, htt3, htt4, htt5, htt6⟩ := pythagorean_triple.coprime_classification' htt h3 ha2 h4, -- Now use the fact that (b / 2) ^ 2 = m * r * s, and m, r and s are pairwise coprime to obtain -- i, j and k such that m = i ^ 2, r = j ^ 2 and s = k ^ 2. -- m and r * s are coprime because m = r ^ 2 + s ^ 2 and r and s are coprime. have hcp : int.gcd m (r * s) = 1, { rw htt3, exact int.gcd_eq_one_iff_coprime.mpr (int.coprime_of_sq_sum' (int.gcd_eq_one_iff_coprime.mp htt4)) }, -- b is even because b ^ 2 = 2 * m * n. have hb2 : 2 ∣ b, { apply @int.prime.dvd_pow' _ 2 _ (by norm_num : nat.prime 2), rw [ht2, mul_assoc], exact dvd_mul_right 2 (m * n) }, cases hb2 with b' hb2', have hs : b' ^ 2 = m * (r * s), { apply (mul_right_inj' (by norm_num : (4 : ℤ) ≠ 0)).mp, calc 4 * b' ^ 2 = (2 * b') * (2 * b') : by ring ... = 2 * m * (2 * r * s) : by rw [← hb2', ← sq, ht2, htt2] ... = 4 * (m * (r * s)) : by ring }, have hrsz : r * s ≠ 0, -- because b ^ 2 is not zero and (b / 2) ^ 2 = m * (r * s) { by_contradiction hrsz, revert hb20, rw [ht2, htt2, mul_assoc, @mul_assoc _ _ _ r s, hrsz], simp }, have h2b0 : b' ≠ 0, { apply ne_zero_pow (dec_trivial : 2 ≠ 0), rw hs, apply mul_ne_zero, { exact ne_of_gt h4}, { exact hrsz } }, obtain ⟨i, hi⟩ := int.sq_of_gcd_eq_one hcp hs.symm, -- use m is positive to exclude m = - i ^ 2 have hi' : ¬ m = - i ^ 2, { by_contradiction h1, have hit : - i ^ 2 ≤ 0, apply neg_nonpos.mpr (sq_nonneg i), rw ← h1 at hit, apply absurd h4 (not_lt.mpr hit) }, replace hi : m = i ^ 2, { apply or.resolve_right hi hi' }, rw mul_comm at hs, rw [int.gcd_comm] at hcp, -- obtain d such that r * s = d ^ 2 obtain ⟨d, hd⟩ := int.sq_of_gcd_eq_one hcp hs.symm, -- (b / 2) ^ 2 and m are positive so r * s is positive have hd' : ¬ r * s = - d ^ 2, { by_contradiction h1, rw h1 at hs, have h2 : b' ^ 2 ≤ 0, { rw [hs, (by ring : - d ^ 2 * m = - (d ^ 2 * m))], exact neg_nonpos.mpr ((zero_le_mul_right h4).mpr (sq_nonneg d)) }, have h2' : 0 ≤ b' ^ 2, { apply sq_nonneg b' }, exact absurd (lt_of_le_of_ne h2' (ne.symm (pow_ne_zero _ h2b0))) (not_lt.mpr h2) }, replace hd : r * s = d ^ 2, { apply or.resolve_right hd hd' }, -- r = +/- j ^ 2 obtain ⟨j, hj⟩ := int.sq_of_gcd_eq_one htt4 hd, have hj0 : j ≠ 0, { intro h0, rw [h0, zero_pow (dec_trivial : 0 < 2), neg_zero, or_self] at hj, apply left_ne_zero_of_mul hrsz hj }, rw mul_comm at hd, rw [int.gcd_comm] at htt4, -- s = +/- k ^ 2 obtain ⟨k, hk⟩ := int.sq_of_gcd_eq_one htt4 hd, have hk0 : k ≠ 0, { intro h0, rw [h0, zero_pow (dec_trivial : 0 < 2), neg_zero, or_self] at hk, apply right_ne_zero_of_mul hrsz hk }, have hj2 : r ^ 2 = j ^ 4, { cases hj with hjp hjp; { rw hjp, ring } }, have hk2 : s ^ 2 = k ^ 4, { cases hk with hkp hkp; { rw hkp, ring } }, -- from m = r ^ 2 + s ^ 2 we now get a new solution to a ^ 4 + b ^ 4 = c ^ 2: have hh : i ^ 2 = j ^ 4 + k ^ 4, { rw [← hi, htt3, hj2, hk2] }, have hn : n ≠ 0, { rw ht2 at hb20, apply right_ne_zero_of_mul hb20 }, -- and it has a smaller c: from c = m ^ 2 + n ^ 2 we see that m is smaller than c, and i ^ 2 = m. have hic : int.nat_abs i < int.nat_abs c, { apply int.coe_nat_lt.mp, rw ← (int.eq_nat_abs_of_zero_le (le_of_lt hc)), apply gt_of_gt_of_ge _ (int.abs_le_self_sq i), rw [← hi, ht3], apply gt_of_gt_of_ge _ (int.le_self_sq m), exact lt_add_of_pos_right (m ^ 2) (sq_pos_of_ne_zero n hn) }, have hic' : int.nat_abs c ≤ int.nat_abs i, { apply (h.2 j k i), exact ⟨hj0, hk0, hh.symm⟩ }, apply absurd (not_le_of_lt hic) (not_not.mpr hic') end end fermat_42 lemma not_fermat_42 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : a ^ 4 + b ^ 4 ≠ c ^ 2 := begin intro h, obtain ⟨a0, b0, c0, ⟨hf, h2, hp⟩⟩ := fermat_42.exists_pos_odd_minimal (and.intro ha (and.intro hb h)), apply fermat_42.not_minimal hf h2 hp end theorem not_fermat_4 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : a ^ 4 + b ^ 4 ≠ c ^ 4 := begin intro heq, apply @not_fermat_42 _ _ (c ^ 2) ha hb, rw heq, ring end
43a29168daddfdfd5579a301a941a24bb07f68e4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/denumerable_auto.lean
cc3b135529d9f390e1f732a2f8e9b406d5e867ed
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,703
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Denumerable (countably infinite) types, as a typeclass extending encodable. This is used to provide explicit encode/decode functions from nat, where the functions are known inverses of each other. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.encodable.basic import Mathlib.data.sigma.default import Mathlib.data.fintype.basic import Mathlib.data.list.min_max import Mathlib.PostPort universes u_1 l u_2 u_3 namespace Mathlib /-- A denumerable type is one which is (constructively) bijective with ℕ. Although we already have a name for this property, namely `α ≃ ℕ`, we are here interested in using it as a typeclass. -/ class denumerable (α : Type u_1) extends encodable α where decode_inv : ∀ (n : ℕ), ∃ (a : α), ∃ (H : a ∈ encodable.decode α n), encodable.encode a = n namespace denumerable theorem decode_is_some (α : Type u_1) [denumerable α] (n : ℕ) : ↥(option.is_some (encodable.decode α n)) := iff.mpr option.is_some_iff_exists (Exists.imp (fun (a : α) => Exists.fst) (decode_inv n)) def of_nat (α : Type u_1) [f : denumerable α] (n : ℕ) : α := option.get (decode_is_some α n) @[simp] theorem decode_eq_of_nat (α : Type u_1) [denumerable α] (n : ℕ) : encodable.decode α n = some (of_nat α n) := option.eq_some_of_is_some (decode_is_some α n) @[simp] theorem of_nat_of_decode {α : Type u_1} [denumerable α] {n : ℕ} {b : α} (h : encodable.decode α n = some b) : of_nat α n = b := option.some.inj (Eq.trans (Eq.symm (decode_eq_of_nat α n)) h) @[simp] theorem encode_of_nat {α : Type u_1} [denumerable α] (n : ℕ) : encodable.encode (of_nat α n) = n := sorry @[simp] theorem of_nat_encode {α : Type u_1} [denumerable α] (a : α) : of_nat α (encodable.encode a) = a := of_nat_of_decode (encodable.encodek a) def eqv (α : Type u_1) [denumerable α] : α ≃ ℕ := equiv.mk encodable.encode (of_nat α) of_nat_encode encode_of_nat def mk' {α : Type u_1} (e : α ≃ ℕ) : denumerable α := mk sorry def of_equiv (α : Type u_1) {β : Type u_2} [denumerable α] (e : β ≃ α) : denumerable β := mk sorry @[simp] theorem of_equiv_of_nat (α : Type u_1) {β : Type u_2} [denumerable α] (e : β ≃ α) (n : ℕ) : of_nat β n = coe_fn (equiv.symm e) (of_nat α n) := sorry def equiv₂ (α : Type u_1) (β : Type u_2) [denumerable α] [denumerable β] : α ≃ β := equiv.trans (eqv α) (equiv.symm (eqv β)) protected instance nat : denumerable ℕ := mk sorry @[simp] theorem of_nat_nat (n : ℕ) : of_nat ℕ n = n := rfl protected instance option {α : Type u_1} [denumerable α] : denumerable (Option α) := mk sorry protected instance sum {α : Type u_1} {β : Type u_2} [denumerable α] [denumerable β] : denumerable (α ⊕ β) := mk sorry protected instance sigma {α : Type u_1} [denumerable α] {γ : α → Type u_3} [(a : α) → denumerable (γ a)] : denumerable (sigma γ) := mk sorry @[simp] theorem sigma_of_nat_val {α : Type u_1} [denumerable α] {γ : α → Type u_3} [(a : α) → denumerable (γ a)] (n : ℕ) : of_nat (sigma γ) n = sigma.mk (of_nat α (prod.fst (nat.unpair n))) (of_nat (γ (of_nat α (prod.fst (nat.unpair n)))) (prod.snd (nat.unpair n))) := sorry protected instance prod {α : Type u_1} {β : Type u_2} [denumerable α] [denumerable β] : denumerable (α × β) := of_equiv (sigma fun (_x : α) => β) (equiv.symm (equiv.sigma_equiv_prod α β)) @[simp] theorem prod_of_nat_val {α : Type u_1} {β : Type u_2} [denumerable α] [denumerable β] (n : ℕ) : of_nat (α × β) n = (of_nat α (prod.fst (nat.unpair n)), of_nat β (prod.snd (nat.unpair n))) := sorry @[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = nat.unpair := sorry protected instance int : denumerable ℤ := mk' equiv.int_equiv_nat protected instance pnat : denumerable ℕ+ := mk' equiv.pnat_equiv_nat protected instance ulift {α : Type u_1} [denumerable α] : denumerable (ulift α) := of_equiv α equiv.ulift protected instance plift {α : Type u_1} [denumerable α] : denumerable (plift α) := of_equiv α equiv.plift def pair {α : Type u_1} [denumerable α] : α × α ≃ α := equiv₂ (α × α) α end denumerable namespace nat.subtype theorem exists_succ {s : set ℕ} [infinite ↥s] (x : ↥s) : ∃ (n : ℕ), subtype.val x + n + 1 ∈ s := sorry def succ {s : set ℕ} [infinite ↥s] [decidable_pred s] (x : ↥s) : ↥s := (fun (h : ∃ (m : ℕ), subtype.val x + m + 1 ∈ s) => { val := subtype.val x + nat.find h + 1, property := sorry }) (exists_succ x) theorem succ_le_of_lt {s : set ℕ} [infinite ↥s] [decidable_pred s] {x : ↥s} {y : ↥s} (h : y < x) : succ y ≤ x := sorry theorem le_succ_of_forall_lt_le {s : set ℕ} [infinite ↥s] [decidable_pred s] {x : ↥s} {y : ↥s} (h : ∀ (z : ↥s), z < x → z ≤ y) : x ≤ succ y := sorry theorem lt_succ_self {s : set ℕ} [infinite ↥s] [decidable_pred s] (x : ↥s) : x < succ x := lt_of_le_of_lt (le_add_right (le_refl (subtype.val x))) (lt_succ_self (subtype.val x + nat.find (exists_succ x))) theorem lt_succ_iff_le {s : set ℕ} [infinite ↥s] [decidable_pred s] {x : ↥s} {y : ↥s} : x < succ y ↔ x ≤ y := { mp := fun (h : x < succ y) => le_of_not_gt fun (h' : x > y) => not_le_of_gt h (succ_le_of_lt h'), mpr := fun (h : x ≤ y) => lt_of_le_of_lt h (lt_succ_self y) } def of_nat (s : set ℕ) [decidable_pred s] [infinite ↥s] : ℕ → ↥s := sorry theorem of_nat_surjective_aux {s : set ℕ} [infinite ↥s] [decidable_pred s] {x : ℕ} (hx : x ∈ s) : ∃ (n : ℕ), of_nat s n = { val := x, property := hx } := sorry theorem of_nat_surjective {s : set ℕ} [infinite ↥s] [decidable_pred s] : function.surjective (of_nat s) := sorry def denumerable (s : set ℕ) [decidable_pred s] [infinite ↥s] : denumerable ↥s := denumerable.of_equiv ℕ (equiv.mk to_fun_aux (of_nat s) sorry sorry) end nat.subtype namespace denumerable def of_encodable_of_infinite (α : Type u_1) [encodable α] [infinite α] : denumerable α := let _inst : decidable_pred (set.range encodable.encode) := encodable.decidable_range_encode α; let _inst_3 : infinite ↥(set.range encodable.encode) := sorry; let _inst_4 : denumerable ↥(set.range encodable.encode) := nat.subtype.denumerable (set.range encodable.encode); of_equiv (↥(set.range encodable.encode)) (encodable.equiv_range_encode α) end Mathlib
df2872e5fac1bc8c5e8f35b1143075f6f576d01a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/set/functor.lean
a37798490a6b6334881afe0bee5c4bcd7e52dda3
[ "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
1,481
lean
/- Copyright (c) 2016 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.set.lattice /-! # Functoriality of `set` This file defines the functor structure of `set`. -/ universes u open function namespace set variables {α β : Type u} {s : set α} {f : α → set β} {g : set (α → β)} instance : monad.{u} set := { pure := λ α a, {a}, bind := λ α β s f, ⋃ i ∈ s, f i, seq := λ α β, set.seq, map := λ α β, set.image } @[simp] lemma bind_def : s >>= f = ⋃ i ∈ s, f i := rfl @[simp] lemma fmap_eq_image (f : α → β) : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl instance : is_lawful_monad set := { id_map := λ α, image_id, comp_map := λ α β γ f g s, image_comp _ _ _, pure_bind := λ α β, bUnion_singleton, bind_assoc := λ α β γ s f g, by simp only [bind_def, bUnion_Union], bind_pure_comp_eq_map := λ α β f s, (image_eq_Union _ _).symm, bind_map_eq_seq := λ α β s t, seq_def.symm } instance : is_comm_applicative (set : Type u → Type u) := ⟨ λ α β s t, prod_image_seq_comm s t ⟩ instance : alternative set := { orelse := λ α, (∪), failure := λ α, ∅, .. set.monad } end set
581a0b9347ad5f5c68291cee425fedcb86aaf992
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/group/type_tags.lean
b6dd3e1046c0876330c17b49c4f89d78552ec4a6
[ "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
9,467
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.group.hom import data.equiv.basic /-! # Type tags that turn additive structures into multiplicative, and vice versa We define two type tags: * `additive α`: turns any multiplicative structure on `α` into the corresponding additive structure on `additive α`; * `multiplicative α`: turns any additive structure on `α` into the corresponding multiplicative structure on `multiplicative α`. We also define instances `additive.*` and `multiplicative.*` that actually transfer the structures. -/ universes u v variables {α : Type u} {β : Type v} /-- If `α` carries some multiplicative structure, then `additive α` carries the corresponding additive structure. -/ def additive (α : Type*) := α /-- If `α` carries some additive structure, then `multiplicative α` carries the corresponding multiplicative structure. -/ def multiplicative (α : Type*) := α namespace additive /-- Reinterpret `x : α` as an element of `additive α`. -/ def of_mul : α ≃ additive α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ /-- Reinterpret `x : additive α` as an element of `α`. -/ def to_mul : additive α ≃ α := of_mul.symm @[simp] lemma of_mul_symm_eq : (@of_mul α).symm = to_mul := rfl @[simp] lemma to_mul_symm_eq : (@to_mul α).symm = of_mul := rfl end additive namespace multiplicative /-- Reinterpret `x : α` as an element of `multiplicative α`. -/ def of_add : α ≃ multiplicative α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ /-- Reinterpret `x : multiplicative α` as an element of `α`. -/ def to_add : multiplicative α ≃ α := of_add.symm @[simp] lemma of_add_symm_eq : (@of_add α).symm = to_add := rfl @[simp] lemma to_add_symm_eq : (@to_add α).symm = of_add := rfl end multiplicative @[simp] lemma to_add_of_add (x : α) : (multiplicative.of_add x).to_add = x := rfl @[simp] lemma of_add_to_add (x : multiplicative α) : multiplicative.of_add x.to_add = x := rfl @[simp] lemma to_mul_of_mul (x : α) : (additive.of_mul x).to_mul = x := rfl @[simp] lemma of_mul_to_mul (x : additive α) : additive.of_mul x.to_mul = x := rfl instance [inhabited α] : inhabited (additive α) := ⟨additive.of_mul (default α)⟩ instance [inhabited α] : inhabited (multiplicative α) := ⟨multiplicative.of_add (default α)⟩ instance [nontrivial α] : nontrivial (additive α) := additive.of_mul.injective.nontrivial instance [nontrivial α] : nontrivial (multiplicative α) := multiplicative.of_add.injective.nontrivial instance additive.has_add [has_mul α] : has_add (additive α) := { add := λ x y, additive.of_mul (x.to_mul * y.to_mul) } instance [has_add α] : has_mul (multiplicative α) := { mul := λ x y, multiplicative.of_add (x.to_add + y.to_add) } @[simp] lemma of_add_add [has_add α] (x y : α) : multiplicative.of_add (x + y) = multiplicative.of_add x * multiplicative.of_add y := rfl @[simp] lemma to_add_mul [has_add α] (x y : multiplicative α) : (x * y).to_add = x.to_add + y.to_add := rfl @[simp] lemma of_mul_mul [has_mul α] (x y : α) : additive.of_mul (x * y) = additive.of_mul x + additive.of_mul y := rfl @[simp] lemma to_mul_add [has_mul α] (x y : additive α) : (x + y).to_mul = x.to_mul * y.to_mul := rfl instance [semigroup α] : add_semigroup (additive α) := { add_assoc := @mul_assoc α _, ..additive.has_add } instance [add_semigroup α] : semigroup (multiplicative α) := { mul_assoc := @add_assoc α _, ..multiplicative.has_mul } instance [comm_semigroup α] : add_comm_semigroup (additive α) := { add_comm := @mul_comm _ _, ..additive.add_semigroup } instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) := { mul_comm := @add_comm _ _, ..multiplicative.semigroup } instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) := { add_left_cancel := @mul_left_cancel _ _, ..additive.add_semigroup } instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) := { mul_left_cancel := @add_left_cancel _ _, ..multiplicative.semigroup } instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) := { add_right_cancel := @mul_right_cancel _ _, ..additive.add_semigroup } instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) := { mul_right_cancel := @add_right_cancel _ _, ..multiplicative.semigroup } instance [has_one α] : has_zero (additive α) := ⟨additive.of_mul 1⟩ @[simp] lemma of_mul_one [has_one α] : @additive.of_mul α 1 = 0 := rfl @[simp] lemma to_mul_zero [has_one α] : (0 : additive α).to_mul = 1 := rfl instance [has_zero α] : has_one (multiplicative α) := ⟨multiplicative.of_add 0⟩ @[simp] lemma of_add_zero [has_zero α] : @multiplicative.of_add α 0 = 1 := rfl @[simp] lemma to_add_one [has_zero α] : (1 : multiplicative α).to_add = 0 := rfl instance [monoid α] : add_monoid (additive α) := { zero := 0, zero_add := @one_mul _ _, add_zero := @mul_one _ _, ..additive.add_semigroup } instance [add_monoid α] : monoid (multiplicative α) := { one := 1, one_mul := @zero_add _ _, mul_one := @add_zero _ _, ..multiplicative.semigroup } instance [comm_monoid α] : add_comm_monoid (additive α) := { .. additive.add_monoid, .. additive.add_comm_semigroup } instance [add_comm_monoid α] : comm_monoid (multiplicative α) := { ..multiplicative.monoid, .. multiplicative.comm_semigroup } instance [has_inv α] : has_neg (additive α) := ⟨λ x, multiplicative.of_add x.to_mul⁻¹⟩ @[simp] lemma of_mul_inv [has_inv α] (x : α) : additive.of_mul x⁻¹ = -(additive.of_mul x) := rfl @[simp] lemma to_mul_neg [has_inv α] (x : additive α) : (-x).to_mul = x.to_mul⁻¹ := rfl instance [has_neg α] : has_inv (multiplicative α) := ⟨λ x, additive.of_mul (-x.to_add)⟩ @[simp] lemma of_add_neg [has_neg α] (x : α) : multiplicative.of_add (-x) = (multiplicative.of_add x)⁻¹ := rfl @[simp] lemma to_add_inv [has_neg α] (x : multiplicative α) : (x⁻¹).to_add = -x.to_add := rfl instance additive.has_sub [has_div α] : has_sub (additive α) := { sub := λ x y, additive.of_mul (x.to_mul / y.to_mul) } instance multiplicative.has_div [has_sub α] : has_div (multiplicative α) := { div := λ x y, multiplicative.of_add (x.to_add - y.to_add) } @[simp] lemma of_add_sub [has_sub α] (x y : α) : multiplicative.of_add (x - y) = multiplicative.of_add x / multiplicative.of_add y := rfl @[simp] lemma to_add_div [has_sub α] (x y : multiplicative α) : (x / y).to_add = x.to_add - y.to_add := rfl @[simp] lemma of_mul_div [has_div α] (x y : α) : additive.of_mul (x / y) = additive.of_mul x - additive.of_mul y := rfl @[simp] lemma to_mul_sub [has_div α] (x y : additive α) : (x - y).to_mul = x.to_mul / y.to_mul := rfl instance [div_inv_monoid α] : sub_neg_monoid (additive α) := { sub_eq_add_neg := @div_eq_mul_inv α _, .. additive.has_neg, .. additive.has_sub, .. additive.add_monoid } instance [sub_neg_monoid α] : div_inv_monoid (multiplicative α) := { div_eq_mul_inv := @sub_eq_add_neg α _, .. multiplicative.has_inv, .. multiplicative.has_div, .. multiplicative.monoid } instance [group α] : add_group (additive α) := { add_left_neg := @mul_left_inv α _, .. additive.sub_neg_monoid } instance [add_group α] : group (multiplicative α) := { mul_left_inv := @add_left_neg α _, .. multiplicative.div_inv_monoid } instance [comm_group α] : add_comm_group (additive α) := { .. additive.add_group, .. additive.add_comm_monoid } instance [add_comm_group α] : comm_group (multiplicative α) := { .. multiplicative.group, .. multiplicative.comm_monoid } /-- Reinterpret `α →+ β` as `multiplicative α →* multiplicative β`. -/ def add_monoid_hom.to_multiplicative [add_monoid α] [add_monoid β] : (α →+ β) ≃ (multiplicative α →* multiplicative β) := ⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩ /-- Reinterpret `α →* β` as `additive α →+ additive β`. -/ def monoid_hom.to_additive [monoid α] [monoid β] : (α →* β) ≃ (additive α →+ additive β) := ⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩ /-- Reinterpret `additive α →+ β` as `α →* multiplicative β`. -/ def add_monoid_hom.to_multiplicative' [monoid α] [add_monoid β] : (additive α →+ β) ≃ (α →* multiplicative β) := ⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩ /-- Reinterpret `α →* multiplicative β` as `additive α →+ β`. -/ def monoid_hom.to_additive' [monoid α] [add_monoid β] : (α →* multiplicative β) ≃ (additive α →+ β) := add_monoid_hom.to_multiplicative'.symm /-- Reinterpret `α →+ additive β` as `multiplicative α →* β`. -/ def add_monoid_hom.to_multiplicative'' [add_monoid α] [monoid β] : (α →+ additive β) ≃ (multiplicative α →* β) := ⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩ /-- Reinterpret `multiplicative α →* β` as `α →+ additive β`. -/ def monoid_hom.to_additive'' [add_monoid α] [monoid β] : (multiplicative α →* β) ≃ (α →+ additive β) := add_monoid_hom.to_multiplicative''.symm
49f890956a0af46c51021d734f31b26de08193ec
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/noetherian.lean
1e7d4889acc6bd2c51e7fa9d54404ae8e7723b63
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
23,233
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal.operations import linear_algebra.basis import order.order_iso_nat /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply rel_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_noetherian_ring variables {R : Type*} [integral_domain R] [is_noetherian_ring R] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : R, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set R)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : R} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : R → Prop} (a : R) (h0 : P 0) (hu : ∀ u : R, is_unit u → P u) (hi : ∀ a i : R, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : R) : a ≠ 0 → ∃f : multiset R, (∀b ∈ f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
faba7ef7c41ca7e1d3081b38a9250e62c15e42a0
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world08/level06.lean
4ee822295d6ad993e1837ac54166463d706e83d6
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
137
lean
theorem add_left_cancel (t a b : mynat) : t + a = t + b → a = b := begin rw add_comm, rw add_comm t, exact add_right_cancel a t b, end
9490b7641b18830145bbb20a6696d90499dfe6e3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/urysohns_bounded.lean
c0ae5baa0a4f5a02ecd2c46a22becc5df55d23ce
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,307
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 topology.urysohns_lemma import topology.continuous_function.bounded /-! # Urysohn's lemma for bounded continuous functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we reformulate Urysohn's lemma `exists_continuous_zero_one_of_closed` in terms of bounded continuous functions `X →ᵇ ℝ`. These lemmas live in a separate file because `topology.continuous_function.bounded` imports too many other files. ## Tags Urysohn's lemma, normal topological space -/ open_locale bounded_continuous_function open set function /-- Urysohns lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, then there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ lemma exists_bounded_zero_one_of_closed {X : Type*} [topological_space X] [normal_space X] {s t : set X} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : X →ᵇ ℝ, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := let ⟨f, hfs, hft, hf⟩ := exists_continuous_zero_one_of_closed hs ht hd in ⟨⟨f, 1, λ x y, real.dist_le_of_mem_Icc_01 (hf _) (hf _)⟩, hfs, hft, hf⟩ /-- Urysohns lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, and `a ≤ b` are two real numbers, then there exists a continuous function `f : X → ℝ` such that * `f` equals `a` on `s`; * `f` equals `b` on `t`; * `a ≤ f x ≤ b` for all `x`. -/ lemma exists_bounded_mem_Icc_of_closed_of_le {X : Type*} [topological_space X] [normal_space X] {s t : set X} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) {a b : ℝ} (hle : a ≤ b) : ∃ f : X →ᵇ ℝ, eq_on f (const X a) s ∧ eq_on f (const X b) t ∧ ∀ x, f x ∈ Icc a b := let ⟨f, hfs, hft, hf01⟩ := exists_bounded_zero_one_of_closed hs ht hd in ⟨bounded_continuous_function.const X a + (b - a) • f, λ x hx, by simp [hfs hx], λ x hx, by simp [hft hx], λ x, ⟨by dsimp; nlinarith [(hf01 x).1], by dsimp; nlinarith [(hf01 x).2]⟩⟩
de4c872aa9d050a59c82c886f6bc7b769c28c4f3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/autoImplicitForbidden.lean
9cc11570aebe289f48f8ef19ad56b6edd3eeccaa
[ "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
547
lean
def f : f → Bool := -- Error at second `f` fun _ => true mutual def g : h → Bool := -- Error at `h`, `h` is not eligible to be an auto implicit because of the mutual block fun _ => true def h := List Nat end structure Bla (x : List Bla) where -- Error at second `Foo` val : Nat inductive Foo : List Foo -> Type -- Error at second `Foo` | x : Foo [] mutual inductive Ex1 : Ex2 → Type -- Error at `Ex2` inductive Ex2 : Type end structure Bar := (x : Na) (y : Nat := foobar) -- Error at `foobar` #print Bar.mk
b7ff6c73b3355f7896b346b76c4167515fdf035f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1295.lean
acd00168d7df4f6c81e6df1f2e91109215309d6e
[ "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
323
lean
set_option pp.all true open tactic example : true := by do a ← to_expr ``((0 : ℕ)), b ← to_expr ``(nat.zero), fail_if_success (unify a b transparency.none), triv example (x : ℕ) : true := by do a ← to_expr ```((x + 0 : ℕ)), b ← to_expr ```(x + nat.zero), fail_if_success (unify a b transparency.none), triv
3fa6e73c80f3a6b0ffcbdbe76cbcae61a9e0c61b
35677d2df3f081738fa6b08138e03ee36bc33cad
/test/rewrite_all.lean
16f790c2445cd5c573daaba9cb6c653f764c06c2
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,585
lean
/- Copyright (c) 2018 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import tactic.rewrite_all import data.vector structure F := (a : ℕ) (v : vector ℕ a) (p : v.val = []) example (f : F) : f.v.val = [] := begin perform_nth_rewrite 0 [f.p], end structure cat := (O : Type) (H : O → O → Type) (i : Π o : O, H o o) (c : Π {X Y Z : O} (f : H X Y) (g : H Y Z), H X Z) (li : Π {X Y : O} (f : H X Y), c (i X) f = f) (ri : Π {X Y : O} (f : H X Y), c f (i Y) = f) (a : Π {W X Y Z : O} (f : H W X) (g : H X Y) (h : H Y Z), c (c f g) h = c f (c g h)) open tactic example (C : cat) (W X Y Z : C.O) (f : C.H X Y) (g : C.H W X) (h k : C.H Y Z) : C.c (C.c g f) h = C.c g (C.c f h) := begin perform_nth_rewrite 0 [C.a], end example (C : cat) (X Y : C.O) (f : C.H X Y) : C.c f (C.i Y) = f := begin perform_nth_rewrite 0 [C.ri], end -- The next two examples fail when using the kabstract backend. axiom foo : [1] = [2] example : [[1], [1], [1]] = [[1], [2], [1]] := begin nth_rewrite_lhs 1 [foo], end axiom foo' : [6] = [7] axiom bar' : [[5],[5]] = [[6],[6]] example : [[7],[6]] = [[5],[5]] := begin nth_rewrite_lhs 0 foo', nth_rewrite_rhs 0 bar', nth_rewrite_lhs 0 ←foo', nth_rewrite_lhs 0 ←foo', end axiom wowzer : (3, 3) = (5, 2) axiom kachow (n : ℕ) : (4, n) = (5, n) axiom pchew (n : ℕ) : (n, 5) = (5, n) axiom smash (n m : ℕ) : (n, m) = (1, 1) example : [(3, 3), (5, 9), (5, 9)] = [(4, 5), (3, 6), (1, 1)] := begin nth_rewrite_lhs 0 wowzer, nth_rewrite_lhs 2 ←pchew, nth_rewrite_rhs 0 pchew, nth_rewrite_rhs 0 smash, nth_rewrite_rhs 1 smash, nth_rewrite_rhs 2 smash, nth_rewrite_lhs 0 smash, nth_rewrite_lhs 1 smash, nth_rewrite_lhs 2 smash, end example (a b c : ℕ) : c + a + b = a + c + b := begin nth_rewrite_rhs 1 add_comm, end -- With the `kabstract` backend, we only find one rewrite, even though there are obviously two. -- The problem is that `(a + b) + c` matches directly, so the WHOLE THING gets replaced with a -- metavariable, per the `kabstract` strategy. This is devastating to the search, since we cannot -- see inside this metavariable. -- I still think it's fixable. Because all applications have an order, I'm pretty sure we can't -- miss any rewrites if we also look inside every thing we chunk-up into a metavariable as well. -- In almost every case this will bring up no results (with the exception of situations like this -- one), so there should be essentially no change in complexity.
a70ea3aa5b8ed4c40b8b8710e98d7202aaca6e54
7565ffb53cc64430691ce89265da0f944ee43051
/hott/homotopy/sphere.hlean
391a5ad21cb5c197e26820b2e2743009f1593703
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,924
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the n-spheres -/ import .susp types.trunc open eq nat susp bool is_trunc unit pointed algebra /- We can define spheres with the following possible indices: - trunc_index (defining S^-2 = S^-1 = empty) - nat (forgetting that S^-1 = empty) - nat, but counting wrong (S^0 = empty, S^1 = bool, ...) - some new type "integers >= -1" We choose the last option here. -/ /- Sphere levels -/ inductive sphere_index : Type₀ := | minus_one : sphere_index | succ : sphere_index → sphere_index notation `ℕ₋₁` := sphere_index namespace trunc_index definition sub_one [reducible] (n : ℕ₋₁) : ℕ₋₂ := sphere_index.rec_on n -2 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_sphere_index [reducible] (n : ℕ₋₁) : ℕ₋₂ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) end trunc_index namespace sphere_index /- notation for sphere_index is -1, 0, 1, ... from 0 and up this comes from a coercion from num to sphere_index (via nat) -/ postfix `.+1`:(max+1) := sphere_index.succ postfix `.+2`:(max+1) := λ(n : sphere_index), (n .+1 .+1) notation `-1` := minus_one definition has_zero_sphere_index [instance] : has_zero ℕ₋₁ := has_zero.mk (succ minus_one) definition has_one_sphere_index [instance] : has_one ℕ₋₁ := has_one.mk (succ (succ minus_one)) definition add_plus_one (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.rec_on m n (λ k l, l .+1) -- addition of sphere_indices, where (-1 + -1) is defined to be -1. protected definition add (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.cases_on m (sphere_index.cases_on n -1 id) (sphere_index.rec n (λn' r, succ r)) inductive le (a : ℕ₋₁) : ℕ₋₁ → Type := | sp_refl : le a a | step : Π {b}, le a b → le a (b.+1) infix ` +1+ `:65 := sphere_index.add_plus_one definition has_add_sphere_index [instance] [priority 2000] [reducible] : has_add ℕ₋₁ := has_add.mk sphere_index.add definition has_le_sphere_index [instance] : has_le ℕ₋₁ := has_le.mk sphere_index.le definition sub_one [reducible] (n : ℕ) : ℕ₋₁ := nat.rec_on n -1 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_nat [coercion] [reducible] (n : ℕ) : ℕ₋₁ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) definition add_one [reducible] (n : ℕ₋₁) : ℕ := sphere_index.rec_on n 0 (λ n k, nat.succ k) definition add_plus_one_of_nat (n m : ℕ) : (n +1+ m) = sphere_index.of_nat (n + m + 1) := begin induction m with m IH, { reflexivity }, { exact ap succ IH} end definition succ_sub_one (n : ℕ) : (nat.succ n)..-1 = n :> ℕ₋₁ := idp definition add_sub_one (n m : ℕ) : (n + m)..-1 = n..-1 +1+ m..-1 :> ℕ₋₁ := begin induction m with m IH, { reflexivity }, { exact ap succ IH } end definition succ_le_succ {n m : ℕ₋₁} (H : n ≤ m) : n.+1 ≤[ℕ₋₁] m.+1 := by induction H with m H IH; apply le.sp_refl; exact le.step IH definition minus_one_le (n : ℕ₋₁) : -1 ≤[ℕ₋₁] n := by induction n with n IH; apply le.sp_refl; exact le.step IH open decidable protected definition has_decidable_eq [instance] : Π(n m : ℕ₋₁), decidable (n = m) | has_decidable_eq -1 -1 := inl rfl | has_decidable_eq (n.+1) -1 := inr (by contradiction) | has_decidable_eq -1 (m.+1) := inr (by contradiction) | has_decidable_eq (n.+1) (m.+1) := match has_decidable_eq n m with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ n = succ m, by injection h with xeqy; exact absurd xeqy xney) end definition not_succ_le_minus_two {n : sphere_index} (H : n .+1 ≤[ℕ₋₁] -1) : empty := by cases H protected definition le_trans {n m k : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] k) : n ≤[ℕ₋₁] k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end definition le_of_succ_le_succ {n m : ℕ₋₁} (H : n.+1 ≤[ℕ₋₁] m.+1) : n ≤[ℕ₋₁] m := begin cases H with m H', { apply le.sp_refl}, { exact sphere_index.le_trans (le.step !le.sp_refl) H'} end theorem not_succ_le_self {n : ℕ₋₁} : ¬n.+1 ≤[ℕ₋₁] n := begin induction n with n IH: intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end protected definition le_antisymm {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] n) : n = m := begin induction H2 with n H2 IH, { reflexivity}, { exfalso, apply @not_succ_le_self n, exact sphere_index.le_trans H1 H2} end protected definition le_succ {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m): n ≤[ℕ₋₁] m.+1 := le.step H1 definition add_plus_one_minus_one (n : ℕ₋₁) : n +1+ -1 = n := idp definition add_plus_one_succ (n m : ℕ₋₁) : n +1+ (m.+1) = (n +1+ m).+1 := idp definition minus_one_add_plus_one (n : ℕ₋₁) : -1 +1+ n = n := begin induction n with n IH, reflexivity, exact ap succ IH end definition succ_add_plus_one (n m : ℕ₋₁) : (n.+1) +1+ m = (n +1+ m).+1 := begin induction m with m IH, reflexivity, exact ap succ IH end definition sphere_index_of_nat_add_one (n : ℕ₋₁) : sphere_index.of_nat (add_one n) = n.+1 := begin induction n with n IH, reflexivity, exact ap succ IH end definition add_one_succ (n : ℕ₋₁) : add_one (n.+1) = succ (add_one n) := by reflexivity definition add_one_sub_one (n : ℕ) : add_one (n..-1) = n := begin induction n with n IH, reflexivity, exact ap nat.succ IH end definition add_one_of_nat (n : ℕ) : add_one n = nat.succ n := ap nat.succ (add_one_sub_one n) definition sphere_index.of_nat_succ (n : ℕ) : sphere_index.of_nat (nat.succ n) = (sphere_index.of_nat n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end /- warning: if this coercion is available, the coercion ℕ → ℕ₋₂ is the composition of the coercions ℕ → ℕ₋₁ → ℕ₋₂. We don't want this composition as coercion, because it has worse computational properties. You can rewrite it with trans_to_of_sphere_index_eq defined below. -/ attribute trunc_index.of_sphere_index [coercion] end sphere_index open sphere_index definition weak_order_sphere_index [trans_instance] [reducible] : weak_order sphere_index := weak_order.mk le sphere_index.le.sp_refl @sphere_index.le_trans @sphere_index.le_antisymm namespace trunc_index definition sub_two_eq_sub_one_sub_one (n : ℕ) : n.-2 = n..-1..-1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition of_nat_sub_one (n : ℕ) : (sphere_index.of_nat n)..-1 = (trunc_index.sub_two n).+1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition sub_one_of_sphere_index (n : ℕ) : of_sphere_index n..-1 = (trunc_index.sub_two n).+1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition succ_sub_one (n : ℕ₋₁) : n.+1..-1 = n :> ℕ₋₂ := idp definition of_sphere_index_of_nat (n : ℕ) : of_sphere_index (sphere_index.of_nat n) = of_nat n :> ℕ₋₂ := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition trans_to_of_sphere_index_eq (n : ℕ) : trunc_index._trans_to_of_sphere_index n = of_nat n :> ℕ₋₂ := of_sphere_index_of_nat n definition trunc_index_of_nat_add_one (n : ℕ₋₁) : trunc_index.of_nat (add_one n) = (of_sphere_index n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end definition of_sphere_index_succ (n : ℕ₋₁) : of_sphere_index (n.+1) = (of_sphere_index n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end end trunc_index open sphere_index equiv definition sphere (n : ℕ₋₁) : Type₀ := iterate_susp (add_one n) empty namespace sphere export [notation] sphere_index definition base {n : ℕ} : sphere n := north definition pointed_sphere [instance] [constructor] (n : ℕ) : pointed (sphere n) := pointed.mk base definition psphere [constructor] (n : ℕ) : Type* := pointed.mk' (sphere n) namespace ops abbreviation S := sphere notation `S*` := psphere end ops open sphere.ops definition sphere_minus_one : S -1 = empty := idp definition sphere_succ [unfold_full] (n : ℕ₋₁) : S n.+1 = susp (S n) := idp definition psphere_succ [unfold_full] (n : ℕ) : S* (n + 1) = psusp (S* n) := idp definition psphere_eq_iterate_susp (n : ℕ) : S* n = pointed.MK (iterate_susp (succ n) empty) !north := begin esimp, apply ap (λx, pointed.MK (susp x) (@north x)); apply ap (λx, iterate_susp x empty), apply add_one_sub_one end definition equator [constructor] (n : ℕ) : S* n →* Ω (S* (succ n)) := loop_psusp_unit (S* n) definition surf {n : ℕ} : Ω[n] (S* n) := begin induction n with n s, { exact south }, { exact (loopn_succ_in (S* (succ n)) n)⁻¹ᵉ* (apn n (equator n) s) } end definition bool_of_sphere [unfold 1] : S 0 → bool := proof susp.rec ff tt (λx, empty.elim x) qed definition sphere_of_bool [unfold 1] : bool → S 0 | ff := proof north qed | tt := proof south qed definition sphere_equiv_bool [constructor] : S 0 ≃ bool := equiv.MK bool_of_sphere sphere_of_bool (λb, match b with | tt := idp | ff := idp end) (λx, proof susp.rec_on x idp idp (empty.rec _) qed) definition psphere_pequiv_pbool [constructor] : S* 0 ≃* pbool := pequiv_of_equiv sphere_equiv_bool idp definition sphere_eq_bool : S 0 = bool := ua sphere_equiv_bool definition sphere_eq_pbool : S* 0 = pbool := pType_eq sphere_equiv_bool idp definition psphere_pequiv_iterate_psusp (n : ℕ) : psphere n ≃* iterate_psusp n pbool := begin induction n with n e, { exact psphere_pequiv_pbool }, { exact psusp_pequiv e } end definition psphere_pmap_pequiv' (A : Type*) (n : ℕ) : ppmap (S* n) A ≃* Ω[n] A := begin revert A, induction n with n IH: intro A, { refine _ ⬝e* !ppmap_pbool_pequiv, exact pequiv_ppcompose_right psphere_pequiv_pbool⁻¹ᵉ* }, { refine psusp_adjoint_loop (S* n) A ⬝e* IH (Ω A) ⬝e* !loopn_succ_in⁻¹ᵉ* } end definition psphere_pmap_pequiv (A : Type*) (n : ℕ) : ppmap (S* n) A ≃* Ω[n] A := begin fapply pequiv_change_fun, { exact psphere_pmap_pequiv' A n }, { exact papn_fun A surf }, { revert A, induction n with n IH: intro A, { reflexivity }, { intro f, refine ap !loopn_succ_in⁻¹ᵉ* (IH (Ω A) _ ⬝ !apn_pcompose _) ⬝ _, exact !loopn_succ_in_inv_natural⁻¹* _ }} end protected definition elim {n : ℕ} {P : Type*} (p : Ω[n] P) : S* n →* P := !psphere_pmap_pequiv⁻¹ᵉ* p -- definition elim_surf {n : ℕ} {P : Type*} (p : Ω[n] P) : apn n (sphere.elim p) surf = p := -- begin -- induction n with n IH, -- { esimp [apn,surf,sphere.elim,psphere_pmap_equiv], apply sorry}, -- { apply sorry} -- end end sphere namespace sphere open is_conn trunc_index sphere_index sphere.ops -- Corollary 8.2.2 theorem is_conn_sphere [instance] (n : ℕ₋₁) : is_conn (n..-1) (S n) := begin induction n with n IH, { apply is_conn_minus_two }, { rewrite [trunc_index.succ_sub_one n, sphere.sphere_succ], apply is_conn_susp } end theorem is_conn_psphere [instance] (n : ℕ) : is_conn (n.-1) (S* n) := transport (λx, is_conn x (sphere n)) (of_nat_sub_one n) (is_conn_sphere n) end sphere open sphere sphere.ops namespace is_trunc open trunc_index variables {n : ℕ} {A : Type} definition is_trunc_of_psphere_pmap_equiv_constant (H : Π(a : A) (f : S* n →* pointed.Mk a) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply iff.elim_right !is_trunc_iff_is_contr_loop, intro a, apply is_trunc_equiv_closed, exact !psphere_pmap_pequiv, fapply is_contr.mk, { exact pmap.mk (λx, a) idp}, { intro f, fapply pmap_eq, { intro x, esimp, refine !respect_pt⁻¹ ⬝ (!H ⬝ !H⁻¹)}, { rewrite [▸*,con.right_inv,▸*,con.left_inv]}} end definition is_trunc_iff_map_sphere_constant (H : Π(f : S n → A) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply is_trunc_of_psphere_pmap_equiv_constant, intros, cases f with f p, esimp at *, apply H end definition psphere_pmap_equiv_constant_of_is_trunc' [H : is_trunc (n.-2.+1) A] (a : A) (f : S* n →* pointed.Mk a) (x : S n) : f x = f base := begin let H' := iff.elim_left (is_trunc_iff_is_contr_loop n A) H a, note H'' := @is_trunc_equiv_closed_rev _ _ _ !psphere_pmap_pequiv H', esimp at H'', have p : f = pmap.mk (λx, f base) (respect_pt f), by apply is_prop.elim, exact ap10 (ap pmap.to_fun p) x end definition psphere_pmap_equiv_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (a : A) (f : S* n →* pointed.Mk a) (x y : S n) : f x = f y := let H := psphere_pmap_equiv_constant_of_is_trunc' a f in !H ⬝ !H⁻¹ definition map_sphere_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (f : S n → A) (x y : S n) : f x = f y := psphere_pmap_equiv_constant_of_is_trunc (f base) (pmap.mk f idp) x y definition map_sphere_constant_of_is_trunc_self [H : is_trunc (n.-2.+1) A] (f : S n → A) (x : S n) : map_sphere_constant_of_is_trunc f x x = idp := !con.right_inv end is_trunc
9d7c6b9cdb12540ef0b177671f45703f9e825362
1dd482be3f611941db7801003235dc84147ec60a
/src/linear_algebra/dimension.lean
a50b1bc65d9379fde4a8e444a23529e2d6121b26
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
8,794
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Johannes Hölzl, Sander Dahmen Dimension of modules and vector spaces. -/ import linear_algebra.basis import set_theory.ordinal noncomputable theory local attribute [instance, priority 0] classical.prop_decidable universes u v w variables {α : Type u} {β γ δ : Type v} section vector_space variables [discrete_field α] [add_comm_group β] [vector_space α β] include α open submodule lattice function set variables (α β) def vector_space.dim : cardinal := cardinal.min (nonempty_subtype.2 (exists_is_basis α β)) (λ b, cardinal.mk b.1) variables {α β} open vector_space theorem is_basis.le_span {I J : set β} (hI : is_basis α I) (hJ : span α J = ⊤) : cardinal.mk I ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { refine le_of_not_lt (λ IJ, _), let S : J → set β := λ j, ↑(hI.repr j).support, have hs : I ⊆ ⋃ j, S j, { intros i hi, have : span α J ≤ comap hI.repr (lc.supported α (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : hI.repr i ∈ _ := this trivial, rw hI.repr_eq_single hi at this, apply this, simp }, suffices : cardinal.mk (⋃ j, S j) < cardinal.mk I, from not_le_of_lt this ⟨set.embedding_of_subset hs⟩, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ finset.finite_to_set _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { rcases exists_finite_card_le_of_finite_of_linear_independent_of_span (cardinal.lt_omega_iff_finite.1 oJ) hI.1 _ with ⟨fI, hi⟩, { rwa [← cardinal.nat_cast_le, cardinal.finset_card, finset.coe_to_finset, cardinal.finset_card, finset.coe_to_finset] at hi }, { rw hJ, apply set.subset_univ } }, end /-- dimension theorem -/ theorem mk_eq_mk_of_basis {I J : set β} (hI : is_basis α I) (hJ : is_basis α J) : cardinal.mk I = cardinal.mk J := le_antisymm (hI.le_span hJ.2) (hJ.le_span hI.2) theorem is_basis.mk_eq_dim {b : set β} (h : is_basis α b) : cardinal.mk b = dim α β := let ⟨b', e⟩ := show ∃ b', dim α β = _, from cardinal.min_eq _ _ in mk_eq_mk_of_basis h (subtype.property _) variables [add_comm_group γ] [vector_space α γ] theorem linear_equiv.dim_eq (f : β ≃ₗ[α] γ) : dim α β = dim α γ := let ⟨b, hb⟩ := exists_is_basis α β in hb.mk_eq_dim.symm.trans $ (cardinal.mk_eq_of_injective f.to_equiv.bijective.1).symm.trans $ (f.is_basis hb).mk_eq_dim lemma dim_bot : dim α (⊥ : submodule α β) = 0 := begin rw [← (@is_basis_empty_bot α β _ _ _).mk_eq_dim], exact cardinal.mk_emptyc (⊥ : submodule α β) end lemma dim_of_field (α : Type*) [discrete_field α] : dim α α = 1 := by rw [← (is_basis_singleton_one α).mk_eq_dim, cardinal.mk_singleton] set_option class.instance_max_depth 37 lemma dim_span {s : set β} (hs : linear_independent α s) : dim α ↥(span α s) = cardinal.mk s := have (span α s).subtype '' ((span α s).subtype ⁻¹' s) = s := image_preimage_eq_of_subset $ by rw [← linear_map.range_coe, range_subtype]; exact subset_span, begin rw [← (is_basis_span hs).mk_eq_dim], calc cardinal.mk ↥(⇑(submodule.subtype (span α s)) ⁻¹' s) = cardinal.mk ↥((submodule.subtype (span α s)) '' ((submodule.subtype (span α s)) ⁻¹' s)) : (cardinal.mk_eq_of_injective subtype.val_injective).symm ... = cardinal.mk ↥s : by rw this end set_option class.instance_max_depth 32 theorem dim_prod : dim α (β × γ) = dim α β + dim α γ := begin rcases exists_is_basis α β with ⟨b, hb⟩, rcases exists_is_basis α γ with ⟨c, hc⟩, rw [← @is_basis.mk_eq_dim α (β × γ) _ _ _ _ (is_basis_inl_union_inr hb hc), ← hb.mk_eq_dim, ← hc.mk_eq_dim, cardinal.mk_union_of_disjoint, cardinal.mk_eq_of_injective, cardinal.mk_eq_of_injective], { exact prod.injective_inr }, { exact prod.injective_inl }, { rintro _ ⟨⟨x, hx, rfl⟩, ⟨y, hy, ⟨⟩⟩⟩, exact zero_not_mem_of_linear_independent (@zero_ne_one α _) hb.1 hx } end theorem dim_quotient (p : submodule α β) : dim α p.quotient + dim α p = dim α β := let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : β →ₗ[α] γ) : dim α f.range + dim α f.ker = dim α β := by rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient] lemma dim_range_le (f : β →ₗ[α] γ) : dim α f.range ≤ dim α β := by rw ← dim_range_add_dim_ker f; exact le_add_right (le_refl _) lemma dim_map_le (f : β →ₗ γ) (p : submodule α β): dim α (p.map f) ≤ dim α p := begin have h := dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_range_of_surjective (f : β →ₗ[α] γ) (h : surjective f) : dim α f.range = dim α γ := begin refine linear_equiv.dim_eq (linear_equiv.of_bijective (submodule.subtype _) _ _), exact linear_map.ker_eq_bot.2 subtype.val_injective, rwa [range_subtype, linear_map.range_eq_top] end lemma dim_eq_surjective (f : β →ₗ[α] γ) (h : surjective f) : dim α β = dim α γ + dim α f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] lemma dim_le_surjective (f : β →ₗ[α] γ) (h : surjective f) : dim α γ ≤ dim α β := by rw [dim_eq_surjective f h]; refine le_add_right (le_refl _) lemma dim_eq_injective (f : β →ₗ[α] γ) (h : injective f) : dim α β = dim α f.range := by rw [← dim_range_add_dim_ker f, linear_map.ker_eq_bot.2 h]; simp [dim_bot] set_option class.instance_max_depth 37 lemma dim_submodule_le (s : submodule α β) : dim α s ≤ dim α β := begin rcases exists_is_basis α s with ⟨bs, hbs⟩, have : linear_independent α (submodule.subtype s '' bs) := hbs.1.image (linear_map.disjoint_ker'.2 $ assume x y _ _ eq, subtype.val_injective eq), have : linear_independent α ((coe : s → β) '' bs) := this, rcases exists_subset_is_basis this with ⟨b, hbs_b, hb⟩, rw [← is_basis.mk_eq_dim hbs, ← is_basis.mk_eq_dim hb], calc cardinal.mk ↥bs = cardinal.mk ((coe : s → β) '' bs) : (cardinal.mk_eq_of_injective $ subtype.val_injective).symm ... ≤ cardinal.mk ↥b : nonempty.intro (embedding_of_subset hbs_b) end set_option class.instance_max_depth 32 lemma dim_le_injective (f : β →ₗ[α] γ) (h : injective f) : dim α β ≤ dim α γ := by rw [dim_eq_injective f h]; exact dim_submodule_le _ lemma dim_le_of_submodule (s t : submodule α β) (h : s ≤ t) : dim α s ≤ dim α t := dim_le_injective (of_le h) $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext.1 eq set_option class.instance_max_depth 37 lemma dim_add_le_dim_add_dim (s t : submodule α β) : dim α (s ⊔ t : submodule α β) ≤ dim α s + dim α t := calc dim α (s ⊔ t : submodule α β) ≤ dim α (s × t) : dim_le_surjective (linear_map.copair (of_le $ le_sup_left) (of_le $ le_sup_right)) (assume ⟨b, (hb : b ∈ (s ⊔ t : submodule α β))⟩, let ⟨x, hx, y, hy, eq⟩ := mem_sup.1 hb in ⟨⟨⟨x, hx⟩, ⟨y, hy⟩⟩, subtype.eq $ by simp [eq.symm]; refl⟩) ... = dim α s + dim α t : dim_prod def rank (f : β →ₗ[α] γ) : cardinal := dim α f.range lemma rank_le_domain (f : β →ₗ[α] γ) : rank f ≤ dim α β := by rw [← dim_range_add_dim_ker f]; exact le_add_right (le_refl _) lemma rank_le_range (f : β →ₗ[α] γ) : rank f ≤ dim α γ := dim_submodule_le _ lemma rank_add_le (f g : β →ₗ[α] γ) : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ dim α (f.range ⊔ g.range : submodule α γ) : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule α γ), from mem_sup.2 ⟨_, mem_image_of_mem _ (mem_univ _), _, mem_image_of_mem _ (mem_univ _), rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ variables [add_comm_group δ] [vector_space α δ] lemma rank_comp_le1 (g : β →ₗ[α] γ) (f : γ →ₗ[α] δ) : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact image_subset _ (subset_univ _) end lemma rank_comp_le2 (g : β →ₗ[α] γ) (f : γ →ₗ δ) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end vector_space
32f3cd212f4c90a501de3e3729d5e87437967abb
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/derive_fintype.lean
0168bea0b27e57fbf2ac2b2ab3c4886122da9c81
[ "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
15,296
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic import data.fintype.basic /-! # Derive handler for `fintype` instances This file introduces a derive handler to automatically generate `fintype` instances for structures and inductives. ## Implementation notes To construct a fintype instance, we need 3 things: 1. A list `l` of elements 2. A proof that `l` has no duplicates 3. A proof that every element in the type is in `l` Now fintype is defined as a finset which enumerates all elements, so steps (1) and (2) are bundled together. It is possible to use finset operations that remove duplicates to avoid the need to prove (2), but this adds unnecessary functions to the constructed term, which makes it more expensive to compute the list, and it also adds a dependence on decidable equality for the type, which we want to avoid. Because we will rely on fintype instances for constructor arguments, we can't actually build a list directly, so (1) and (2) are necessarily somewhat intertwined. The inductive types we will be proving instances for look something like this: ``` @[derive fintype] inductive foo | zero : foo | one : bool → foo | two : ∀ x : fin 3, bar x → foo ``` The list of elements that we generate is ``` {foo.zero} ∪ (finset.univ : bool).map (λ b, finset.one b) ∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y) ``` except that instead of `∪`, that is `finset.union`, we use `finset.disj_union` which doesn't require any deduplication, but does require a proof that the two parts of the union are disjoint. We use `finset.cons` to append singletons like `foo.zero`. The proofs of disjointness would be somewhat expensive since there are quadratically many of them, so instead we use a "discriminant" function. Essentially, we define ``` def foo.enum : foo → ℕ | foo.zero := 0 | (foo.one _) := 1 | (foo.two _ _) := 2 ``` and now the existence of this function implies that foo.zero is not foo.two and so on because they map to different natural numbers. We can prove that sets of natural numbers are mutually disjoint more easily because they have a linear order: `0 < 1 < 2` so `0 ≠ 2`. To package this argument up, we define `finset_above foo foo.enum n` to be a finset `s` together with a proof that all elements `a ∈ s` have `n ≤ enum a`. Now we only have to prove that `enum foo.zero = 0`, `enum (foo.one _) = 1`, etc. (linearly many proofs, all `rfl`) in order to prove that all variants are mutually distinct. We mirror the `finset.cons` and `finset.disj_union` functions into `finset_above.cons` and `finset_above.union`, and this forms the main part of the finset construction. This only handles distinguishing variants of a finset. Now we must enumerate the elements of a variant, for example `{foo.one ff, foo.one tt}`, while at the same time proving that all these elements have discriminant `1` in this case. To do that, we use the `finset_in` type, which is a finset satisfying a property `P`, here `λ a, foo.enum a = 1`. We could use `finset.bind` many times to construct the finset but it turns out to be somewhat complicated to get good side goals for a naturally nodup version of `finset.bind` in the same way as we did with `finset.cons` and `finset.union`. Instead, we tuple up all arguments into one type, leveraging the `fintype` instance on `psigma`, and then define a map from this type to the inductive type that untuples them and applies the constructor. The injectivity property of the constructor ensures that this function is injective, so we can use `finset.map` to apply it. This is the content of the constructor `finset_in.mk`. That completes the proofs of (1) and (2). To prove (3), we perform one case analysis over the inductive type, proving theorems like ``` foo.one a ∈ {foo.zero} ∪ (finset.univ : bool).map (λ b, finset.one b) ∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y) ``` by seeking to the relevant disjunct and then supplying the constructor arguments. This part of the proof is quadratic, but quite simple. (We could do it in `O(n log n)` if we used a balanced tree for the unions.) The tactics perform the following parts of this proof scheme: * `mk_sigma` constructs the type `Γ` in `finset_in.mk` * `mk_sigma_elim` constructs the function `f` in `finset_in.mk` * `mk_sigma_elim_inj` proves that `f` is injective * `mk_sigma_elim_eq` proves that `∀ a, enum (f a) = k` * `mk_finset` constructs the finset `S = {foo.zero} ∪ ...` by recursion on the variants * `mk_finset_total` constructs the proof `|- foo.zero ∈ S; |- foo.one a ∈ S; |- foo.two a b ∈ S` by recursion on the subgoals coming out of the initial `cases` * `mk_fintype_instance` puts it all together to produce a proof of `fintype foo`. The construction of `foo.enum` is also done in this function. -/ namespace derive_fintype /-- A step in the construction of `finset.univ` for a finite inductive type. We will set `enum` to the discriminant of the inductive type, so a `finset_above` represents a finset that enumerates all elements in a tail of the constructor list. -/ def finset_above (α) (enum : α → ℕ) (n : ℕ) := {s : finset α // ∀ x ∈ s, n ≤ enum x} /-- Construct a fintype instance from a completed `finset_above`. -/ def mk_fintype {α} (enum : α → ℕ) (s : finset_above α enum 0) (H : ∀ x, x ∈ s.1) : fintype α := ⟨s.1, H⟩ /-- This is the case for a simple variant (no arguments) in an inductive type. -/ def finset_above.cons {α} {enum : α → ℕ} (n) (a : α) (h : enum a = n) (s : finset_above α enum (n+1)) : finset_above α enum n := begin refine ⟨finset.cons a s.1 _, _⟩, { intro h', have := s.2 _ h', rw h at this, exact nat.not_succ_le_self n this }, { intros x h', rcases finset.mem_cons.1 h' with rfl | h', { exact ge_of_eq h }, { exact nat.le_of_succ_le (s.2 _ h') } } end theorem finset_above.mem_cons_self {α} {enum : α → ℕ} {n a h s} : a ∈ (@finset_above.cons α enum n a h s).1 := multiset.mem_cons_self _ _ theorem finset_above.mem_cons_of_mem {α} {enum : α → ℕ} {n a h s b} : b ∈ (s : finset_above _ _ _).1 → b ∈ (@finset_above.cons α enum n a h s).1 := multiset.mem_cons_of_mem /-- The base case is when we run out of variants; we just put an empty finset at the end. -/ def finset_above.nil {α} {enum : α → ℕ} (n) : finset_above α enum n := ⟨∅, by rintro _ ⟨⟩⟩ instance (α enum n) : inhabited (finset_above α enum n) := ⟨finset_above.nil _⟩ /-- This is a finset covering a nontrivial variant (with one or more constructor arguments). The property `P` here is `λ a, enum a = n` where `n` is the discriminant for the current variant. -/ @[nolint has_inhabited_instance] def finset_in {α} (P : α → Prop) := {s : finset α // ∀ x ∈ s, P x} /-- To construct the finset, we use an injective map from the type `Γ`, which will be the sigma over all constructor arguments. We use sigma instances and existing fintype instances to prove that `Γ` is a fintype, and construct the function `f` that maps `⟨a, b, c, ...⟩` to `C_n a b c ...` where `C_n` is the nth constructor, and `mem` asserts `enum (C_n a b c ...) = n`. -/ def finset_in.mk {α} {P : α → Prop} (Γ) [fintype Γ] (f : Γ → α) (inj : function.injective f) (mem : ∀ x, P (f x)) : finset_in P := ⟨finset.univ.map ⟨f, inj⟩, λ x h, by rcases finset.mem_map.1 h with ⟨x, _, rfl⟩; exact mem x⟩ theorem finset_in.mem_mk {α} {P : α → Prop} {Γ} {s : fintype Γ} {f : Γ → α} {inj mem a} (b) (H : f b = a) : a ∈ (@finset_in.mk α P Γ s f inj mem).1 := finset.mem_map.2 ⟨_, finset.mem_univ _, H⟩ /-- For nontrivial variants, we split the constructor list into a `finset_in` component for the current constructor and a `finset_above` for the rest. -/ def finset_above.union {α} {enum : α → ℕ} (n) (s : finset_in (λ a, enum a = n)) (t : finset_above α enum (n+1)) : finset_above α enum n := begin refine ⟨finset.disj_union s.1 t.1 _, _⟩, { intros a hs ht, have := t.2 _ ht, rw s.2 _ hs at this, exact nat.not_succ_le_self n this }, { intros x h', rcases finset.mem_disj_union.1 h' with h' | h', { exact ge_of_eq (s.2 _ h') }, { exact nat.le_of_succ_le (t.2 _ h') } } end theorem finset_above.mem_union_left {α} {enum : α → ℕ} {n s t a} (H : a ∈ (s : finset_in _).1) : a ∈ (@finset_above.union α enum n s t).1 := multiset.mem_add.2 (or.inl H) theorem finset_above.mem_union_right {α} {enum : α → ℕ} {n s t a} (H : a ∈ (t : finset_above _ _ _).1) : a ∈ (@finset_above.union α enum n s t).1 := multiset.mem_add.2 (or.inr H) end derive_fintype namespace tactic open derive_fintype tactic expr namespace derive_fintype /-- Construct the term `Σ' (a:A) (b:B a) (c:C a b), unit` from `Π (a:A) (b:B a), C a b → T` (the type of a constructor). -/ meta def mk_sigma : expr → tactic expr | (expr.pi n bi d b) := do p ← mk_local' n bi d, e ← mk_sigma (expr.instantiate_var b p), tactic.mk_app ``psigma [d, bind_lambda e p] | _ := pure `(unit) /-- Prove the goal `(Σ' (a:A) (b:B a) (c:C a b), unit) → T` (this is the function `f` in `finset_in.mk`) using recursive `psigma.elim`, finishing with the constructor. The two arguments are the type of the constructor, and the constructor term itself; as we recurse we add arguments to the constructor application and destructure the pi type of the constructor. We return the number of `psigma.elim` applications constructed, which is the number of constructor arguments. -/ meta def mk_sigma_elim : expr → expr → tactic ℕ | (expr.pi n bi d b) c := do refine ``(@psigma.elim %%d _ _ _), i ← intro_fresh n, (+ 1) <$> mk_sigma_elim (expr.instantiate_var b i) (c i) | _ c := do intro1, exact c $> 0 /-- Prove the goal `a, b |- f a = f b → g a = g b` where `f` is the function we constructed in `mk_sigma_elim`, and `g` is some other term that gets built up and eventually closed by reflexivity. Here `a` and `b` have sigma types so the proof approach is to case on `a` and `b` until the goal reduces to `C_n a1 ... am = C_n b1 ... bm → ⟨a1, ..., am⟩ = ⟨b1, ..., bm⟩`, at which point cases on the equality reduces the problem to reflexivity. The arguments are the number `m` returned from `mk_sigma_elim`, and the hypotheses `a,b` that we need to case on. -/ meta def mk_sigma_elim_inj : ℕ → expr → expr → tactic unit | (m+1) x y := do [(_, [x1, x2])] ← cases x, [(_, [y1, y2])] ← cases y, mk_sigma_elim_inj m x2 y2 | 0 x y := do cases x, cases y, is ← intro1 >>= injection, is.mmap' cases, reflexivity /-- Prove the goal `a |- enum (f a) = n`, where `f` is the function constructed in `mk_sigma_elim`, and `enum` is a function that reduces to `n` on the constructor `C_n`. Here we just have to case on `a` `m` times, and then `reflexivity` finishes the proof. -/ meta def mk_sigma_elim_eq : ℕ → expr → tactic unit | (n+1) x := do [(_, [x1, x2])] ← cases x, mk_sigma_elim_eq n x2 | 0 x := reflexivity /-- Prove the goal `|- finset_above T enum k`, where `T` is the inductive type and `enum` is the discriminant function. The arguments are `args`, the parameters to the inductive type (and all constructors), `k`, the index of the current variant, and `cs`, the list of constructor names. This uses `finset_above.cons` for basic variants and `finset_above.union` for variants with arguments, using the auxiliary functions `mk_sigma`, `mk_sigma_elim`, `mk_sigma_elim_inj`, `mk_sigma_elim_eq` to close subgoals. -/ meta def mk_finset (args : list expr) : ℕ → list name → tactic unit | k (c::cs) := do e ← mk_const c, let e := e.mk_app args, t ← infer_type e, if is_pi t then do to_expr ``(finset_above.union %%(reflect k)) tt ff >>= (λ c, apply c {new_goals := new_goals.all}), Γ ← mk_sigma t, to_expr ``(finset_in.mk %%Γ) tt ff >>= (λ c, apply c {new_goals := new_goals.all}), n ← mk_sigma_elim t e, intro1 >>= (λ x, intro1 >>= mk_sigma_elim_inj n x), intro1 >>= mk_sigma_elim_eq n, mk_finset (k+1) cs else do c ← to_expr ``(finset_above.cons %%(reflect k) %%e) tt ff, apply c {new_goals := new_goals.all}, reflexivity, mk_finset (k+1) cs | k [] := applyc ``finset_above.nil /-- Prove the goal `|- Σ' (a:A) (b: B a) (c:C a b), unit` given a list of terms `a, b, c`. -/ meta def mk_sigma_mem : list expr → tactic unit | (x::xs) := fconstructor >> exact x >> mk_sigma_mem xs | [] := fconstructor $> () /-- This function is called to prove `a : T |- a ∈ S.1` where `S` is the `finset_above` constructed by `mk_finset`, after the initial cases on `a : T`, producing a list of subgoals. For each case, we have to navigate past all the variants that don't apply (which is what the `tac` input tactic does), and then call either `finset_above.mem_cons_self` for trivial variants or `finset_above.mem_union_left` and `finset_in.mem_mk` for nontrivial variants. Either way the proof is quite simple. -/ meta def mk_finset_total : tactic unit → list (name × list expr) → tactic unit | tac [] := done | tac ((_, xs) :: gs) := do tac, b ← succeeds (applyc ``finset_above.mem_cons_self), if b then mk_finset_total (tac >> applyc ``finset_above.mem_cons_of_mem) gs else do applyc ``finset_above.mem_union_left, applyc ``finset_in.mem_mk {new_goals := new_goals.all}, mk_sigma_mem xs, reflexivity, mk_finset_total (tac >> applyc ``finset_above.mem_union_right) gs end derive_fintype open tactic.derive_fintype /-- Proves `|- fintype T` where `T` is a non-recursive inductive type with no indices, where all arguments to all constructors are fintypes. -/ meta def mk_fintype_instance : tactic unit := do intros, `(fintype %%e) ← target >>= whnf, (const I ls, args) ← pure (get_app_fn_args e), env ← get_env, let cs := env.constructors_of I, guard (env.inductive_num_indices I = 0) <|> fail "@[derive fintype]: inductive indices are not supported", guard (¬ env.is_recursive I) <|> fail ("@[derive fintype]: recursive inductive types are " ++ "not supported (they are also usually infinite)"), applyc ``mk_fintype {new_goals := new_goals.all}, intro1 >>= cases >>= (λ gs, gs.enum.mmap' $ λ ⟨i, _⟩, exact (reflect i)), mk_finset args 0 cs, intro1 >>= cases >>= mk_finset_total skip /-- Tries to derive a `fintype` instance for inductives and structures. For example: ``` @[derive fintype] inductive foo (n m : ℕ) | zero : foo | one : bool → foo | two : fin n → fin m → foo ``` Here, `@[derive fintype]` adds the instance `foo.fintype`. The underlying finset definitionally unfolds to a list that enumerates the elements of the inductive in lexicographic order. If the structure/inductive has a type parameter `α`, then the generated instance will have an argument `fintype α`, even if it is not used. (This is due to the implementation using `instance_derive_handler`.) -/ @[derive_handler] meta def fintype_instance : derive_handler := instance_derive_handler ``fintype mk_fintype_instance end tactic
3f2fd1963fb8b42f489e482b1ff59bac2e898ab1
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/notation2.lean
a1c631b1c8b3421f219b368996d13e4723a1e21c
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
273
lean
import data.num inductive list (T : Type) : Type := nil {} : list T | cons : T → list T → list T open list notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l infixr `::` := cons check 1 :: 2 :: nil check 1 :: 2 :: 3 :: 4 :: 5 :: nil
c9fae880e5c6cc33f7b372e7857e90bee764b2b4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/pointed2.hlean
aee4af75974ad5b20df97ad9ee79c075adf941b8
[ "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
7,993
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Ported from Coq HoTT -/ import .equiv cubical.square open eq is_equiv equiv pointed is_trunc -- structure pequiv (A B : Type*) := -- (to_pmap : A →* B) -- (is_equiv_to_pmap : is_equiv to_pmap) structure pequiv (A B : Type*) extends equiv A B, pmap A B namespace pointed attribute pequiv._trans_of_to_pmap pequiv._trans_of_to_equiv pequiv.to_pmap pequiv.to_equiv [unfold 3] variables {A B C : Type*} /- pointed equivalences -/ infix ` ≃* `:25 := pequiv attribute pequiv.to_pmap [coercion] attribute pequiv.to_is_equiv [instance] definition pequiv_of_pmap [constructor] (f : A →* B) (H : is_equiv f) : A ≃* B := pequiv.mk f _ (respect_pt f) definition pequiv_of_equiv [constructor] (f : A ≃ B) (H : f pt = pt) : A ≃* B := pequiv.mk f _ H protected definition pequiv.MK [constructor] (f : A →* B) (g : B →* A) (gf : Πa, g (f a) = a) (fg : Πb, f (g b) = b) : A ≃* B := pequiv.mk f (adjointify f g fg gf) (respect_pt f) definition equiv_of_pequiv [constructor] (f : A ≃* B) : A ≃ B := equiv.mk f _ definition to_pinv [constructor] (f : A ≃* B) : B →* A := pmap.mk f⁻¹ ((ap f⁻¹ (respect_pt f))⁻¹ ⬝ !left_inv) definition pua {A B : Type*} (f : A ≃* B) : A = B := pType_eq (equiv_of_pequiv f) !respect_pt protected definition pequiv.refl [refl] [constructor] (A : Type*) : A ≃* A := pequiv_of_pmap !pid !is_equiv_id protected definition pequiv.rfl [constructor] : A ≃* A := pequiv.refl A protected definition pequiv.symm [symm] (f : A ≃* B) : B ≃* A := pequiv_of_pmap (to_pinv f) !is_equiv_inv protected definition pequiv.trans [trans] (f : A ≃* B) (g : B ≃* C) : A ≃* C := pequiv_of_pmap (pcompose g f) !is_equiv_compose postfix `⁻¹ᵉ*`:(max + 1) := pequiv.symm infix ` ⬝e* `:75 := pequiv.trans definition pequiv_rect' (f : A ≃* B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition pequiv_of_eq [constructor] {A B : Type*} (p : A = B) : A ≃* B := pequiv_of_pmap (pcast p) !is_equiv_tr definition peconcat_eq {A B C : Type*} (p : A ≃* B) (q : B = C) : A ≃* C := p ⬝e* pequiv_of_eq q definition eq_peconcat {A B C : Type*} (p : A = B) (q : B ≃* C) : A ≃* C := pequiv_of_eq p ⬝e* q definition eq_of_pequiv {A B : Type*} (p : A ≃* B) : A = B := pType_eq (equiv_of_pequiv p) !respect_pt definition peap {A B : Type*} (F : Type* → Type*) (p : A ≃* B) : F A ≃* F B := pequiv_of_pmap (pcast (ap F (eq_of_pequiv p))) begin cases eq_of_pequiv p, apply is_equiv_id end definition loop_space_pequiv [constructor] (p : A ≃* B) : Ω A ≃* Ω B := pequiv_of_pmap (ap1 p) (is_equiv_ap1 p) definition iterated_loop_space_pequiv [constructor] (n : ℕ) (p : A ≃* B) : Ω[n] A ≃* Ω[n] B := pequiv_of_pmap (apn n p) (is_equiv_apn n p) definition pequiv_eq {p q : A ≃* B} (H : p = q :> (A →* B)) : p = q := begin cases p with f Hf, cases q with g Hg, esimp at *, exact apd011 pequiv_of_pmap H !is_prop.elim end definition loop_space_pequiv_rfl : loop_space_pequiv (@pequiv.refl A) = @pequiv.refl (Ω A) := begin apply pequiv_eq, fapply pmap_eq: esimp, { intro p, exact !idp_con ⬝ !ap_id}, { reflexivity} end infix ` ⬝e*p `:75 := peconcat_eq infix ` ⬝pe* `:75 := eq_peconcat local attribute pequiv.symm [constructor] definition pleft_inv (f : A ≃* B) : f⁻¹ᵉ* ∘* f ~* pid A := phomotopy.mk (left_inv f) abstract begin esimp, symmetry, apply con_inv_cancel_left end end definition pright_inv (f : A ≃* B) : f ∘* f⁻¹ᵉ* ~* pid B := phomotopy.mk (right_inv f) abstract begin induction f with f H p, esimp, rewrite [ap_con, +ap_inv, -adj f, -ap_compose], note q := natural_square (right_inv f) p, rewrite [ap_id at q], apply eq_bot_of_square, exact transpose q end end definition pcancel_left (f : B ≃* C) {g h : A →* B} (p : f ∘* g ~* f ∘* h) : g ~* h := begin refine _⁻¹* ⬝* pwhisker_left f⁻¹ᵉ* p ⬝* _: refine !passoc⁻¹* ⬝* _: refine pwhisker_right _ (pleft_inv f) ⬝* _: apply pid_comp end definition pcancel_right (f : A ≃* B) {g h : B →* C} (p : g ∘* f ~* h ∘* f) : g ~* h := begin refine _⁻¹* ⬝* pwhisker_right f⁻¹ᵉ* p ⬝* _: refine !passoc ⬝* _: refine pwhisker_left _ (pright_inv f) ⬝* _: apply comp_pid end definition phomotopy_pinv_right_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C} (p : g ∘* f ~* h) : g ~* h ∘* f⁻¹ᵉ* := begin refine _ ⬝* pwhisker_right _ p, symmetry, refine !passoc ⬝* _, refine pwhisker_left _ (pright_inv f) ⬝* _, apply comp_pid end definition phomotopy_of_pinv_right_phomotopy {f : B ≃* A} {g : B →* C} {h : A →* C} (p : g ∘* f⁻¹ᵉ* ~* h) : g ~* h ∘* f := begin refine _ ⬝* pwhisker_right _ p, symmetry, refine !passoc ⬝* _, refine pwhisker_left _ (pleft_inv f) ⬝* _, apply comp_pid end definition pinv_right_phomotopy_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C} (p : h ~* g ∘* f) : h ∘* f⁻¹ᵉ* ~* g := (phomotopy_pinv_right_of_phomotopy p⁻¹*)⁻¹* definition phomotopy_of_phomotopy_pinv_right {f : B ≃* A} {g : B →* C} {h : A →* C} (p : h ~* g ∘* f⁻¹ᵉ*) : h ∘* f ~* g := (phomotopy_of_pinv_right_phomotopy p⁻¹*)⁻¹* definition phomotopy_pinv_left_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C} (p : f ∘* g ~* h) : g ~* f⁻¹ᵉ* ∘* h := begin refine _ ⬝* pwhisker_left _ p, symmetry, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (pleft_inv f) ⬝* _, apply pid_comp end definition phomotopy_of_pinv_left_phomotopy {f : C ≃* B} {g : A →* B} {h : A →* C} (p : f⁻¹ᵉ* ∘* g ~* h) : g ~* f ∘* h := begin refine _ ⬝* pwhisker_left _ p, symmetry, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (pright_inv f) ⬝* _, apply pid_comp end definition pinv_left_phomotopy_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C} (p : h ~* f ∘* g) : f⁻¹ᵉ* ∘* h ~* g := (phomotopy_pinv_left_of_phomotopy p⁻¹*)⁻¹* definition phomotopy_of_phomotopy_pinv_left {f : C ≃* B} {g : A →* B} {h : A →* C} (p : h ~* f⁻¹ᵉ* ∘* g) : f ∘* h ~* g := (phomotopy_of_pinv_left_phomotopy p⁻¹*)⁻¹* /- pointed equivalences between particular pointed types -/ definition loop_pequiv_loop [constructor] (f : A ≃* B) : Ω A ≃* Ω B := pequiv.MK (ap1 f) (ap1 f⁻¹ᵉ*) abstract begin intro p, refine ((ap1_compose f⁻¹ᵉ* f) p)⁻¹ ⬝ _, refine ap1_phomotopy (pleft_inv f) p ⬝ _, exact ap1_id p end end abstract begin intro p, refine ((ap1_compose f f⁻¹ᵉ*) p)⁻¹ ⬝ _, refine ap1_phomotopy (pright_inv f) p ⬝ _, exact ap1_id p end end definition loopn_pequiv_loopn (n : ℕ) (f : A ≃* B) : Ω[n] A ≃* Ω[n] B := begin induction n with n IH, { exact f}, { exact loop_pequiv_loop IH} end definition pmap_functor [constructor] {A A' B B' : Type*} (f : A' →* A) (g : B →* B') : ppmap A B →* ppmap A' B' := pmap.mk (λh, g ∘* h ∘* f) abstract begin fapply pmap_eq, { esimp, intro a, exact respect_pt g}, { rewrite [▸*, ap_constant], apply idp_con} end end /- definition pmap_pequiv_pmap {A A' B B' : Type*} (f : A ≃* A') (g : B ≃* B') : ppmap A B ≃* ppmap A' B' := pequiv.MK (pmap_functor f⁻¹ᵉ* g) (pmap_functor f g⁻¹ᵉ*) abstract begin intro a, esimp, apply pmap_eq, { esimp, }, { } end end abstract begin end end -/ end pointed
395bb4530acb2cacdd175d93278e51ffd79f3722
bde6690019e9da475b0c91d5a066e0f6681a1179
/library/standard/kernel.lean
4f912499a8419704990a49e979ddb0a9311e450d
[ "Apache-2.0" ]
permissive
leodemoura/libraries
ae67d491abc580407aa837d65736d515bec39263
14afd47544daa9520ea382d33ba7f6f05c949063
refs/heads/master
1,473,601,302,073
1,403,713,370,000
1,403,713,370,000
19,831,525
1
0
null
null
null
null
UTF-8
Lean
false
false
50,486
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import macros tactic universe U ≥ 1 definition TypeU := (Type U) -- create default rewrite rule set (* mk_rewrite_rule_set() *) variable Bool : Type -- Reflexivity for heterogeneous equality -- We use universe U+1 in heterogeneous equality axioms because we want to be able -- to state the equality between A and B of (Type U) axiom hrefl {A : (Type U+1)} (a : A) : a == a -- Homogeneous equality definition eq {A : (Type U)} (a b : A) := a == b infix 50 = : eq theorem refl {A : (Type U)} (a : A) : a = a := hrefl a theorem heq_eq {A : (Type U)} (a b : A) : (a == b) = (a = b) := refl (a == b) definition true : Bool := (λ x : Bool, x) = (λ x : Bool, x) theorem trivial : true := refl (λ x : Bool, x) set_opaque true true definition false : Bool := ∀ x : Bool, x alias ⊤ : true alias ⊥ : false definition not (a : Bool) := a → false notation 40 ¬ _ : not definition or (a b : Bool) := ∀ c : Bool, (a → c) → (b → c) → c infixr 30 || : or infixr 30 \/ : or infixr 30 ∨ : or definition and (a b : Bool) := ∀ c : Bool, (a → b → c) → c infixr 35 && : and infixr 35 /\ : and infixr 35 ∧ : and definition implies (a b : Bool) := a → b definition ne {A : (Type U)} (a b : A) := ¬ (a = b) infix 50 ≠ : ne theorem ne_intro {A : (Type U)} {a b : A} (H : (a = b) → false) : a ≠ b := H theorem ne_elim {A : (Type U)} {a b : A} (H1 : (a ≠ b)) (H2 : (a = b)) : false := H1 H2 theorem ne_irrefl {A : (Type U)} {a : A} (H : a ≠ a) : false := H (refl a) definition iff (a b : Bool) := a = b infixr 25 <-> : iff infixr 25 ↔ : iff theorem not_intro {a : Bool} (H : a → false) : ¬ a := H theorem not_elim {a : Bool} (H1: ¬ a) (H2 : a) : false := H1 H2 theorem absurd {a : Bool} (H1 : a) (H2 : ¬ a) : false := H2 H1 theorem false_elim (a : Bool) (H : false) : a := H a set_opaque false true theorem mt {a b : Bool} (H1 : a → b) (H2 : ¬ b) : ¬ a := assume Ha : a, absurd (H1 Ha) H2 theorem contrapos {a b : Bool} (H : a → b) : ¬ b → ¬ a := assume Hnb : ¬ b, mt H Hnb theorem absurd_elim {a : Bool} (b : Bool) (H1 : a) (H2 : ¬ a) : b := false_elim b (absurd H1 H2) theorem or_intro_left {a : Bool} (b : Bool) (H : a) : a ∨ b := take c : Bool, assume (H1 : a → c) (H2 : b → c), H1 H theorem or_intro_right (a : Bool) {b : Bool} (H : b) : a ∨ b := take c : Bool, assume (H1 : a → c) (H2 : b → c), H2 H theorem or_elim {a b c : Bool} (H1 : a ∨ b) (H2 : a → c) (H3 : b → c) : c := H1 c H2 H3 theorem resolve_right {a b : Bool} (H1 : a ∨ b) (H2 : ¬ a) : b := H1 b (assume Ha : a, absurd_elim b Ha H2) (assume Hb : b, Hb) theorem resolve_left {a b : Bool} (H1 : a ∨ b) (H2 : ¬ b) : a := H1 a (assume Ha : a, Ha) (assume Hb : b, absurd_elim a Hb H2) theorem or_flip {a b : Bool} (H : a ∨ b) : b ∨ a := take c : Bool, assume (H1 : b → c) (H2 : a → c), H c H2 H1 theorem and_intro {a b : Bool} (H1 : a) (H2 : b) : a ∧ b := take c : Bool, assume H : a → b → c, H H1 H2 theorem and_elim_left {a b : Bool} (H : a ∧ b) : a := H a (assume (Ha : a) (Hb : b), Ha) theorem and_elim_right {a b : Bool} (H : a ∧ b) : b := H b (assume (Ha : a) (Hb : b), Hb) axiom subst {A : (Type U)} {a b : A} {P : A → Bool} (H1 : P a) (H2 : a = b) : P b -- Alias for subst where we provide P explicitly, but keep A,a,b implicit theorem substp {A : (Type U)} {a b : A} (P : A → Bool) (H1 : P a) (H2 : a = b) : P b := subst H1 H2 theorem symm {A : (Type U)} {a b : A} (H : a = b) : b = a := subst (refl a) H theorem trans {A : (Type U)} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H1 H2 theorem hcongr1 {A : (Type U)} {B : A → (Type U)} {f g : ∀ x, B x} (H : f = g) (a : A) : f a = g a := substp (fun h, f a = h a) (refl (f a)) H theorem congr1 {A B : (Type U)} {f g : A → B} (H : f = g) (a : A) : f a = g a := hcongr1 H a theorem congr2 {A B : (Type U)} {a b : A} (f : A → B) (H : a = b) : f a = f b := substp (fun x : A, f a = f x) (refl (f a)) H theorem congr {A B : (Type U)} {f g : A → B} {a b : A} (H1 : f = g) (H2 : a = b) : f a = g b := subst (congr2 f H2) (congr1 H1 b) theorem true_ne_false : ¬ true = false := assume H : true = false, subst trivial H theorem absurd_not_true (H : ¬ true) : false := absurd trivial H theorem not_false_trivial : ¬ false := assume H : false, H -- "equality modus pones" theorem eqmp {a b : Bool} (H1 : a = b) (H2 : a) : b := subst H2 H1 infixl 100 <| : eqmp infixl 100 ◂ : eqmp theorem eqmpr {a b : Bool} (H1 : a = b) (H2 : b) : a := (symm H1) ◂ H2 theorem imp_trans {a b c : Bool} (H1 : a → b) (H2 : b → c) : a → c := assume Ha, H2 (H1 Ha) theorem imp_eq_trans {a b c : Bool} (H1 : a → b) (H2 : b = c) : a → c := assume Ha, H2 ◂ (H1 Ha) theorem eq_imp_trans {a b c : Bool} (H1 : a = b) (H2 : b → c) : a → c := assume Ha, H2 (H1 ◂ Ha) theorem to_eq {A : (Type U)} {a b : A} (H : a == b) : a = b := (heq_eq a b) ◂ H theorem to_heq {A : (Type U)} {a b : A} (H : a = b) : a == b := (symm (heq_eq a b)) ◂ H theorem iff_elim_left {a b : Bool} (H : a ↔ b) : a → b := (λ Ha : a, eqmp H Ha) theorem iff_elim_right {a b : Bool} (H : a ↔ b) : b → a := (λ Hb : b, eqmpr H Hb) theorem ne_symm {A : (Type U)} {a b : A} (H : a ≠ b) : b ≠ a := assume H1 : b = a, H (symm H1) theorem eq_ne_trans {A : (Type U)} {a b c : A} (H1 : a = b) (H2 : b ≠ c) : a ≠ c := subst H2 (symm H1) theorem ne_eq_trans {A : (Type U)} {a b c : A} (H1 : a ≠ b) (H2 : b = c) : a ≠ c := subst H1 H2 theorem eqt_elim {a : Bool} (H : a = true) : a := (symm H) ◂ trivial theorem eqf_elim {a : Bool} (H : a = false) : ¬ a := not_intro (λ Ha : a, H ◂ Ha) theorem heqt_elim {a : Bool} (H : a == true) : a := eqt_elim (to_eq H) axiom boolcomplete (a : Bool) : a = true ∨ a = false theorem case (P : Bool → Bool) (H1 : P true) (H2 : P false) (a : Bool) : P a := or_elim (boolcomplete a) (assume Ht : a = true, subst H1 (symm Ht)) (assume Hf : a = false, subst H2 (symm Hf)) theorem em (a : Bool) : a ∨ ¬ a := or_elim (boolcomplete a) (assume Ht : a = true, or_intro_left (¬ a) (eqt_elim Ht)) (assume Hf : a = false, or_intro_right a (eqf_elim Hf)) -- allows "proof by cases" theorem by_cases {P : Bool} {b : Bool} (H1 : b → P) (H2 : ¬ b → P) : P := or_elim (em b) H1 H2 theorem boolcomplete_swapped (a : Bool) : a = false ∨ a = true := case (λ x, x = false ∨ x = true) (or_intro_right (true = false) (refl true)) (or_intro_left (false = true) (refl false)) a theorem not_true : (¬ true) = false := let aux : ¬ (¬ true) = true := assume H : (¬ true) = true, absurd_not_true (subst trivial (symm H)) in resolve_right (boolcomplete (¬ true)) aux theorem not_false : (¬ false) = true := let aux : ¬ (¬ false) = false := assume H : (¬ false) = false, subst not_false_trivial H in resolve_right (boolcomplete_swapped (¬ false)) aux add_rewrite not_true not_false theorem not_not_eq (a : Bool) : (¬ ¬ a) = a := case (λ x, (¬ ¬ x) = x) (calc (¬ ¬ true) = (¬ false) : { not_true } ... = true : not_false) (calc (¬ ¬ false) = (¬ true) : { not_false } ... = false : not_true) a add_rewrite not_not_eq theorem not_ne {A : (Type U)} (a b : A) : ¬ (a ≠ b) ↔ a = b := not_not_eq (a = b) add_rewrite not_ne theorem not_ne_elim {A : (Type U)} {a b : A} (H : ¬ (a ≠ b)) : a = b := (not_ne a b) ◂ H theorem not_not_elim {a : Bool} (H : ¬ ¬ a) : a := (not_not_eq a) ◂ H theorem not_imp_elim_left {a b : Bool} (Hnab : ¬ (a → b)) : a := not_not_elim (show ¬ ¬ a, from assume Hna : ¬ a, absurd (assume Ha : a, absurd_elim b Ha Hna) Hnab) theorem not_imp_elimr {a b : Bool} (H : ¬ (a → b)) : ¬ b := assume Hb : b, absurd (assume Ha : a, Hb) H theorem boolext {a b : Bool} (Hab : a → b) (Hba : b → a) : a = b := or_elim (boolcomplete a) (λ Hat : a = true, or_elim (boolcomplete b) (λ Hbt : b = true, trans Hat (symm Hbt)) (λ Hbf : b = false, false_elim (a = b) (subst (Hab (eqt_elim Hat)) Hbf))) (λ Haf : a = false, or_elim (boolcomplete b) (λ Hbt : b = true, false_elim (a = b) (subst (Hba (eqt_elim Hbt)) Haf)) (λ Hbf : b = false, trans Haf (symm Hbf))) -- Another name for boolext theorem iff_intro {a b : Bool} (Hab : a → b) (Hba : b → a) : a ↔ b := boolext Hab Hba theorem eqt_intro {a : Bool} (H : a) : a = true := boolext (assume H1 : a, trivial) (assume H2 : true, H) theorem eqf_intro {a : Bool} (H : ¬ a) : a = false := boolext (assume H1 : a, absurd H1 H) (assume H2 : false, false_elim a H2) theorem by_contradiction {a : Bool} (H : ¬ a → false) : a := or_elim (em a) (λ H1 : a, H1) (λ H1 : ¬ a, false_elim a (H H1)) theorem ne_id {A : (Type U)} (a : A) : (a ≠ a) ↔ false := boolext (assume H, ne_irrefl H) (assume H, false_elim (a ≠ a) H) theorem eq_id {A : (Type U)} (a : A) : (a = a) ↔ true := eqt_intro (refl a) theorem iff_id (a : Bool) : (a ↔ a) ↔ true := eqt_intro (refl a) theorem heq_id (A : (Type U+1)) (a : A) : (a == a) ↔ true := eqt_intro (hrefl a) theorem ne_eq_iff_false {A : (Type U)} {a b : A} (H : a ≠ b) : a = b ↔ false := eqf_intro H theorem ne_to_not_eq {A : (Type U)} {a b : A} : a ≠ b ↔ ¬ a = b := refl (a ≠ b) add_rewrite eq_id iff_id ne_to_not_eq -- Remark: ordered rewriting + assoc + comm + left_comm sorts a term lexicographically theorem left_comm {A : (Type U)} {R : A -> A -> A} (comm : ∀ x y, R x y = R y x) (assoc : ∀ x y z, R (R x y) z = R x (R y z)) : ∀ x y z, R x (R y z) = R y (R x z) := take x y z, calc R x (R y z) = R (R x y) z : symm (assoc x y z) ... = R (R y x) z : { comm x y } ... = R y (R x z) : assoc y x z theorem right_comm {A : (Type U)} {R : A -> A -> A} (comm : ∀ x y, R x y = R y x) (assoc : ∀ x y z, R (R x y) z = R x (R y z)) : ∀ x y z, R (R x y) z = R (R x z) y := take x y z, calc R (R x y) z = R x (R y z) : assoc x y z ... = R x (R z y) : { comm y z } ... = R (R x z) y : symm (assoc x z y) theorem or_comm (a b : Bool) : (a ∨ b) = (b ∨ a) := boolext (assume H, or_elim H (λ H1, or_intro_right b H1) (λ H2, or_intro_left a H2)) (assume H, or_elim H (λ H1, or_intro_right a H1) (λ H2, or_intro_left b H2)) theorem or_assoc (a b c : Bool) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := boolext (assume H : (a ∨ b) ∨ c, or_elim H (λ H1 : a ∨ b, or_elim H1 (λ Ha : a, or_intro_left (b ∨ c) Ha) (λ Hb : b, or_intro_right a (or_intro_left c Hb))) (λ Hc : c, or_intro_right a (or_intro_right b Hc))) (assume H : a ∨ (b ∨ c), or_elim H (λ Ha : a, (or_intro_left c (or_intro_left b Ha))) (λ H1 : b ∨ c, or_elim H1 (λ Hb : b, or_intro_left c (or_intro_right a Hb)) (λ Hc : c, or_intro_right (a ∨ b) Hc))) theorem or_id (a : Bool) : a ∨ a ↔ a := boolext (assume H, or_elim H (λ H1, H1) (λ H2, H2)) (assume H, or_intro_left a H) theorem or_false_left (a : Bool) : a ∨ false ↔ a := boolext (assume H, or_elim H (λ H1, H1) (λ H2, false_elim a H2)) (assume H, or_intro_left false H) theorem or_false_right (a : Bool) : false ∨ a ↔ a := trans (or_comm false a) (or_false_left a) theorem or_true_left (a : Bool) : true ∨ a ↔ true := boolext (assume H : true ∨ a, trivial) (assume H : true, or_intro_left a trivial) theorem or_true_right (a : Bool) : a ∨ true ↔ true := trans (or_comm a true) (or_true_left a) theorem or_tauto (a : Bool) : a ∨ ¬ a ↔ true := eqt_intro (em a) theorem or_left_comm (a b c : Bool) : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := left_comm or_comm or_assoc a b c theorem or_right_comm (a b c : Bool) : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := right_comm or_comm or_assoc a b c theorem or_imp_or {a b c d : Bool} (H1 : a ∨ b) (H2 : a → c) (H3 : b → d) : c ∨ d := or_elim H1 (assume Ha : a, or_intro_left d (H2 Ha)) (assume Hb : b, or_intro_right c (H3 Hb)) theorem or_imp_or_left {a b c : Bool} (H1 : a ∨ c) (H : a → b) : b ∨ c := or_imp_or H1 (assume H2 : a, H H2) (assume H2 : c, H2) theorem or_imp_or_right {a b c : Bool} (H1 : c ∨ a) (H : a → b) : c ∨ b := or_imp_or H1 (assume H2 : c, H2) (assume H2 : a, H H2) add_rewrite or_comm or_assoc or_id or_false_left or_false_right or_true_left or_true_right or_tauto or_left_comm theorem and_comm (a b : Bool) : a ∧ b ↔ b ∧ a := boolext (assume H, and_intro (and_elim_right H) (and_elim_left H)) (assume H, and_intro (and_elim_right H) (and_elim_left H)) theorem and_id (a : Bool) : a ∧ a ↔ a := boolext (assume H, and_elim_left H) (assume H, and_intro H H) theorem and_assoc (a b c : Bool) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := boolext (assume H, and_intro (and_elim_left (and_elim_left H)) (and_intro (and_elim_right (and_elim_left H)) (and_elim_right H))) (assume H, and_intro (and_intro (and_elim_left H) (and_elim_left (and_elim_right H))) (and_elim_right (and_elim_right H))) theorem and_true_right (a : Bool) : a ∧ true ↔ a := boolext (assume H : a ∧ true, and_elim_left H) (assume H : a, and_intro H trivial) theorem and_true_left (a : Bool) : true ∧ a ↔ a := trans (and_comm true a) (and_true_right a) theorem and_false_left (a : Bool) : a ∧ false ↔ false := boolext (assume H, and_elim_right H) (assume H, false_elim (a ∧ false) H) theorem and_false_right (a : Bool) : false ∧ a ↔ false := trans (and_comm false a) (and_false_left a) theorem and_absurd (a : Bool) : a ∧ ¬ a ↔ false := boolext (assume H, absurd (and_elim_left H) (and_elim_right H)) (assume H, false_elim (a ∧ ¬ a) H) theorem and_left_comm (a b c : Bool) : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := left_comm and_comm and_assoc a b c add_rewrite and_comm and_assoc and_id and_false_left and_false_right and_true_left and_true_right and_absurd and_left_comm theorem imp_true_right (a : Bool) : (a → true) ↔ true := boolext (assume H, trivial) (assume H Ha, trivial) theorem imp_true_left (a : Bool) : (true → a) ↔ a := boolext (assume H : true → a, H trivial) (assume Ha H, Ha) theorem imp_false_right (a : Bool) : (a → false) ↔ ¬ a := refl _ theorem imp_false_left (a : Bool) : (false → a) ↔ true := boolext (assume H, trivial) (assume H Hf, false_elim a Hf) theorem imp_id (a : Bool) : (a → a) ↔ true := eqt_intro (λ H : a, H) add_rewrite imp_true_right imp_true_left imp_false_right imp_false_left imp_id theorem imp_or (a b : Bool) : (a → b) ↔ ¬ a ∨ b := boolext (assume H : a → b, (or_elim (em a) (λ Ha : a, or_intro_right (¬ a) (H Ha)) (λ Hna : ¬ a, or_intro_left b Hna))) (assume H : ¬ a ∨ b, assume Ha : a, resolve_right H ((symm (not_not_eq a)) ◂ Ha)) theorem or_imp (a b : Bool) : a ∨ b ↔ (¬ a → b) := boolext (assume H : a ∨ b, (or_elim H (assume (Ha : a) (Hna : ¬ a), absurd_elim b Ha Hna) (assume (Hb : b) (Hna : ¬ a), Hb))) (assume H : ¬ a → b, (or_elim (em a) (assume Ha : a, or_intro_left b Ha) (assume Hna : ¬ a, or_intro_right a (H Hna)))) theorem not_congr {a b : Bool} (H : a ↔ b) : ¬ a ↔ ¬ b := congr2 not H -- The Lean parser has special treatment for the constant exists. -- It allows us to write -- exists x y : A, P x y and ∃ x y : A, P x y -- as syntax sugar for -- exists A (fun x : A, exists A (fun y : A, P x y)) -- That is, it treats the exists as an extra binder such as fun and forall. -- It also provides an alias (Exists) that should be used when we -- want to treat exists as a constant. definition Exists (A : (Type U)) (P : A → Bool) := ¬ (∀ x, ¬ (P x)) definition exists_unique {A : (Type U)} (p : A → Bool) := ∃ x, p x ∧ ∀ y, y ≠ x → ¬ p y theorem exists_elim {A : (Type U)} {P : A → Bool} {B : Bool} (H1 : Exists A P) (H2 : ∀ (a : A) (H : P a), B) : B := by_contradiction (assume R : ¬ B, absurd (take a : A, mt (assume H : P a, H2 a H) R) H1) theorem exists_intro {A : (Type U)} {P : A → Bool} (a : A) (H : P a) : Exists A P := assume H1 : (∀ x : A, ¬ P x), absurd H (H1 a) theorem not_exists (A : (Type U)) (P : A → Bool) : ¬ (∃ x : A, P x) ↔ (∀ x : A, ¬ P x) := calc (¬ ∃ x : A, P x) = ¬ ¬ ∀ x : A, ¬ P x : refl (¬ ∃ x : A, P x) ... = ∀ x : A, ¬ P x : not_not_eq (∀ x : A, ¬ P x) theorem not_exists_elim {A : (Type U)} {P : A → Bool} (H : ¬ ∃ x : A, P x) : ∀ x : A, ¬ P x := (not_exists A P) ◂ H theorem exists_unfold1 {A : (Type U)} {P : A → Bool} (a : A) (H : ∃ x : A, P x) : P a ∨ (∃ x : A, x ≠ a ∧ P x) := exists_elim H (λ (w : A) (H1 : P w), or_elim (em (w = a)) (λ Heq : w = a, or_intro_left (∃ x : A, x ≠ a ∧ P x) (subst H1 Heq)) (λ Hne : w ≠ a, or_intro_right (P a) (exists_intro w (and_intro Hne H1)))) theorem exists_unfold2 {A : (Type U)} {P : A → Bool} (a : A) (H : P a ∨ (∃ x : A, x ≠ a ∧ P x)) : ∃ x : A, P x := or_elim H (λ H1 : P a, exists_intro a H1) (λ H2 : (∃ x : A, x ≠ a ∧ P x), exists_elim H2 (λ (w : A) (Hw : w ≠ a ∧ P w), exists_intro w (and_elim_right Hw))) theorem exists_unfold {A : (Type U)} (P : A → Bool) (a : A) : (∃ x : A, P x) ↔ (P a ∨ (∃ x : A, x ≠ a ∧ P x)) := boolext (assume H : (∃ x : A, P x), exists_unfold1 a H) (assume H : (P a ∨ (∃ x : A, x ≠ a ∧ P x)), exists_unfold2 a H) definition inhabited (A : (Type U)) := ∃ x : A, true -- If we have an element of type A, then A is inhabited theorem inhabited_intro {A : (Type U)} (a : A) : inhabited A := assume H : (∀ x, ¬ true), absurd_not_true (H a) theorem inhabited_elim {A : (Type U)} (H1 : inhabited A) {B : Bool} (H2 : A → B) : B := obtain (w : A) (Hw : true), from H1, H2 w theorem inhabited_ex_intro {A : (Type U)} {P : A → Bool} (H : ∃ x, P x) : inhabited A := obtain (w : A) (Hw : P w), from H, exists_intro w trivial -- If a function space is non-empty, then for every 'a' in the domain, the range (B a) is not empty theorem inhabited_range {A : (Type U)} {B : A → (Type U)} (H : inhabited (∀ x, B x)) (a : A) : inhabited (B a) := by_contradiction (assume N : ¬ inhabited (B a), let s1 : ¬ ∃ x : B a, true := N, s2 : ∀ x : B a, false := take x : B a, absurd_not_true (not_exists_elim s1 x), s3 : ∃ y : (∀ x, B x), true := H in obtain (w : (∀ x, B x)) (Hw : true), from s3, let s4 : B a := w a in s2 s4) theorem exists_rem {A : (Type U)} (H : inhabited A) (p : Bool) : (∃ x : A, p) ↔ p := iff_intro (assume Hl : (∃ x : A, p), obtain (w : A) (Hw : p), from Hl, Hw) (assume Hr : p, inhabited_elim H (λ w, exists_intro w Hr)) theorem forall_rem {A : (Type U)} (H : inhabited A) (p : Bool) : (∀ x : A, p) ↔ p := iff_intro (assume Hl : (∀ x : A, p), inhabited_elim H (λ w, Hl w)) (assume Hr : p, take x, Hr) theorem not_and (a b : Bool) : ¬ (a ∧ b) ↔ ¬ a ∨ ¬ b := boolext (assume H, or_elim (em a) (assume Ha, or_elim (em b) (assume Hb, absurd_elim (¬ a ∨ ¬ b) (and_intro Ha Hb) H) (assume Hnb, or_intro_right (¬ a) Hnb)) (assume Hna, or_intro_left (¬ b) Hna)) (assume (H : ¬ a ∨ ¬ b) (N : a ∧ b), or_elim H (assume Hna, absurd (and_elim_left N) Hna) (assume Hnb, absurd (and_elim_right N) Hnb)) theorem not_and_elim {a b : Bool} (H : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := (not_and a b) ◂ H theorem not_or (a b : Bool) : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := boolext (assume H, or_elim (em a) (assume Ha, absurd_elim (¬ a ∧ ¬ b) (or_intro_left b Ha) H) (assume Hna, or_elim (em b) (assume Hb, absurd_elim (¬ a ∧ ¬ b) (or_intro_right a Hb) H) (assume Hnb, and_intro Hna Hnb))) (assume (H : ¬ a ∧ ¬ b) (N : a ∨ b), or_elim N (assume Ha, absurd Ha (and_elim_left H)) (assume Hb, absurd Hb (and_elim_right H))) theorem not_or_elim {a b : Bool} (H : ¬ (a ∨ b)) : ¬ a ∧ ¬ b := (not_or a b) ◂ H theorem not_implies (a b : Bool) : ¬ (a → b) ↔ a ∧ ¬ b := calc (¬ (a → b)) = ¬ (¬ a ∨ b) : { imp_or a b } ... = ¬ ¬ a ∧ ¬ b : not_or (¬ a) b ... = a ∧ ¬ b : congr2 (λ x, x ∧ ¬ b) (not_not_eq a) theorem and_imp (a b : Bool) : a ∧ b ↔ ¬ (a → ¬ b) := have H1 : a ∧ ¬ ¬ b ↔ ¬ (a → ¬ b), from symm (not_implies a (¬ b)), subst H1 (not_not_eq b) theorem not_implies_elim {a b : Bool} (H : ¬ (a → b)) : a ∧ ¬ b := (not_implies a b) ◂ H theorem eq_not_self (a : Bool) : (a = ¬ a) ↔ false := boolext (λ H, or_elim (em a) (λ Ha, absurd Ha (subst Ha H)) (λ Hna, absurd (subst Hna (symm H)) Hna)) (λ H, false_elim (a = ¬ a) H) theorem iff_not_self (a : Bool) : (a ↔ ¬ a) ↔ false := eq_not_self a theorem true_eq_false : (true = false) ↔ false := subst (eq_not_self true) not_true theorem true_iff_false : (true ↔ false) ↔ false := true_eq_false theorem false_eq_true : (false = true) ↔ false := subst (eq_not_self false) not_false theorem false_iff_true : (false ↔ true) ↔ false := false_eq_true theorem iff_true_right (a : Bool) : (a ↔ true) ↔ a := boolext (λ H, eqt_elim H) (λ H, eqt_intro H) theorem iff_false_right (a : Bool) : (a ↔ false) ↔ ¬ a := boolext (λ H, eqf_elim H) (λ H, eqf_intro H) add_rewrite eq_not_self iff_not_self true_eq_false true_iff_false false_eq_true false_iff_true iff_true_right iff_false_right theorem not_iff (a b : Bool) : ¬ (a ↔ b) ↔ (¬ a ↔ b) := or_elim (em b) (λ Hb, calc (¬ (a ↔ b)) = (¬ (a ↔ true)) : { eqt_intro Hb } ... = ¬ a : { iff_true_right a } ... = ¬ a ↔ true : { symm (iff_true_right (¬ a)) } ... = ¬ a ↔ b : { symm (eqt_intro Hb) }) (λ Hnb, calc (¬ (a ↔ b)) = (¬ (a ↔ false)) : { eqf_intro Hnb } ... = ¬ ¬ a : { iff_false_right a } ... = ¬ a ↔ false : { symm (iff_false_right (¬ a)) } ... = ¬ a ↔ b : { symm (eqf_intro Hnb) }) theorem not_iff_elim {a b : Bool} (H : ¬ (a ↔ b)) : (¬ a) ↔ b := (not_iff a b) ◂ H -- Congruence theorems for contextual simplification -- Simplify a → b, by first simplifying a to c using the fact that ¬ b is true, and then -- b to d using the fact that c is true theorem imp_congr_right {a b c d : Bool} (H_ac : ∀ (H_nb : ¬ b), a = c) (H_bd : ∀ (H_c : c), b = d) : (a → b) = (c → d) := or_elim (em b) (λ H_b : b, or_elim (em c) (λ H_c : c, calc (a → b) = (a → true) : { eqt_intro H_b } ... = true : imp_true_right a ... = (c → true) : symm (imp_true_right c) ... = (c → b) : { symm (eqt_intro H_b) } ... = (c → d) : { H_bd H_c }) (λ H_nc : ¬ c, calc (a → b) = (a → true) : { eqt_intro H_b } ... = true : imp_true_right a ... = (false → d) : symm (imp_false_left d) ... = (c → d) : { symm (eqf_intro H_nc) })) (λ H_nb : ¬ b, or_elim (em c) (λ H_c : c, calc (a → b) = (c → b) : { H_ac H_nb } ... = (c → d) : { H_bd H_c }) (λ H_nc : ¬ c, calc (a → b) = (c → b) : { H_ac H_nb } ... = (false → b) : { eqf_intro H_nc } ... = true : imp_false_left b ... = (false → d) : symm (imp_false_left d) ... = (c → d) : { symm (eqf_intro H_nc) })) -- Simplify a → b, by first simplifying b to d using the fact that a is true, and then -- b to d using the fact that ¬ d is true. -- This kind of congruence seems to be useful in very rare cases. theorem imp_congr_left {a b c d : Bool} (H_bd : ∀ (H_a : a), b = d) (H_ac : ∀ (H_nd : ¬ d), a = c) : (a → b) = (c → d) := or_elim (em a) (λ H_a : a, or_elim (em d) (λ H_d : d, calc (a → b) = (a → d) : { H_bd H_a } ... = (a → true) : { eqt_intro H_d } ... = true : imp_true_right a ... = (c → true) : symm (imp_true_right c) ... = (c → d) : { symm (eqt_intro H_d) }) (λ H_nd : ¬ d, calc (a → b) = (c → b) : { H_ac H_nd } ... = (c → d) : { H_bd H_a })) (λ H_na : ¬ a, or_elim (em d) (λ H_d : d, calc (a → b) = (false → b) : { eqf_intro H_na } ... = true : imp_false_left b ... = (c → true) : symm (imp_true_right c) ... = (c → d) : { symm (eqt_intro H_d) }) (λ H_nd : ¬ d, calc (a → b) = (false → b) : { eqf_intro H_na } ... = true : imp_false_left b ... = (false → d) : symm (imp_false_left d) ... = (a → d) : { symm (eqf_intro H_na) } ... = (c → d) : { H_ac H_nd })) -- (Common case) simplify a to c, and then b to d using the fact that c is true theorem imp_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_c : c), b = d) : (a → b) = (c → d) := imp_congr_right (λ H, H_ac) H_bd theorem or_congr_right {a b c d : Bool} (H_ac : ∀ (H_nb : ¬ b), a = c) (H_bd : ∀ (H_nc : ¬ c), b = d) : a ∨ b ↔ c ∨ d := have H1 : (¬ a → b) ↔ (¬ c → d), from imp_congr_right (λ H_nb : ¬ b, congr2 not (H_ac H_nb)) H_bd, calc (a ∨ b) = (¬ a → b) : or_imp _ _ ... = (¬ c → d) : H1 ... = c ∨ d : symm (or_imp _ _) theorem or_congr_left {a b c d : Bool} (H_bd : ∀ (H_na : ¬ a), b = d) (H_ac : ∀ (H_nd : ¬ d), a = c) : a ∨ b ↔ c ∨ d := have H1 : (¬ a → b) ↔ (¬ c → d), from imp_congr_left H_bd (λ H_nd : ¬ d, congr2 not (H_ac H_nd)), calc (a ∨ b) = (¬ a → b) : or_imp _ _ ... = (¬ c → d) : H1 ... = c ∨ d : symm (or_imp _ _) -- (Common case) simplify a to c, and then b to d using the fact that ¬ c is true theorem or_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_nc : ¬ c), b = d) : a ∨ b ↔ c ∨ d := or_congr_right (λ H, H_ac) H_bd theorem and_congr_right {a b c d : Bool} (H_ac : ∀ (H_b : b), a = c) (H_bd : ∀ (H_c : c), b = d) : a ∧ b ↔ c ∧ d := have H1 : ¬ (a → ¬ b) ↔ ¬ (c → ¬ d), from congr2 not (imp_congr_right (λ (H_nnb : ¬ ¬ b), H_ac (not_not_elim H_nnb)) (λ H_c : c, congr2 not (H_bd H_c))), calc (a ∧ b) = ¬ (a → ¬ b) : and_imp _ _ ... = ¬ (c → ¬ d) : H1 ... = c ∧ d : symm (and_imp _ _) theorem and_congr_left {a b c d : Bool} (H_bd : ∀ (H_a : a), b = d) (H_ac : ∀ (H_d : d), a = c) : a ∧ b ↔ c ∧ d := have H1 : ¬ (a → ¬ b) ↔ ¬ (c → ¬ d), from congr2 not (imp_congr_left (λ H_a : a, congr2 not (H_bd H_a)) (λ (H_nnd : ¬ ¬ d), H_ac (not_not_elim H_nnd))), calc (a ∧ b) = ¬ (a → ¬ b) : and_imp _ _ ... = ¬ (c → ¬ d) : H1 ... = c ∧ d : symm (and_imp _ _) -- (Common case) simplify a to c, and then b to d using the fact that c is true theorem and_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_c : c), b = d) : a ∧ b ↔ c ∧ d := and_congr_right (λ H, H_ac) H_bd theorem forall_or_distribute_right {A : (Type U)} (p : Bool) (φ : A → Bool) : (∀ x, p ∨ φ x) = (p ∨ ∀ x, φ x) := boolext (assume H : (∀ x, p ∨ φ x), or_elim (em p) (λ Hp : p, or_intro_left (∀ x, φ x) Hp) (λ Hnp : ¬ p, or_intro_right p (take x, resolve_right (H x) Hnp))) (assume H : (p ∨ ∀ x, φ x), take x, or_elim H (λ H1 : p, or_intro_left (φ x) H1) (λ H2 : (∀ x, φ x), or_intro_right p (H2 x))) theorem forall_or_distribute_left {A : Type} (p : Bool) (φ : A → Bool) : (∀ x, φ x ∨ p) = ((∀ x, φ x) ∨ p) := boolext (assume H : (∀ x, φ x ∨ p), or_elim (em p) (λ Hp : p, or_intro_right (∀ x, φ x) Hp) (λ Hnp : ¬ p, or_intro_left p (take x, resolve_left (H x) Hnp))) (assume H : (∀ x, φ x) ∨ p, take x, or_elim H (λ H1 : (∀ x, φ x), or_intro_left p (H1 x)) (λ H2 : p, or_intro_right (φ x) H2)) theorem forall_and_distribute {A : (Type U)} (φ ψ : A → Bool) : (∀ x, φ x ∧ ψ x) ↔ (∀ x, φ x) ∧ (∀ x, ψ x) := boolext (assume H : (∀ x, φ x ∧ ψ x), and_intro (take x, and_elim_left (H x)) (take x, and_elim_right (H x))) (assume H : (∀ x, φ x) ∧ (∀ x, ψ x), take x, and_intro (and_elim_left H x) (and_elim_right H x)) theorem exists_and_distribute_right {A : (Type U)} (p : Bool) (φ : A → Bool) : (∃ x, p ∧ φ x) ↔ p ∧ ∃ x, φ x := boolext (assume H : (∃ x, p ∧ φ x), obtain (w : A) (Hw : p ∧ φ w), from H, and_intro (and_elim_left Hw) (exists_intro w (and_elim_right Hw))) (assume H : (p ∧ ∃ x, φ x), obtain (w : A) (Hw : φ w), from (and_elim_right H), exists_intro w (and_intro (and_elim_left H) Hw)) theorem exists_or_distribute {A : (Type U)} (φ ψ : A → Bool) : (∃ x, φ x ∨ ψ x) ↔ (∃ x, φ x) ∨ (∃ x, ψ x) := boolext (assume H : (∃ x, φ x ∨ ψ x), obtain (w : A) (Hw : φ w ∨ ψ w), from H, or_elim Hw (λ Hw1 : φ w, or_intro_left (∃ x, ψ x) (exists_intro w Hw1)) (λ Hw2 : ψ w, or_intro_right (∃ x, φ x) (exists_intro w Hw2))) (assume H : (∃ x, φ x) ∨ (∃ x, ψ x), or_elim H (λ H1 : (∃ x, φ x), obtain (w : A) (Hw : φ w), from H1, exists_intro w (or_intro_left (ψ w) Hw)) (λ H2 : (∃ x, ψ x), obtain (w : A) (Hw : ψ w), from H2, exists_intro w (or_intro_right (φ w) Hw))) theorem eq_exists_intro {A : (Type U)} {P Q : A → Bool} (H : ∀ x : A, P x ↔ Q x) : (∃ x : A, P x) ↔ (∃ x : A, Q x) := boolext (assume Hex, obtain w Pw, from Hex, exists_intro w ((H w) ◂ Pw)) (assume Hex, obtain w Qw, from Hex, exists_intro w ((symm (H w)) ◂ Qw)) theorem not_forall (A : (Type U)) (P : A → Bool) : ¬ (∀ x : A, P x) ↔ (∃ x : A, ¬ P x) := boolext (assume H, by_contradiction (assume N : ¬ (∃ x, ¬ P x), absurd (take x, not_not_elim (not_exists_elim N x)) H)) (assume (H : ∃ x, ¬ P x) (N : ∀ x, P x), obtain w Hw, from H, absurd (N w) Hw) theorem not_forall_elim {A : (Type U)} {P : A → Bool} (H : ¬ (∀ x : A, P x)) : ∃ x : A, ¬ P x := (not_forall A P) ◂ H theorem exists_and_distribute_left {A : (Type U)} (p : Bool) (φ : A → Bool) : (∃ x, φ x ∧ p) ↔ (∃ x, φ x) ∧ p := calc (∃ x, φ x ∧ p) = (∃ x, p ∧ φ x) : eq_exists_intro (λ x, and_comm (φ x) p) ... = (p ∧ (∃ x, φ x)) : exists_and_distribute_right p φ ... = ((∃ x, φ x) ∧ p) : and_comm p (∃ x, φ x) theorem exists_imp_distribute {A : (Type U)} (φ ψ : A → Bool) : (∃ x, φ x → ψ x) ↔ ((∀ x, φ x) → (∃ x, ψ x)) := calc (∃ x, φ x → ψ x) = (∃ x, ¬ φ x ∨ ψ x) : eq_exists_intro (λ x, imp_or (φ x) (ψ x)) ... = (∃ x, ¬ φ x) ∨ (∃ x, ψ x) : exists_or_distribute _ _ ... = ¬ (∀ x, φ x) ∨ (∃ x, ψ x) : { symm (not_forall A φ) } ... = (∀ x, φ x) → (∃ x, ψ x) : symm (imp_or _ _) theorem forall_uninhabited {A : (Type U)} {B : A → Bool} (H : ¬ inhabited A) : ∀ x, B x := by_contradiction (assume N : ¬ (∀ x, B x), obtain w Hw, from not_forall_elim N, absurd (inhabited_intro w) H) theorem allext {A : (Type U)} {B C : A → Bool} (H : ∀ x : A, B x = C x) : (∀ x : A, B x) = (∀ x : A, C x) := boolext (assume Hl, take x, (H x) ◂ (Hl x)) (assume Hr, take x, (symm (H x)) ◂ (Hr x)) theorem proj1_congr {A : (Type U)} {B : A → (Type U)} {a b : sig x, B x} (H : a = b) : proj1 a = proj1 b := subst (refl (proj1 a)) H theorem proj2_congr {A B : (Type U)} {a b : A # B} (H : a = b) : proj2 a = proj2 b := subst (refl (proj2 a)) H theorem hproj2_congr {A : (Type U)} {B : A → (Type U)} {a b : sig x, B x} (H : a = b) : proj2 a == proj2 b := subst (hrefl (proj2 a)) H -- Up to this point, we proved all theorems using just reflexivity, substitution and case (proof by cases) -- Function extensionality axiom funext {A : (Type U)} {B : A → (Type U)} {f g : ∀ x : A, B x} (H : ∀ x : A, f x = g x) : f = g -- Eta is a consequence of function extensionality theorem eta {A : (Type U)} {B : A → (Type U)} (f : ∀ x : A, B x) : (λ x : A, f x) = f := funext (λ x : A, refl (f x)) -- Epsilon (Hilbert's operator) variable eps {A : (Type U)} (H : inhabited A) (P : A → Bool) : A alias ε : eps axiom eps_ax {A : (Type U)} (H : inhabited A) {P : A → Bool} (a : A) : P a → P (ε H P) theorem eps_th {A : (Type U)} {P : A → Bool} (a : A) : P a → P (ε (inhabited_intro a) P) := assume H : P a, @eps_ax A (inhabited_intro a) P a H theorem eps_singleton {A : (Type U)} (H : inhabited A) (a : A) : ε H (λ x, x = a) = a := let P := λ x, x = a, Ha : P a := refl a in eps_ax H a Ha -- A function space (∀ x : A, B x) is inhabited if forall a : A, we have inhabited (B a) theorem inhabited_dfun {A : (Type U)} {B : A → (Type U)} (Hn : ∀ a, inhabited (B a)) : inhabited (∀ x, B x) := inhabited_intro (λ x, ε (Hn x) (λ y, true)) theorem inhabited_fun (A : (Type U)) {B : (Type U)} (H : inhabited B) : inhabited (A → B) := inhabited_intro (λ x, ε H (λ y, true)) theorem exists_to_eps {A : (Type U)} {P : A → Bool} (H : ∃ x, P x) : P (ε (inhabited_ex_intro H) P) := obtain (w : A) (Hw : P w), from H, @eps_ax _ (inhabited_ex_intro H) P w Hw theorem axiom_of_choice {A : (Type U)} {B : A → (Type U)} {R : ∀ x : A, B x → Bool} (H : ∀ x, ∃ y, R x y) : ∃ f, ∀ x, R x (f x) := exists_intro (λ x, ε (inhabited_ex_intro (H x)) (λ y, R x y))-- witness for f (λ x, exists_to_eps (H x)) -- proof that witness satisfies ∀ x, R x (f x) theorem skolem_th {A : (Type U)} {B : A → (Type U)} {P : ∀ x : A, B x → Bool} : (∀ x, ∃ y, P x y) ↔ ∃ f, (∀ x, P x (f x)) := iff_intro (λ H : (∀ x, ∃ y, P x y), @axiom_of_choice _ _ P H) (λ H : (∃ f, (∀ x, P x (f x))), take x, obtain (fw : ∀ x, B x) (Hw : ∀ x, P x (fw x)), from H, exists_intro (fw x) (Hw x)) -- if-then-else expression, we define it using Hilbert's operator definition ite {A : (Type U)} (c : Bool) (a b : A) : A := ε (inhabited_intro a) (λ r, (c → r = a) ∧ (¬ c → r = b)) notation 45 if _ then _ else _ : ite theorem if_true {A : (Type U)} (a b : A) : (if true then a else b) = a := calc (if true then a else b) = ε (inhabited_intro a) (λ r, (true → r = a) ∧ (¬ true → r = b)) : refl (if true then a else b) ... = ε (inhabited_intro a) (λ r, r = a) : by simp ... = a : eps_singleton (inhabited_intro a) a theorem if_false {A : (Type U)} (a b : A) : (if false then a else b) = b := calc (if false then a else b) = ε (inhabited_intro a) (λ r, (false → r = a) ∧ (¬ false → r = b)) : refl (if false then a else b) ... = ε (inhabited_intro a) (λ r, r = b) : by simp ... = b : eps_singleton (inhabited_intro a) b theorem if_same {A : (Type U)} (c : Bool) (a: A) : (if c then a else a) = a := or_elim (em c) (λ H : c, calc (if c then a else a) = (if true then a else a) : { eqt_intro H } ... = a : if_true a a) (λ H : ¬ c, calc (if c then a else a) = (if false then a else a) : { eqf_intro H } ... = a : if_false a a) add_rewrite if_true if_false if_same theorem if_congr {A : (Type U)} {b c : Bool} {x y u v : A} (H_bc : b = c) (H_xu : ∀ (H_c : c), x = u) (H_yv : ∀ (H_nc : ¬ c), y = v) : (if b then x else y) = if c then u else v := or_elim (em c) (λ H_c : c, calc (if b then x else y) = if c then x else y : { H_bc } ... = if true then x else y : { eqt_intro H_c } ... = x : if_true _ _ ... = u : H_xu H_c ... = if true then u else v : symm (if_true _ _) ... = if c then u else v : { symm (eqt_intro H_c) }) (λ H_nc : ¬ c, calc (if b then x else y) = if c then x else y : { H_bc } ... = if false then x else y : { eqf_intro H_nc } ... = y : if_false _ _ ... = v : H_yv H_nc ... = if false then u else v : symm (if_false _ _) ... = if c then u else v : { symm (eqf_intro H_nc) }) theorem if_imp_then {a b c : Bool} (H : if a then b else c) : a → b := assume Ha : a, eqt_elim (calc b = if true then b else c : symm (if_true b c) ... = if a then b else c : { symm (eqt_intro Ha) } ... = true : eqt_intro H) theorem if_imp_else {a b c : Bool} (H : if a then b else c) : ¬ a → c := assume Hna : ¬ a, eqt_elim (calc c = if false then b else c : symm (if_false b c) ... = if a then b else c : { symm (eqf_intro Hna) } ... = true : eqt_intro H) theorem app_if_distribute {A B : (Type U)} (c : Bool) (f : A → B) (a b : A) : f (if c then a else b) = if c then f a else f b := or_elim (em c) (λ Hc : c , calc f (if c then a else b) = f (if true then a else b) : { eqt_intro Hc } ... = f a : { if_true a b } ... = if true then f a else f b : symm (if_true (f a) (f b)) ... = if c then f a else f b : { symm (eqt_intro Hc) }) (λ Hnc : ¬ c, calc f (if c then a else b) = f (if false then a else b) : { eqf_intro Hnc } ... = f b : { if_false a b } ... = if false then f a else f b : symm (if_false (f a) (f b)) ... = if c then f a else f b : { symm (eqf_intro Hnc) }) theorem eq_if_distribute_right {A : (Type U)} (c : Bool) (a b v : A) : (v = (if c then a else b)) = if c then v = a else v = b := app_if_distribute c (eq v) a b theorem eq_if_distribute_left {A : (Type U)} (c : Bool) (a b v : A) : ((if c then a else b) = v) = if c then a = v else b = v := app_if_distribute c (λ x, x = v) a b --same theorem as eqt_intro theorem imp_eq_true {b : Bool} : b → b = ⊤ := case _ (take H, refl _) (take H, false_elim _ H) b --same theorem as eqf_intro theorem not_imp_eq_false {b : Bool} : ¬ b → b = ⊥ := case (λx, ¬ x → x = ⊥) (take H, absurd_elim _ trivial H) (take H, refl _) b --rename to something which starts with "if"? theorem imp_if_eq {A : Type} {b : Bool} (H : b) (a a' : A) : (if b then a else a') = a := calc (if b then a else a') = (if ⊤ then a else a') : {imp_eq_true H} ... = a : if_true _ _ theorem not_imp_if_eq {A : Type} {b : Bool} (H : ¬ b) (a a' : A) : (if b then a else a') = a' := calc (if b then a else a') = (if ⊥ then a else a') : {not_imp_eq_false H} ... = a' : if_false _ _ set_opaque exists true set_opaque not true set_opaque or true set_opaque and true set_opaque implies true set_opaque ite true set_opaque eq true definition injective {A B : (Type U)} (f : A → B) := ∀ x1 x2, f x1 = f x2 → x1 = x2 definition non_surjective {A B : (Type U)} (f : A → B) := ∃ y, ∀ x, ¬ f x = y -- The set of individuals, we need to assert the existence of one infinite set variable ind : Type -- ind is infinite, i.e., there is a function f s.t. f is injective, and not surjective axiom infinity : ∃ f : ind → ind, injective f ∧ non_surjective f -- Pair extensionality axiom pairext {A : (Type U)} {B : A → (Type U)} (a b : sig x, B x) (H1 : proj1 a = proj1 b) (H2 : proj2 a == proj2 b) : a = b theorem pair_proj_eq {A : (Type U)} {B : A → (Type U)} (a : sig x, B x) : pair (proj1 a) (proj2 a) = a := have Heq1 : proj1 (pair (proj1 a) (proj2 a)) = proj1 a, from refl (proj1 a), have Heq2 : proj2 (pair (proj1 a) (proj2 a)) == proj2 a, from hrefl (proj2 a), show pair (proj1 a) (proj2 a) = a, from pairext (pair (proj1 a) (proj2 a)) a Heq1 Heq2 theorem pair_congr {A : (Type U)} {B : A → (Type U)} {a a' : A} {b : B a} {b' : B a'} (Ha : a = a') (Hb : b == b') : (pair a b) = (pair a' b') := have Heq1 : proj1 (pair a b) = proj1 (pair a' b'), from Ha, have Heq2 : proj2 (pair a b) == proj2 (pair a' b'), from Hb, show (pair a b) = (pair a' b'), from pairext (pair a b) (pair a' b') Heq1 Heq2 theorem pairext_proj {A B : (Type U)} {p : A # B} {a : A} {b : B} (H1 : proj1 p = a) (H2 : proj2 p = b) : p = (pair a b) := pairext p (pair a b) H1 (to_heq H2) theorem hpairext_proj {A : (Type U)} {B : A → (Type U)} {p : sig x, B x} {a : A} {b : B a} (H1 : proj1 p = a) (H2 : proj2 p == b) : p = (pair a b) := pairext p (pair a b) H1 H2 -- -- temporary definition of the product of two types - will be eliminated with Lean 0.2 -- definition tprod (A B : Type) := A ⨯ B infix 60 ## : tprod definition tpair {A B : Type} (a : A) (b : B) : A ## B := pair a b definition tproj1 {A B : Type} (p : A ## B) := proj1 p definition tproj2 {A B : Type} (p : A ## B) := proj2 p theorem tproj1_tpair {A B : Type} (a : A) (b : B) : tproj1 (tpair a b) = a := refl _ theorem tproj2_tpair {A B : Type} (a : A) (b : B) : tproj2 (tpair a b) = b := refl _ theorem tpair_tproj_eq {A B : Type} (a : A ## B) : tpair (tproj1 a) (tproj2 a) = a := pair_proj_eq a theorem tpairext {A B : Type} {a b : A ## B} (H1 : tproj1 a = tproj1 b) (H2 : tproj2 a = tproj2 b) : a = b := calc a = tpair (tproj1 a) (tproj2 a) : symm (tpair_tproj_eq a) ... = tpair (tproj1 b) (tproj2 a) : {H1} ... = tpair (tproj1 b) (tproj2 b) : {H2} ... = b : tpair_tproj_eq b theorem tpair_congr {A B : Type} {a a' : A} {b b' : B} (Ha : a = a') (Hb : b = b') : (tpair a b) = (tpair a' b') := subst (congr2 _ Ha) Hb theorem tpairext_proj {A B : Type} {p : A ## B} {a : A} {b : B} (H1 : tproj1 p = a) (H2 : tproj2 p = b) : p = (tpair a b) := pairext_proj H1 H2 theorem htpairext_proj {A B : Type} {p : A ## B} {a : A} {b : B} (H1 : tproj1 p = a) (H2 : tproj2 p == b) : p = (tpair a b) := hpairext_proj H1 H2 set_opaque tprod true set_opaque tpair true set_opaque tproj1 true set_opaque tproj2 true add_rewrite tproj1_tpair tproj2_tpair -- Heterogeneous equality axioms and theorems -- We can "type-cast" an A expression into a B expression, if we can prove that A == B -- Remark: we use A == B instead of A = B, because A = B would be type incorrect. -- A = B is actually (@eq (Type U) A B), which is type incorrect because -- the first argument of eq must have type (Type U) and the type of (Type U) is (Type U+1) variable cast {A B : (Type U+1)} : A == B → A → B axiom cast_heq {A B : (Type U+1)} (H : A == B) (a : A) : cast H a == a -- Heterogeneous equality satisfies the usual properties: -- symmetry, transitivity, congruence, function extensionality, ... -- Heterogeneous version of subst axiom hsubst {A B : (Type U+1)} {a : A} {b : B} (P : ∀ T : (Type U+1), T → Bool) : P A a → a == b → P B b theorem hsymm {A B : (Type U+1)} {a : A} {b : B} (H : a == b) : b == a := hsubst (λ (T : (Type U+1)) (x : T), x == a) (hrefl a) H theorem htrans {A B C : (Type U+1)} {a : A} {b : B} {c : C} (H1 : a == b) (H2 : b == c) : a == c := hsubst (λ (T : (Type U+1)) (x : T), a == x) H1 H2 axiom hcongr {A A' : (Type U+1)} {B : A → (Type U+1)} {B' : A' → (Type U+1)} {f : ∀ x, B x} {f' : ∀ x, B' x} {a : A} {a' : A'} : f == f' → a == a' → f a == f' a' axiom hfunext {A A' : (Type U+1)} {B : A → (Type U+1)} {B' : A' → (Type U+1)} {f : ∀ x, B x} {f' : ∀ x, B' x} : A == A' → (∀ x x', x == x' → f x == f' x') → f == f' axiom hpiext {A A' : (Type U+1)} {B : A → (Type U+1)} {B' : A' → (Type U+1)} : A == A' → (∀ x x', x == x' → B x == B' x') → (∀ x, B x) == (∀ x, B' x) axiom hsigext {A A' : (Type U+1)} {B : A → (Type U+1)} {B' : A' → (Type U+1)} : A == A' → (∀ x x', x == x' → B x == B' x') → (sig x, B x) == (sig x, B' x) -- Heterogeneous version of the allext theorem theorem hallext {A A' : (Type U+1)} {B : A → Bool} {B' : A' → Bool} (Ha : A == A') (Hb : ∀ x x', x == x' → B x = B' x') : (∀ x, B x) = (∀ x, B' x) := to_eq (hpiext Ha (λ x x' Heq, to_heq (Hb x x' Heq))) -- Simpler version of hfunext axiom, we use it to build proofs theorem hsfunext {A : (Type U)} {B B' : A → (Type U)} {f : ∀ x, B x} {f' : ∀ x, B' x} : (∀ x, f x == f' x) → f == f' := λ Hb, hfunext (hrefl A) (λ (x x' : A) (Heq : x == x'), let s1 : f x == f' x := Hb x, s2 : f' x == f' x' := hcongr (hrefl f') Heq in htrans s1 s2) theorem heq_congr {A B : (Type U)} {a a' : A} {b b' : B} (H1 : a = a') (H2 : b = b') : (a == b) = (a' == b') := calc (a == b) = (a' == b) : { H1 } ... = (a' == b') : { H2 } theorem hheq_congr {A A' B B' : (Type U+1)} {a : A} {a' : A'} {b : B} {b' : B'} (H1 : a == a') (H2 : b == b') : (a == b) = (a' == b') := have Heq1 : (a == b) = (a' == b), from (hsubst (λ (T : (Type U+1)) (x : T), (a == b) = (x == b)) (refl (a == b)) H1), have Heq2 : (a' == b) = (a' == b'), from (hsubst (λ (T : (Type U+1)) (x : T), (a' == b) = (a' == x)) (refl (a' == b)) H2), show (a == b) = (a' == b'), from trans Heq1 Heq2 theorem type_eq {A B : (Type U)} {a : A} {b : B} (H : a == b) : A == B := hsubst (λ (T : (Type U+1)) (x : T), A == T) (hrefl A) H -- Some theorems that are useful for applying simplifications. theorem cast_eq {A : (Type U)} (H : A == A) (a : A) : cast H a = a := to_eq (cast_heq H a) theorem cast_trans {A B C : (Type U)} (Hab : A == B) (Hbc : B == C) (a : A) : cast Hbc (cast Hab a) = cast (htrans Hab Hbc) a := have Heq1 : cast Hbc (cast Hab a) == cast Hab a, from cast_heq Hbc (cast Hab a), have Heq2 : cast Hab a == a, from cast_heq Hab a, have Heq3 : cast (htrans Hab Hbc) a == a, from cast_heq (htrans Hab Hbc) a, show cast Hbc (cast Hab a) = cast (htrans Hab Hbc) a, from to_eq (htrans (htrans Heq1 Heq2) (hsymm Heq3)) theorem cast_pull {A : (Type U)} {B B' : A → (Type U)} (f : ∀ x, B x) (a : A) (Hb : (∀ x, B x) == (∀ x, B' x)) (Hba : (B a) == (B' a)) : cast Hb f a = cast Hba (f a) := have s1 : cast Hb f a == f a, from hcongr (cast_heq Hb f) (hrefl a), have s2 : cast Hba (f a) == f a, from cast_heq Hba (f a), show cast Hb f a = cast Hba (f a), from to_eq (htrans s1 (hsymm s2)) -- Proof irrelevance is true in the set theoretic model we have for Lean. axiom proof_irrel {a : Bool} (H1 H2 : a) : H1 = H2 -- A more general version of proof_irrel that can be be derived using proof_irrel, heq axioms and boolext/iff_intro theorem hproof_irrel {a b : Bool} (H1 : a) (H2 : b) : H1 == H2 := let Hab : a == b := to_heq (iff_intro (assume Ha, H2) (assume Hb, H1)), H1b : b := cast Hab H1, H1_eq_H1b : H1 == H1b := hsymm (cast_heq Hab H1), H1b_eq_H2 : H1b == H2 := to_heq (proof_irrel H1b H2) in htrans H1_eq_H1b H1b_eq_H2
7375798543c61cc1783b64c68c6cfd9dea452ae9
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/termParserAttr.lean
0afa9201db2e673a994bd925493a55d9f8ad38cd
[ "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
2,125
lean
import Lean open Lean open Lean.Elab def runCore (input : String) (failIff : Bool := true) : CoreM Unit := do let env ← getEnv; let opts ← getOptions; let (env, messages) ← process input env opts; messages.toList.forM fun msg => do IO.println (← msg.toString) if failIff && messages.hasErrors then throwError "errors have been found"; if !failIff && !messages.hasErrors then throwError "there are no errors"; pure () open Lean.Parser @[termParser] def tst := leading_parser "(|" >> termParser >> Parser.optional (symbol ", " >> termParser) >> "|)" def tst2 : Parser := symbol "(||" >> termParser >> symbol "||)" @[termParser] def boo : ParserDescr := ParserDescr.node `boo 10 (ParserDescr.binary `andthen (ParserDescr.symbol "[|") (ParserDescr.binary `andthen (ParserDescr.cat `term 0) (ParserDescr.symbol "|]"))) @[termParser] def boo2 : ParserDescr := ParserDescr.node `boo2 10 (ParserDescr.parser `tst2) open Lean.Elab.Term @[termElab tst] def elabTst : TermElab := adaptExpander $ fun stx => match stx with | `((| $e |)) => pure e | _ => throwUnsupportedSyntax @[termElab boo] def elabBoo : TermElab := fun stx expected? => elabTerm (stx.getArg 1) expected? @[termElab boo2] def elabBool2 : TermElab := adaptExpander $ fun stx => match stx with | `((|| $e ||)) => `($e + 1) | _ => throwUnsupportedSyntax #eval runCore "#check [| @id.{1} Nat |]" #eval runCore "#check (| id 1 |)" #eval runCore "#check (|| id 1 ||)" -- #eval run "#check (| id 1, id 1 |)" -- it will fail @[termElab tst] def elabTst2 : TermElab := adaptExpander $ fun stx => match stx with | `((| $e1, $e2 |)) => `(($e1, $e2)) | _ => throwUnsupportedSyntax -- Now both work #eval runCore "#check (| id 1 |)" #eval runCore "#check (| id 1, id 2 |)" declare_syntax_cat foo syntax "⟨|" term "|⟩" : foo syntax term : foo syntax term ">>>" term : foo syntax (name := tst3) "FOO " foo : term macro_rules | `(FOO ⟨| $t |⟩) => `($t+1) | `(FOO $t:term) => `($t) | `(FOO $t:term >>> $r) => `($t * $r) #check FOO ⟨| id 1 |⟩ #check FOO 1 #check FOO 1 >>> 2
10e71e686d903637aa636e4e0a5937283fce5ef9
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Elab/StructInst.lean
47e9d0c186b2df1ddf6ac12beb45675ccf0312c4
[ "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
34,167
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.FindExpr import Lean.Parser.Term import Lean.Elab.App import Lean.Elab.Binders namespace Lean.Elab.Term.StructInst open Std (HashMap) open Meta /- Structure instances are of the form: "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optEllipsis >> optional (" : " >> termParser) >> " }" -/ @[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx => let expectedArg := stx[4] if expectedArg.isNone then Macro.throwUnsupported else let expected := expectedArg[1] let stxNew := stx.setArg 4 mkNullNode `(($stxNew : $expected)) /- If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`. Note that this one is not a `Macro` because we need to access the local context. -/ private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) := withFreshMacroScope do let sourceOpt := stx[1] if sourceOpt.isNone then pure none else let source := sourceOpt[0] match (← isLocalIdent? source) with | some _ => pure none | none => let src ← `(src) let sourceOpt := sourceOpt.setArg 0 src let stxNew := stx.setArg 1 sourceOpt `(let src := $source; $stxNew) inductive Source where | none -- structure instance source has not been provieded | implicit (stx : Syntax) -- `..` | explicit (stx : Syntax) (src : Expr) -- `src with` deriving Inhabited def Source.isNone : Source → Bool | Source.none => true | _ => false def setStructSourceSyntax (structStx : Syntax) : Source → Syntax | Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode | Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx | Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode private def getStructSource (stx : Syntax) : TermElabM Source := withRef stx do let explicitSource := stx[1] let implicitSource := stx[3] if explicitSource.isNone && implicitSource[0].isNone then return Source.none else if explicitSource.isNone then return Source.implicit implicitSource else if implicitSource[0].isNone then let fvar? ← isLocalIdent? explicitSource[0] match fvar? with | none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here | some src => return Source.explicit explicitSource src else throwError "invalid structure instance `with` and `..` cannot be used together" /- We say a `{ ... }` notation is a `modifyOp` if it contains only one ``` def structInstArrayRef := parser! "[" >> termParser >>"]" ``` -/ private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do let s? ← stx[2].getArgs.foldlM (init := none) fun s? p => /- p is of the form `(group (structInstField >> optional ", "))` -/ let arg := p[0] /- Remark: the syntax for `structInstField` is ``` def structInstLVal := parser! (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstField := parser! structInstLVal >> " := " >> termParser ``` -/ let lval := arg[0] let k := lval[0].getKind if k == `Lean.Parser.Term.structInstArrayRef then match s? with | none => pure (some arg) | some s => if s.getKind == `Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid {...} notation, at most one `[..]` at a given level" else throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level" else match s? with | none => pure (some arg) | some s => if s.getKind == `Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level" else pure s? match s? with | none => pure none | some s => if s[0][0].getKind == `Lean.Parser.Term.structInstArrayRef then pure s? else pure none private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let cont (val : Syntax) : TermElabM Expr := do let lval := modifyOp[0][0] let idx := lval[1] let self := source[0] let stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val)) trace[Elab.struct.modifyOp]! "{stx}\n===>\n{stxNew}" withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? trace[Elab.struct.modifyOp]! "{modifyOp}\nSource: {source}" let rest := modifyOp[0][1] if rest.isNone then cont modifyOp[2] else let s ← `(s) let valFirst := rest[0] let valFirst := if valFirst.getKind == `Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1] let restArgs := rest.getArgs let valRest := mkNullNode restArgs[1:restArgs.size] let valField := modifyOp.setArg 0 <| Syntax.node ``Parser.Term.structInstLVal #[valFirst, valRest] let valSource := source.modifyArg 0 fun _ => s let val := stx.setArg 1 valSource let val := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]] trace[Elab.struct.modifyOp]! "{stx}\nval: {val}" cont val /- Get structure name and elaborate explicit source (if available) -/ private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name := do tryPostponeIfNoneOrMVar expectedType? let useSource : Unit → TermElabM Name := fun _ => match sourceView, expectedType? with | Source.explicit _ src, _ => do let srcType ← inferType src let srcType ← whnf srcType tryPostponeIfMVar srcType match srcType.getAppFn with | Expr.const constName _ _ => pure constName | _ => throwUnexpectedExpectedType srcType "source" | _, some expectedType => throwUnexpectedExpectedType expectedType | _, none => throwUnknownExpectedType match expectedType? with | none => useSource () | some expectedType => let expectedType ← whnf expectedType match expectedType.getAppFn with | Expr.const constName _ _ => pure constName | _ => useSource () where throwUnknownExpectedType := throwError! "invalid \{...} notation, expected type is not known" throwUnexpectedExpectedType type (kind := "expected") := do let type ← instantiateMVars type if type.getAppFn.isMVar then throwUnknownExpectedType else throwError! "invalid \{...} notation, {kind} type is not of the form (C ...){indentExpr type}" inductive FieldLHS where | fieldName (ref : Syntax) (name : Name) | fieldIndex (ref : Syntax) (idx : Nat) | modifyOp (ref : Syntax) (index : Syntax) deriving Inhabited instance : ToFormat FieldLHS := ⟨fun lhs => match lhs with | FieldLHS.fieldName _ n => fmt n | FieldLHS.fieldIndex _ i => fmt i | FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩ inductive FieldVal (σ : Type) where | term (stx : Syntax) : FieldVal σ | nested (s : σ) : FieldVal σ | default : FieldVal σ -- mark that field must be synthesized using default value deriving Inhabited structure Field (σ : Type) where ref : Syntax lhs : List FieldLHS val : FieldVal σ expr? : Option Expr := none deriving Inhabited def Field.isSimple {σ} : Field σ → Bool | { lhs := [_], .. } => true | _ => false inductive Struct where | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source) deriving Inhabited abbrev Fields := List (Field Struct) /- true if all fields of the given structure are marked as `default` -/ partial def Struct.allDefault : Struct → Bool | ⟨_, _, fields, _⟩ => fields.all fun ⟨_, _, val, _⟩ => match val with | FieldVal.term _ => false | FieldVal.default => true | FieldVal.nested s => allDefault s def Struct.ref : Struct → Syntax | ⟨ref, _, _, _⟩ => ref def Struct.structName : Struct → Name | ⟨_, structName, _, _⟩ => structName def Struct.fields : Struct → Fields | ⟨_, _, fields, _⟩ => fields def Struct.source : Struct → Source | ⟨_, _, _, s⟩ => s def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format := Format.joinSep field.lhs " . " ++ " := " ++ match field.val with | FieldVal.term v => v.prettyPrint | FieldVal.nested s => formatStruct s | FieldVal.default => "<default>" partial def formatStruct : Struct → Format | ⟨_, structName, fields, source⟩ => let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", " match source with | Source.none => "{" ++ fieldsFmt ++ "}" | Source.implicit _ => "{" ++ fieldsFmt ++ " .. }" | Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}" instance : ToFormat Struct := ⟨formatStruct⟩ instance : ToString Struct := ⟨toString ∘ format⟩ instance : ToFormat (Field Struct) := ⟨formatField formatStruct⟩ instance : ToString (Field Struct) := ⟨toString ∘ format⟩ /- Recall that `structInstField` elements have the form ``` def structInstField := parser! structInstLVal >> " := " >> termParser def structInstLVal := parser! (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstArrayRef := parser! "[" >> termParser >>"]" ``` -/ -- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName` def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax | FieldLHS.modifyOp stx _ => stx | FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkNullNode #[mkAtomFrom stx ".", mkIdentFrom stx name] | FieldLHS.fieldIndex stx _ => if first then stx else mkNullNode #[mkAtomFrom stx ".", stx] def FieldVal.toSyntax : FieldVal Struct → Syntax | FieldVal.term stx => stx | _ => unreachable! def Field.toSyntax : Field Struct → Syntax | field => let stx := field.ref let stx := stx.setArg 2 field.val.toSyntax match field.lhs with | first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ] | _ => unreachable! private def toFieldLHS (stx : Syntax) : Except String FieldLHS := if stx.getKind == `Lean.Parser.Term.structInstArrayRef then return FieldLHS.modifyOp stx stx[1] else -- Note that the representation of the first field is different. let stx := if stx.getKind == nullKind then stx[1] else stx if stx.isIdent then return FieldLHS.fieldName stx stx.getId.eraseMacroScopes else match stx.isFieldIdx? with | some idx => return FieldLHS.fieldIndex stx idx | none => throw "unexpected structure syntax" private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : Except String Struct := do /- Recall that `stx` is of the form ``` parser! "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let fieldsStx := stx[2].getArgs.map (·[0]) let fields ← fieldsStx.toList.mapM fun fieldStx => do let val := fieldStx[2] let first ← toFieldLHS fieldStx[0][0] let rest ← fieldStx[0][1].getArgs.toList.mapM toFieldLHS pure { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct } pure ⟨stx, structName, fields, source⟩ def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct := match s with | ⟨ref, structName, fields, source⟩ => return ⟨ref, structName, (← f fields), source⟩ @[inline] def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct := Id.run <| s.modifyFieldsM f def Struct.setFields (s : Struct) (fields : Fields) : Struct := s.modifyFields fun _ => fields private def expandCompositeFields (s : Struct) : Struct := s.modifyFields fun fields => fields.map fun field => match field with | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } => let newEntries := n.components.map <| FieldLHS.fieldName ref { field with lhs := newEntries ++ rest } | _ => field private def expandNumLitFields (s : Struct) : TermElabM Struct := s.modifyFieldsM fun fields => do let env ← getEnv let fieldNames := getStructureFields env s.structName fields.mapM fun field => match field with | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } => if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0" else if idx > fieldNames.size then throwErrorAt! ref "invalid field index, structure has only #{fieldNames.size} fields" else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest } | _ => pure field /- For example, consider the following structures: ``` structure A where x : Nat structure B extends A where y : Nat structure C extends B where z : Bool ``` This method expands parent structure fields using the path to the parent structure. For example, ``` { x := 0, y := 0, z := true : C } ``` is expanded into ``` { toB.toA.x := 0, toB.y := 0, z := true : C } ``` -/ private def expandParentFields (s : Struct) : TermElabM Struct := do let env ← getEnv s.modifyFieldsM fun fields => fields.mapM fun field => match field with | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } => match findField? env s.structName fieldName with | none => throwErrorAt! ref "'{fieldName}' is not a field of structure '{s.structName}'" | some baseStructName => if baseStructName == s.structName then pure field else match getPathToBaseStructure? env baseStructName s.structName with | some path => do let path := path.map fun funName => match funName with | Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s) | _ => unreachable! pure { field with lhs := path ++ field.lhs } | _ => throwErrorAt! ref "failed to access field '{fieldName}' in parent structure" | _ => pure field private abbrev FieldMap := HashMap Name Fields private def mkFieldMap (fields : Fields) : TermElabM FieldMap := fields.foldlM (init := {}) fun fieldMap field => match field.lhs with | FieldLHS.fieldName _ fieldName :: rest => match fieldMap.find? fieldName with | some (prevField::restFields) => if field.isSimple || prevField.isSimple then throwErrorAt! field.ref "field '{fieldName}' has already beed specified" else return fieldMap.insert fieldName (field::prevField::restFields) | _ => return fieldMap.insert fieldName [field] | _ => unreachable! private def isSimpleField? : Fields → Option (Field Struct) | [field] => if field.isSimple then some field else none | _ => none private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do match fieldNames.findIdx? fun n => n == fieldName with | some idx => pure idx | none => throwError! "field '{fieldName}' is not a valid field of '{structName}'" private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax := Syntax.node `Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName] private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source := match src with | Source.explicit stx src => do let idx ← getFieldIdx structName fieldNames fieldName let stx := stx.modifyArg 0 fun stx => mkProjStx stx fieldName return Source.explicit stx (mkProj structName idx src) | s => return s @[specialize] private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName withRef s.ref do s.modifyFieldsM fun fields => do let fieldMap ← mkFieldMap fields fieldMap.toList.mapM fun ⟨fieldName, fields⟩ => do match isSimpleField? fields with | some field => pure field | none => let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! } let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let field := fields.head! match Lean.isSubobjectField? env s.structName fieldName with | some substructName => let substruct := Struct.mk s.ref substructName substructFields substructSource let substruct ← expandStruct substruct pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct } | none => do -- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them. let valStx := s.ref -- construct substructure syntax using s.ref as template let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type let args := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode] let valStx := valStx.setArg 2 (mkNullNode args) let valStx := setStructSourceSyntax valStx substructSource pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx } def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) := fields.find? fun field => match field.lhs with | [FieldLHS.fieldName _ n] => n == fieldName | _ => false @[specialize] private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName let ref := s.ref withRef ref do let fields ← fieldNames.foldlM (init := []) fun fields fieldName => do match findField? s.fields fieldName with | some field => return field::fields | none => let addField (val : FieldVal Struct) : TermElabM Fields := do return { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields match Lean.isSubobjectField? env s.structName fieldName with | some substructName => do let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let substruct := Struct.mk s.ref substructName [] substructSource let substruct ← expandStruct substruct addField (FieldVal.nested substruct) | none => match s.source with | Source.none => addField FieldVal.default | Source.implicit _ => addField (FieldVal.term (mkHole s.ref)) | Source.explicit stx _ => -- stx is of the form `optional (try (termParser >> "with"))` let src := stx[0] let val := mkProjStx src fieldName addField (FieldVal.term val) return s.setFields fields.reverse private partial def expandStruct (s : Struct) : TermElabM Struct := do let s := expandCompositeFields s let s ← expandNumLitFields s let s ← expandParentFields s let s ← groupFields expandStruct s addMissingFields expandStruct s structure CtorHeaderResult where ctorFn : Expr ctorFnType : Expr instMVars : Array MVarId := #[] private def mkCtorHeaderAux : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult | 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars } | n+1, type, ctorFn, instMVars => do let type ← whnfForall type match type with | Expr.forallE _ d b c => match c.binderInfo with | BinderInfo.instImplicit => let a ← mkFreshExprMVar d MetavarKind.synthetic mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!) | _ => let a ← mkFreshExprMVar d mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars | _ => throwError "unexpected constructor type" private partial def getForallBody : Nat → Expr → Option Expr | i+1, Expr.forallE _ _ b _ => getForallBody i b | i+1, _ => none | 0, type => type private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit := match expectedType? with | none => pure () | some expectedType => do match getForallBody numFields type with | none => pure () | some typeBody => unless typeBody.hasLooseBVars do discard <| isDefEq expectedType typeBody private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do let us ← ctorVal.levelParams.mapM fun _ => mkFreshLevelMVar let val := Lean.mkConst ctorVal.name us let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams us let r ← mkCtorHeaderAux ctorVal.numParams type val #[] propagateExpectedType r.ctorFnType ctorVal.numFields expectedType? synthesizeAppInstMVars r.instMVars pure r def markDefaultMissing (e : Expr) : Expr := mkAnnotation `structInstDefault e def defaultMissing? (e : Expr) : Option Expr := annotation? `structInstDefault e def throwFailedToElabField {α} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α := throwError! "failed to elaborate field '{fieldName}' of '{structName}, {msgData}" def trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do if !s.allDefault then pure none else try synthInstance? expectedType catch _ => pure none private partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr × Struct) := withRef s.ref do let env ← getEnv let ctorVal := getStructureCtor env s.structName let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType? let (e, _, fields) ← s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field => match field.lhs with | [FieldLHS.fieldName ref fieldName] => do let type ← whnfForall type match type with | Expr.forallE _ d b c => let cont (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo { lctx := (← getLCtx), val := val, name := fieldName, stx := ref } let e := mkApp e val let type := b.instantiate1 val let field := { field with expr? := some val } pure (e, type, field::fields) match field.val with | FieldVal.term stx => cont (← elabTermEnsuringType stx d) field | FieldVal.nested s => do -- if all fields of `s` are marked as `default`, then try to synthesize instance match (← trySynthStructInstance? s d) with | some val => cont val { field with val := FieldVal.term (mkHole field.ref) } | none => do let (val, sNew) ← elabStruct s (some d); let val ← ensureHasType d val; cont val { field with val := FieldVal.nested sNew } | FieldVal.default => do let val ← withRef field.ref <| mkFreshExprMVar (some d); cont (markDefaultMissing val) field | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!"unexpected constructor type{indentExpr type}" | _ => throwErrorAt field.ref "unexpected unexpanded structure field" pure (e, s.setFields fields.reverse) namespace DefaultFields structure Context where -- We must search for default values overriden in derived structures structs : Array Struct := #[] allStructNames : Array Name := #[] /-- Consider the following example: ``` structure A where x : Nat := 1 structure B extends A where y : Nat := x + 1 x := y + 1 structure C extends B where z : Nat := 2*y x := z + 3 ``` And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`. We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2. The field `maxDistance` specifies the maximum distance considered in a round of Default field computation. Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0. The fixpoint for setting default values works in the following way. - Keep computing default values using `maxDistance == 0`. - We increase `maxDistance` whenever we failed to compute a new default value in a round. - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value. We use depth-first search. - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above). -/ maxDistance : Nat := 0 structure State where progress : Bool := false partial def collectStructNames (struct : Struct) (names : Array Name) : Array Name := let names := names.push struct.structName struct.fields.foldl (init := names) fun names field => match field.val with | FieldVal.nested struct => collectStructNames struct names | _ => names partial def getHierarchyDepth (struct : Struct) : Nat := struct.fields.foldl (init := 0) fun max field => match field.val with | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1) | _ => max partial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) := struct.fields.findSome? fun field => match field.val with | FieldVal.nested struct => findDefaultMissing? mctx struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field | _ => none def getFieldName (field : Field Struct) : Name := match field.lhs with | [FieldLHS.fieldName _ fieldName] => fieldName | _ => unreachable! abbrev M := ReaderT Context (StateRefT State TermElabM) def isRoundDone : M Bool := do return (← get).progress && (← read).maxDistance > 0 def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr := struct.fields.findSome? fun field => if getFieldName field == fieldName then field.expr? else none partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr) | Expr.lam n d b c => withRef struct.ref do if c.binderInfo.isExplicit then let fieldName := n match getFieldValue? struct fieldName with | none => pure none | some val => let valType ← inferType val if (← isDefEq valType d) then mkDefaultValueAux? struct (b.instantiate1 val) else pure none else let arg ← mkFreshExprMVar d mkDefaultValueAux? struct (b.instantiate1 arg) | e => if e.isAppOfArity `id 2 then pure (some e.appArg!) else pure (some e) def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) := withRef struct.ref do let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us) /-- If `e` is a projection function of one of the given structures, then reduce it -/ def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name _ _ => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if structNames.contains structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none /-- Reduce default value. It performs beta reduction and projections of the given structures. -/ partial def reduce (structNames : Array Name) : Expr → MetaM Expr | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (← reduce structNames b) | e@(Expr.forallE _ _ _ _) => forallTelescope e fun xs b => do mkForallFVars xs (← reduce structNames b) | e@(Expr.letE _ _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLetFVars xs (← reduce structNames b) | e@(Expr.proj _ i b _) => do match (← Meta.project? b i) with | some r => reduce structNames r | none => return e.updateProj! (← reduce structNames b) | e@(Expr.app f _ _) => do match (← reduceProjOf? structNames e) with | some r => reduce structNames r | none => let f := f.getAppFn let f' ← reduce structNames f if f'.isLambda then let revArgs := e.getAppRevArgs reduce structNames (f'.betaRev revArgs) else let args ← e.getAppArgs.mapM (reduce structNames) return (mkAppN f' args) | e@(Expr.mdata _ b _) => do let b ← reduce structNames b if (defaultMissing? e).isSome && !b.isMVar then return b else return e.updateMData! b | e@(Expr.mvar mvarId _) => do match (← getExprMVarAssignment? mvarId) with | some val => if val.isMVar then reduce structNames val else pure val | none => return e | e => return e partial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool := let rec loop (i : Nat) (dist : Nat) := do if dist > maxDistance then pure false else if h : i < structs.size then do let struct := structs.get ⟨i, h⟩ let defaultName := struct.structName ++ fieldName ++ `_default let env ← getEnv match env.find? defaultName with | some cinfo@(ConstantInfo.defnInfo defVal) => do let mctx ← getMCtx let val? ← mkDefaultValue? struct cinfo match val? with | none => do setMCtx mctx; loop (i+1) (dist+1) | some val => do let val ← reduce allStructNames val match val.find? fun e => (defaultMissing? e).isSome with | some _ => setMCtx mctx; loop (i+1) (dist+1) | none => let mvarDecl ← getMVarDecl mvarId let val ← ensureHasType mvarDecl.type val assignExprMVar mvarId val pure true | _ => loop (i+1) dist else pure false loop 0 0 partial def step (struct : Struct) : M Unit := unless (← isRoundDone) do withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do for field in struct.fields do match field.val with | FieldVal.nested struct => step struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => unless (← isExprMVarAssigned mvarId) do let ctx ← read if (← withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then modify fun s => { s with progress := true } | _ => pure () partial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do match findDefaultMissing? (← getMCtx) struct with | none => pure () -- Done | some field => if d > hierarchyDepth then throwErrorAt! field.ref "field '{getFieldName field}' is missing" else withReader (fun ctx => { ctx with maxDistance := d }) do modify fun s => { s with progress := false } step struct if (← get).progress then do propagateLoop hierarchyDepth 0 struct else propagateLoop hierarchyDepth (d+1) struct def propagate (struct : Struct) : TermElabM Unit := let hierarchyDepth := getHierarchyDepth struct let structNames := collectStructNames struct #[] (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {} end DefaultFields private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do let structName ← getStructName stx expectedType? source unless isStructureLike (← getEnv) structName do throwError! "invalid \{...} notation, '{structName}' is not a structure" match mkStructView stx structName source with | Except.error ex => throwError ex | Except.ok struct => let struct ← expandStruct struct trace[Elab.struct]! "{struct}" let (r, struct) ← elabStruct struct expectedType? DefaultFields.propagate struct pure r @[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do match (← expandNonAtomicExplicitSource stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let sourceView ← getStructSource stx match (← isModifyOp? stx), sourceView with | some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType? | some _, _ => throwError "invalid {...} notation, explicit source is required when using '[<index>] := <value>'" | _, _ => elabStructInstAux stx expectedType? sourceView builtin_initialize registerTraceClass `Elab.struct end Lean.Elab.Term.StructInst
cbfb2031c2266e997bcd7c7adc945d2540e41e86
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Linter/Builtin.lean
2548e9b23a19b58a16422a79890492a0da320207
[ "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,263
lean
import Lean.Linter.Util import Lean.Elab.Command namespace Lean.Linter register_builtin_option linter.suspiciousUnexpanderPatterns : Bool := { defValue := true, descr := "enable the 'suspicious unexpander patterns' linter" } def getLinterSuspiciousUnexpanderPatterns (o : Options) : Bool := getLinterValue linter.suspiciousUnexpanderPatterns o def suspiciousUnexpanderPatterns : Linter where run cmdStx := do unless getLinterSuspiciousUnexpanderPatterns (← getOptions) do return -- check `[app_unexpander _]` defs defined by pattern matching let `($[$_:docComment]? @[$[$attrs:attr],*] $(_vis)? def $_ : $_ $[| $pats => $_]*) := cmdStx | return unless attrs.any (· matches `(attr| app_unexpander $_)) do return for pat in pats do let patHead ← match pat with | `(`($patHead:ident $_args*)) => pure patHead | `(`($patHead:ident)) => pure patHead | _ => continue logLint linter.suspiciousUnexpanderPatterns patHead "Unexpanders should match the function name against an antiquotation `$_` so as to be independent of the specific pretty printing of the name." builtin_initialize addLinter suspiciousUnexpanderPatterns end Lean.Linter
c970e47640ef3c9b069d81842ead031af277744d
df2ac890a99cf2a713b837b1a2a1c322c21b7929
/src/test.lean
c08076822a551f1532edcccc542372dbd713e0a3
[]
no_license
alib99/lean
3ff677698b0df63ddc32365dc77d495afee3668a
a4f168b789901deba7b7a47f1d0f4dfe696bd7b9
refs/heads/master
1,585,988,152,218
1,541,120,824,000
1,541,120,824,000
155,777,199
0
0
null
null
null
null
UTF-8
Lean
false
false
2,611
lean
import category_theory.category group_theory.group_action category_theory.functor import category_theory.yoneda open category_theory category_theory.category instance Gset (G : Type) [group G] : category (Σ X : Type, {f : G → X → X // is_group_action f}) := { hom := λ X Y, {k : X.1 → Y.1 // ∀ (g : G) (x : X.1), k (X.2.1 g x) = Y.2.1 g (k x) }, id := λ X, ⟨id, λ g x, rfl⟩, comp := λ X Y Z h₁ h₂, ⟨h₂.1 ∘ h₁.1, by simp [h₁.2, h₂.2] at *⟩ } /- given ctegories D and C i watnt to give for each object X in C a functo from D to C -/ def const_func (D C : Type*) [category D][category C](X:C): functor D C:= {obj:=λ_,X , map' := λ _ _ _, category.id X } def const_nat {D C : Type*} [category D] [category C] {X Y : C} (f : hom X Y) : const_func D C X ⟹ const_func D C Y := { app := λ _, f, naturality' := by dsimp [const_func]; simp } /- given a functor F :D → C I'm going to give a functor from Cᵒᵖ to Type sending X to Hom(const_func X,F) -/ def chris_func (D C:Type*)[category D][category C](F:functor D C): functor (Cᵒᵖ) (Type*) := { obj := λ X, const_func D C X ⟹ F, map' := λ X Y f, ((yoneda (D ⥤ C)).obj F).map (const_nat f), map_id' := λ X, funext $ λ x, nat_trans.ext _ _ $ λ Z, id_comp _ _, map_comp' := λ X Y Z f g, funext $ λ h, nat_trans.ext _ _ $ λ Z, assoc _ _ _ _ } /- given a functor F: D ⥤ C limit will give me an obect X:C -/ structure limit (D :Type*){C : Type*}[category D][category C](F:D ⥤ C):= (limit:C) (is_limit: (chris_func D C F) ≅ (yoneda C).obj limit) /-now to give an instance of a category for fibred product diagram-/ inductive three_stuff :Type |B |U |F inductive fiber_diagram.hom : three_stuff → three_stuff → Type | id : Π u, fiber_diagram.hom u u | cov_map : fiber_diagram.hom three_stuff.U three_stuff.B | moduli : fiber_diagram.hom three_stuff.F three_stuff.B def fiber_diagram.hom.comp : Π {X Y Z: three_stuff}, fiber_diagram.hom X Y → fiber_diagram.hom Y Z → fiber_diagram.hom X Z | _ _ _ (fiber_diagram.hom.id u) g := g |three_stuff.U three_stuff.B three_stuff.B hom.cov_map (hom.id three_stuff.B):=fiber_diagram.hom.cov_map |three_stuff.F three_stuff.B three_stuff.B hom.moduli (hom.id three_stuff.B):=fiber_diagram.hom.moduli instance fiber_diagram :category three_stuff := { hom := fiber_diagram.hom, id := fiber_diagram.hom.id, comp :=λ _ _ _ , fiber_diagram.hom.comp, id_comp':= λ X Y f,by cases X ;cases f ;refl, comp_id':= λ X Y f, by cases Y;cases f;refl, assoc':=λ W X Y Z f g h,by cases W;cases Y;cases f;cases g;refl, }
5041739d2a946574711542d08fc53a33aa964526
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Meta/Tactic.lean
07715bfa4edcd7190f8143a425a0941356edfcac
[ "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
547
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.Meta.Tactic.Intro import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Target import Lean.Meta.Tactic.Rewrite import Lean.Meta.Tactic.Generalize import Lean.Meta.Tactic.LocalDecl import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases
065799c9d6b5f9b5e21f31257ca0b8c9f556921d
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/algebra/trunc_group.hlean
011fa1dbf63cd5dd9e79c049a1bd5a1e9e1150b7
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
2,445
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn truncating an ∞-group to a group -/ import hit.trunc algebra.bundled open eq is_trunc trunc namespace algebra section parameters (n : trunc_index) {A : Type} [inf_group A] local abbreviation G := trunc n A definition trunc_mul [unfold 9 10] (g h : G) : G := begin induction g with p, induction h with q, exact tr (p * q) end definition trunc_inv [unfold 9] (g : G) : G := begin induction g with p, exact tr p⁻¹ end definition trunc_one [constructor] : G := tr 1 local notation 1 := trunc_one local postfix ⁻¹ := trunc_inv local infix * := trunc_mul theorem trunc_mul_assoc (g₁ g₂ g₃ : G) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := begin induction g₁ with p₁, induction g₂ with p₂, induction g₃ with p₃, exact ap tr !mul.assoc, end theorem trunc_one_mul (g : G) : 1 * g = g := begin induction g with p, exact ap tr !one_mul end theorem trunc_mul_one (g : G) : g * 1 = g := begin induction g with p, exact ap tr !mul_one end theorem trunc_mul_left_inv (g : G) : g⁻¹ * g = 1 := begin induction g with p, exact ap tr !mul.left_inv end parameter (A) definition trunc_inf_group [constructor] [instance] : inf_group (trunc n A) := ⦃inf_group, mul := algebra.trunc_mul n, mul_assoc := algebra.trunc_mul_assoc n, one := algebra.trunc_one n, one_mul := algebra.trunc_one_mul n, mul_one := algebra.trunc_mul_one n, inv := algebra.trunc_inv n, mul_left_inv := algebra.trunc_mul_left_inv n⦄ definition trunc_group [constructor] : group (trunc 0 A) := group_of_inf_group _ end section variables (n : trunc_index) {A : Type} [ab_inf_group A] theorem trunc_mul_comm (g h : trunc n A) : trunc_mul n g h = trunc_mul n h g := begin induction g with p, induction h with q, exact ap tr !mul.comm end variable (A) definition trunc_ab_inf_group [constructor] [instance] : ab_inf_group (trunc n A) := ⦃ab_inf_group, trunc_inf_group n A, mul_comm := algebra.trunc_mul_comm n⦄ definition trunc_ab_group [constructor] : ab_group (trunc 0 A) := ab_group_of_ab_inf_group _ end end algebra
e4e2a17a5834c00ea50d338d1ba1a1fcb6d2bd29
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/nat/examples/fib2.lean
50b20c4d224ac137b0722c431d345cd5edf150b5
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,293
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 Show that tail recursive fib is equal to standard one. -/ import data.nat open nat definition fib : nat → nat | 0 := 1 | 1 := 1 | (n+2) := fib (n+1) + fib n private definition fib_fast_aux : nat → nat → nat → nat | 0 i j := j | (n+1) i j := fib_fast_aux n j (j+i) lemma fib_fast_aux_lemma : ∀ n m, fib_fast_aux n (fib m) (fib (succ m)) = fib (succ (n + m)) | 0 m := sorry -- by rewrite zero_add | (succ n) m := sorry /- begin have ih : fib_fast_aux n (fib (succ m)) (fib (succ (succ m))) = fib (succ (n + succ m)), from fib_fast_aux_lemma n (succ m), have h₁ : fib (succ m) + fib m = fib (succ (succ m)), from rfl, change fib_fast_aux n (fib (succ m)) (fib (succ m) + fib m) = fib (succ (succ n + m)), rewrite [h₁, ih, succ_add, add_succ] end -/ definition fib_fast (n: nat) := fib_fast_aux n 0 1 lemma fib_fast_eq_fib : ∀ n, fib_fast n = fib n | 0 := rfl | (succ n) := sorry /- begin have h₁ : fib_fast_aux n (fib 0) (fib 1) = fib (succ n), from !fib_fast_aux_lemma, change fib_fast_aux n 1 (1+0) = fib (succ n), krewrite h₁ end -/
b3fe50f904d8b34c3dfef5c6506fbd1d4aefdbf9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/representation_theory/maschke.lean
f8133b981258b33049eaf94a622c22ad61675b69
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,150
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.monoid_algebra import Mathlib.algebra.invertible import Mathlib.algebra.char_p.basic import Mathlib.linear_algebra.basis import Mathlib.PostPort universes u namespace Mathlib /-! # Maschke's theorem We prove Maschke's theorem for finite groups, in the formulation that every submodule of a `k[G]` module has a complement, when `k` is a field with `¬(ring_char k ∣ fintype.card G)`. We do the core computation in greater generality. For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`, and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`, we produce a `k[G]`-linear retraction by taking the average over `G` of the conjugates of `π`. ## Future work It's not so far to give the usual statement, that every finite dimensional representation of a finite group is semisimple (i.e. a direct sum of irreducibles). -/ -- At first we work with any `[comm_ring k]`, and add the assumption that -- `[invertible (fintype.card G : k)]` when it is required. /-! We now do the key calculation in Maschke's theorem. Given `V → W`, an inclusion of `k[G]` modules,, assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`), just as a `k`-linear map. (When `k` is a field, this will be available cheaply, by choosing a basis.) We now construct a retraction of the inclusion as a `k[G]`-linear map, by the formula $$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$ -/ namespace linear_map /-- We define the conjugate of `π` by `g`, as a `k`-linear map. -/ def conjugate {k : Type u} [comm_ring k] {G : Type u} [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (π : linear_map k W V) (g : G) : linear_map k W V := comp (comp (monoid_algebra.group_smul.linear_map k V (g⁻¹)) π) (monoid_algebra.group_smul.linear_map k W g) theorem conjugate_i {k : Type u} [comm_ring k] {G : Type u} [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (π : linear_map k W V) (i : linear_map (monoid_algebra k G) V W) (h : ∀ (v : V), coe_fn π (coe_fn i v) = v) (g : G) (v : V) : coe_fn (conjugate π g) (coe_fn i v) = v := sorry /-- The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map. (We postpone dividing by the size of the group as long as possible.) -/ def sum_of_conjugates {k : Type u} [comm_ring k] (G : Type u) [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (π : linear_map k W V) [fintype G] : linear_map k W V := finset.sum finset.univ fun (g : G) => conjugate π g /-- In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map. -/ def sum_of_conjugates_equivariant {k : Type u} [comm_ring k] (G : Type u) [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (π : linear_map k W V) [fintype G] : linear_map (monoid_algebra k G) W V := monoid_algebra.equivariant_of_linear_of_comm (sum_of_conjugates G π) sorry /-- We construct our `k[G]`-linear retraction of `i` as $$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$ -/ def equivariant_projection {k : Type u} [comm_ring k] (G : Type u) [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (π : linear_map k W V) [fintype G] [inv : invertible ↑(fintype.card G)] : linear_map (monoid_algebra k G) W V := ⅟ • sum_of_conjugates_equivariant G π theorem equivariant_projection_condition {k : Type u} [comm_ring k] (G : Type u) [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (π : linear_map k W V) (i : linear_map (monoid_algebra k G) V W) (h : ∀ (v : V), coe_fn π (coe_fn i v) = v) [fintype G] [inv : invertible ↑(fintype.card G)] (v : V) : coe_fn (equivariant_projection G π) (coe_fn i v) = v := sorry end linear_map -- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]` -- with `¬(ring_char k ∣ fintype.card G)`. theorem monoid_algebra.exists_left_inverse_of_injective {k : Type u} [field k] {G : Type u} [fintype G] [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (not_dvd : ¬ring_char k ∣ fintype.card G) (f : linear_map (monoid_algebra k G) V W) (hf : linear_map.ker f = ⊥) : ∃ (g : linear_map (monoid_algebra k G) W V), linear_map.comp g f = linear_map.id := sorry theorem monoid_algebra.submodule.exists_is_compl {k : Type u} [field k] {G : Type u} [fintype G] [group G] {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (not_dvd : ¬ring_char k ∣ fintype.card G) (p : submodule (monoid_algebra k G) V) : ∃ (q : submodule (monoid_algebra k G) V), is_compl p q := sorry
41b9df735e3845349cbead67bb1ff063a1799132
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/modular_forms/congruence_subgroups.lean
5dfd42d0e3b01146553ceb95c572d762a570b967
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,961
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import linear_algebra.special_linear_group import data.zmod.basic import group_theory.subgroup.pointwise import group_theory.group_action.conj_act /-! # Congruence subgroups This defines congruence subgroups of `SL(2,ℤ)` such as `Γ(N)`, `Γ₀(N)` and `Γ₁(N)` for `N` a natural number. It also contains basic results about congruence subgroups. -/ local notation `SL(` n `, ` R `)`:= matrix.special_linear_group (fin n) R local attribute [-instance] matrix.special_linear_group.has_coe_to_fun local prefix `↑ₘ`:1024 := @coe _ (matrix (fin 2) (fin 2) _) _ open matrix.special_linear_group matrix variable (N : ℕ) local notation `SLMOD(`N`)` := @matrix.special_linear_group.map (fin 2) _ _ _ _ _ _ (int.cast_ring_hom (zmod N)) @[simp] lemma SL_reduction_mod_hom_val (N : ℕ) (γ : SL(2, ℤ)) : ∀ (i j : fin 2), ((SLMOD(N) γ) : (matrix (fin 2) (fin 2) (zmod N))) i j = (((↑ₘγ i j) : ℤ) : zmod N) := λ i j, rfl /--The full level `N` congruence subgroup of `SL(2,ℤ)` of matrices that reduce to the identity modulo `N`.-/ def Gamma (N : ℕ) : subgroup SL(2, ℤ) := (SLMOD(N)).ker lemma Gamma_mem' (N : ℕ) (γ : SL(2, ℤ)) : γ ∈ Gamma N ↔ SLMOD(N) γ = 1 := iff.rfl @[simp] lemma Gamma_mem (N : ℕ) (γ : SL(2, ℤ)) : γ ∈ Gamma N ↔ (((↑ₘγ 0 0) : ℤ) : zmod N) = 1 ∧ (((↑ₘγ 0 1) : ℤ) : zmod N) = 0 ∧ (((↑ₘγ 1 0) : ℤ) : zmod N) = 0 ∧ (((↑ₘγ 1 1) : ℤ) : zmod N) = 1 := begin rw Gamma_mem', split, { intro h, simp [←(SL_reduction_mod_hom_val N γ), h] }, { intro h, ext, rw SL_reduction_mod_hom_val N γ, fin_cases i; fin_cases j, all_goals {simp_rw h, refl} } end lemma Gamma_normal (N : ℕ) : subgroup.normal (Gamma N) := (SLMOD(N)).normal_ker lemma Gamma_one_top : Gamma 1 = ⊤ := begin ext, simp, end lemma Gamma_zero_bot : Gamma 0 = ⊥ := begin ext, simp only [Gamma_mem, coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, map_apply, int.cast_id, subgroup.mem_bot], split, { intro h, ext, fin_cases i; fin_cases j, any_goals {simp [h]} }, { intro h, simp [h] } end /--The congruence subgroup of `SL(2,ℤ)` of matrices whose lower left-hand entry reduces to zero modulo `N`. -/ def Gamma0 (N : ℕ) : subgroup SL(2, ℤ) := { carrier := { g : SL(2, ℤ) | ((↑ₘg 1 0 : ℤ) : zmod N) = 0 }, one_mem' := by { simp }, mul_mem':= by {intros a b ha hb, simp only [ set.mem_set_of_eq], have h := ((matrix.two_mul_expl a.1 b.1).2.2.1), simp only [coe_coe, coe_matrix_coe, coe_mul, int.coe_cast_ring_hom, map_apply, set.mem_set_of_eq, subtype.val_eq_coe, mul_eq_mul] at *, rw h, simp [ha, hb] }, inv_mem':= by {intros a ha, simp only [ set.mem_set_of_eq, subtype.val_eq_coe], rw (SL2_inv_expl a), simp only [subtype.val_eq_coe, cons_val_zero, cons_val_one, head_cons, coe_coe, coe_matrix_coe, coe_mk, int.coe_cast_ring_hom, map_apply, int.cast_neg, neg_eq_zero, set.mem_set_of_eq] at *, exact ha } } @[simp] lemma Gamma0_mem (N : ℕ) (A: SL(2, ℤ)) : A ∈ Gamma0 N ↔ (((↑ₘA) 1 0 : ℤ) : zmod N) = 0 := iff.rfl lemma Gamma0_det (N : ℕ) (A : Gamma0 N) : (A.1.1.det : zmod N) = 1 := by {simp [A.1.property]} /--The group homomorphism from `Gamma0` to `zmod N` given by mapping a matrix to its lower right-hand entry. -/ def Gamma_0_map (N : ℕ): Gamma0 N →* zmod N := { to_fun := λ g, ((↑ₘg 1 1 : ℤ) : zmod N), map_one' := by { simp, }, map_mul' := by {intros A B, have := (two_mul_expl A.1.1 B.1.1).2.2.2, simp only [coe_coe, subgroup.coe_mul, coe_matrix_coe, coe_mul, int.coe_cast_ring_hom, map_apply, subtype.val_eq_coe, mul_eq_mul] at *, rw this, have ha := A.property, simp only [int.cast_add, int.cast_mul, add_left_eq_self, subtype.val_eq_coe, Gamma0_mem, coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, map_apply] at *, rw ha, simp,} } /--The congruence subgroup `Gamma1` (as a subgroup of `Gamma0`) of matrices whose bottom row is congruent to `(0,1)` modulo `N`.-/ def Gamma1' (N : ℕ) : subgroup (Gamma0 N) := (Gamma_0_map N).ker @[simp] lemma Gamma1_mem' (N : ℕ) (γ : Gamma0 N) : γ ∈ Gamma1' N ↔ (Gamma_0_map N) γ = 1 := iff.rfl lemma Gamma1_to_Gamma0_mem (N : ℕ) (A : Gamma0 N) : A ∈ Gamma1' N ↔ ((↑ₘA 0 0 : ℤ) : zmod N) = 1 ∧ ((↑ₘA 1 1 : ℤ) : zmod N) = 1 ∧ ((↑ₘA 1 0 : ℤ) : zmod N) = 0 := begin split, { intro ha, have hA := A.property, rw Gamma0_mem at hA, have adet := Gamma0_det N A, rw matrix.det_fin_two at adet, simp only [Gamma_0_map, coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, map_apply, Gamma1_mem', monoid_hom.coe_mk, subtype.val_eq_coe, int.cast_sub, int.cast_mul] at *, rw [hA, ha] at adet, simp only [mul_one, mul_zero, sub_zero] at adet, simp only [adet, hA, ha, eq_self_iff_true, and_self]}, { intro ha, simp only [Gamma1_mem', Gamma_0_map, monoid_hom.coe_mk, coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, map_apply], exact ha.2.1,} end /--The congruence subgroup `Gamma1` of `SL(2,ℤ)` consisting of matrices whose bottom row is congruent to `(0,1)` modulo `N`. -/ def Gamma1 (N : ℕ) : subgroup SL(2, ℤ) := subgroup.map (((Gamma0 N).subtype).comp (Gamma1' N).subtype) ⊤ @[simp] lemma Gamma1_mem (N : ℕ) (A : SL(2, ℤ)) : A ∈ Gamma1 N ↔ ((↑ₘA 0 0 : ℤ) : zmod N) = 1 ∧ ((↑ₘA 1 1 : ℤ) : zmod N) = 1 ∧ ((↑ₘA 1 0 : ℤ) : zmod N) = 0 := begin split, { intro ha, simp_rw [Gamma1, subgroup.mem_map] at ha, simp at ha, obtain ⟨⟨x, hx⟩, hxx⟩ := ha, rw Gamma1_to_Gamma0_mem at hx, rw ←hxx, convert hx }, { intro ha, simp_rw [Gamma1, subgroup.mem_map], have hA : A ∈ (Gamma0 N), by {simp [ha.right.right, Gamma0_mem, subtype.val_eq_coe],}, have HA : (⟨A , hA⟩ : Gamma0 N) ∈ Gamma1' N, by {simp only [Gamma1_to_Gamma0_mem, subgroup.coe_mk, coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, map_apply], exact ha,}, refine ⟨(⟨(⟨A , hA⟩ : Gamma0 N), HA ⟩ : (( Gamma1' N ) : subgroup (Gamma0 N))), _⟩, simp } end lemma Gamma1_in_Gamma0 (N : ℕ) : Gamma1 N ≤ Gamma0 N := begin intros x HA, simp only [Gamma0_mem, Gamma1_mem, coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, map_apply] at *, exact HA.2.2, end section congruence_subgroup /--A congruence subgroup is a subgroup of `SL(2,ℤ)` which contains some `Gamma N` for some `(N : ℕ+)`. -/ def is_congruence_subgroup (Γ : subgroup SL(2, ℤ)) : Prop := ∃ (N : ℕ+), Gamma N ≤ Γ lemma is_congruence_subgroup_trans (H K : subgroup SL(2, ℤ)) (h: H ≤ K) (h2 : is_congruence_subgroup H) : is_congruence_subgroup K := begin obtain ⟨N , hN⟩ := h2, refine ⟨N, le_trans hN h⟩, end lemma Gamma_is_cong_sub (N : ℕ+) : is_congruence_subgroup (Gamma N) := ⟨N, by {simp only [le_refl]}⟩ lemma Gamma1_is_congruence (N : ℕ+) : is_congruence_subgroup (Gamma1 N) := begin refine ⟨N, _⟩, intros A hA, simp only [Gamma1_mem, Gamma_mem] at *, simp only [hA, eq_self_iff_true, and_self], end lemma Gamma0_is_congruence (N : ℕ+) : is_congruence_subgroup (Gamma0 N) := is_congruence_subgroup_trans _ _ (Gamma1_in_Gamma0 N) (Gamma1_is_congruence N) end congruence_subgroup section conjugation open_locale pointwise lemma Gamma_cong_eq_self (N : ℕ) (g : conj_act SL(2, ℤ)) : g • (Gamma N) = Gamma N := begin apply subgroup.normal.conj_act (Gamma_normal N), end lemma conj_cong_is_cong (g : conj_act SL(2, ℤ)) (Γ : subgroup SL(2, ℤ)) (h : is_congruence_subgroup Γ) : is_congruence_subgroup (g • Γ) := begin obtain ⟨N, HN⟩ := h, refine ⟨N, _⟩, rw [←Gamma_cong_eq_self N g, subgroup.pointwise_smul_le_pointwise_smul_iff], exact HN, end end conjugation
06b7afce14054645a727dc1d5fe021c8d654437a
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/category_theory/shift.lean
2667a51854247b27565c29eb77f7cdbc7f8bc6d4
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
1,422
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.zero /-! #Shift A `shift` on a category is nothing more than an automorphism of the category. An example to keep in mind might be the category of complexes ⋯ → C_{n-1} → C_n → C_{n+1} → ⋯ with the shift operator re-indexing the terms, so the degree `n` term of `shift C` would be the degree `n+1` term of `C`. -/ namespace category_theory universes v u variables (C : Type u) [category.{v} C] /-- A category has a shift, or translation, if it is equipped with an automorphism. -/ class has_shift := (shift : C ≌ C) variables [has_shift.{v} C] /-- The shift autoequivalence, moving objects and morphisms 'up'. -/ def shift : C ≌ C := has_shift.shift.{v} -- Any better notational suggestions? notation X`⟦`n`⟧`:20 := ((shift _)^(n : ℤ)).functor.obj X notation f`⟦`n`⟧'`:80 := ((shift _)^(n : ℤ)).functor.map f example {X Y : C} (f : X ⟶ Y) : X⟦1⟧ ⟶ Y⟦1⟧ := f⟦1⟧' example {X Y : C} (f : X ⟶ Y) : X⟦-2⟧ ⟶ Y⟦-2⟧ := f⟦-2⟧' open category_theory.limits variables [has_zero_morphisms.{v} C] @[simp] lemma shift_zero_eq_zero (X Y : C) (n : ℤ) : (0 : X ⟶ Y)⟦n⟧' = (0 : X⟦n⟧ ⟶ Y⟦n⟧) := by apply equivalence_preserves_zero_morphisms end category_theory
41ac2b433bb7bcaef0ff176b262477bc252b02e7
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/ring_theory/eisenstein_criterion.lean
7a79944caecc512c075bd6cea3b9d4599dca2453
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
5,389
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.ideal.operations import data.polynomial.ring_division import tactic.apply_fun import ring_theory.prime /-! # Eisenstein's criterion A proof of a slight generalisation of Eisenstein's criterion for the irreducibility of a polynomial over an integral domain. -/ open polynomial ideal.quotient variables {R : Type*} [integral_domain R] namespace polynomial namespace eisenstein_criterion_aux /- Section for auxiliary lemmas used in the proof of `irreducible_of_eisenstein_criterion`-/ lemma map_eq_C_mul_X_pow_of_forall_coeff_mem {f : polynomial R} {P : ideal R} (hfP : ∀ (n : ℕ), ↑n < f.degree → f.coeff n ∈ P) (hf0 : f ≠ 0) : map (mk P) f = C ((mk P) f.leading_coeff) * X ^ f.nat_degree := polynomial.ext (λ n, begin rcases lt_trichotomy ↑n (degree f) with h | h | h, { erw [coeff_map, eq_zero_iff_mem.2 (hfP n h), coeff_C_mul, coeff_X_pow, if_neg, mul_zero], rintro rfl, exact not_lt_of_ge degree_le_nat_degree h }, { have : nat_degree f = n, from nat_degree_eq_of_degree_eq_some h.symm, rw [coeff_C_mul, coeff_X_pow, if_pos this.symm, mul_one, leading_coeff, this, coeff_map] }, { rw [coeff_eq_zero_of_degree_lt, coeff_eq_zero_of_degree_lt], { refine lt_of_le_of_lt (degree_C_mul_X_pow_le _ _) _, rwa ← degree_eq_nat_degree hf0 }, { exact lt_of_le_of_lt (degree_map_le _) h } } end) lemma le_nat_degree_of_map_eq_mul_X_pow {n : ℕ} {P : ideal R} (hP : P.is_prime) {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hc0 : c.degree = 0) : n ≤ q.nat_degree := with_bot.coe_le_coe.1 (calc ↑n = degree (q.map (mk P)) : by rw [hq, degree_mul, hc0, zero_add, degree_pow, degree_X, nsmul_one, nat.cast_with_bot] ... ≤ degree q : degree_map_le _ ... ≤ nat_degree q : degree_le_nat_degree) lemma eval_zero_mem_ideal_of_eq_mul_X_pow {n : ℕ} {P : ideal R} {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hn0 : 0 < n) : eval 0 q ∈ P := by rw [← coeff_zero_eq_eval_zero, ← eq_zero_iff_mem, ← coeff_map, coeff_zero_eq_eval_zero, hq, eval_mul, eval_pow, eval_X, zero_pow hn0, mul_zero] lemma is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit {p q : polynomial R} (hu : ∀ (x : R), C x ∣ p * q → is_unit x) (hpm : p.nat_degree = 0) : is_unit p := begin rw [eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm), is_unit_C], refine hu _ _, rw [← eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm)], exact dvd_mul_right _ _ end end eisenstein_criterion_aux open eisenstein_criterion_aux /-- If `f` is a non constant polynomial with coefficients in `R`, and `P` is a prime ideal in `R`, then if every coefficient in `R` except the leading coefficient is in `P`, and the trailing coefficient is not in `P^2` and no non units in `R` divide `f`, then `f` is irreducible. -/ theorem irreducible_of_eisenstein_criterion {f : polynomial R} {P : ideal R} (hP : P.is_prime) (hfl : f.leading_coeff ∉ P) (hfP : ∀ n : ℕ, ↑n < degree f → f.coeff n ∈ P) (hfd0 : 0 < degree f) (h0 : f.coeff 0 ∉ P^2) (hu : ∀ x : R, C x ∣ f → is_unit x) : irreducible f := have hf0 : f ≠ 0, from λ _, by simp only [*, not_true, submodule.zero_mem, coeff_zero] at *, have hf : f.map (mk P) = C (mk P (leading_coeff f)) * X ^ nat_degree f, from map_eq_C_mul_X_pow_of_forall_coeff_mem hfP hf0, have hfd0 : 0 < f.nat_degree, from with_bot.coe_lt_coe.1 (lt_of_lt_of_le hfd0 degree_le_nat_degree), ⟨mt degree_eq_zero_of_is_unit (λ h, by simp only [*, lt_irrefl] at *), begin rintros p q rfl, rw [map_mul] at hf, rcases mul_eq_mul_prime_pow (show prime (X : polynomial (ideal.quotient P)), from prime_of_degree_eq_one_of_monic degree_X monic_X) hf with ⟨m, n, b, c, hmnd, hbc, hp, hq⟩, have hmn : 0 < m → 0 < n → false, { assume hm0 hn0, refine h0 _, rw [coeff_zero_eq_eval_zero, eval_mul, pow_two], exact ideal.mul_mem_mul (eval_zero_mem_ideal_of_eq_mul_X_pow hp hm0) (eval_zero_mem_ideal_of_eq_mul_X_pow hq hn0) }, have hpql0 : (mk P) (p * q).leading_coeff ≠ 0, { rwa [ne.def, eq_zero_iff_mem] }, have hp0 : p ≠ 0, from λ h, by simp only [*, zero_mul, eq_self_iff_true, not_true, ne.def] at *, have hq0 : q ≠ 0, from λ h, by simp only [*, eq_self_iff_true, not_true, ne.def, mul_zero] at *, have hbc0 : degree b = 0 ∧ degree c = 0, { apply_fun degree at hbc, rwa [degree_C hpql0, degree_mul, eq_comm, nat.with_bot.add_eq_zero_iff] at hbc }, have hmp : m ≤ nat_degree p, from le_nat_degree_of_map_eq_mul_X_pow hP hp hbc0.1, have hnq : n ≤ nat_degree q, from le_nat_degree_of_map_eq_mul_X_pow hP hq hbc0.2, have hpmqn : p.nat_degree = m ∧ q.nat_degree = n, { rw [nat_degree_mul hp0 hq0] at hmnd, clear_except hmnd hmp hnq, omega }, obtain rfl | rfl : m = 0 ∨ n = 0, { rwa [pos_iff_ne_zero, pos_iff_ne_zero, imp_false, not_not, ← or_iff_not_imp_left] at hmn }, { exact or.inl (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit hu hpmqn.1) }, { exact or.inr (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit (by simpa only [mul_comm] using hu) hpmqn.2) } end⟩ end polynomial
9639e1e78f9348b97db26d97947bc6f8ddb34b46
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/125.lean
c24fb615b812d4a6240ee1f33cfa8e41e44aabe8
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
640
lean
class HasElems (α : Type) : Type := (elems : Array α) def elems (α : Type) [HasElems α] : Array α := HasElems.elems inductive Foo : Type | mk1 : Bool → Foo | mk2 : Bool → Foo open Foo instance BoolElems : HasElems Bool := ⟨#[false, true]⟩ instance FooElems : HasElems Foo := ⟨(elems Bool).map mk1 ++ (elems Bool).map mk2⟩ def fooRepr (foo : Foo) := match foo with | mk1 b => s!"OH {b}" | mk2 b => s!"DR {b}" instance : Repr Foo := ⟨fooRepr⟩ #eval elems Foo #eval #[false, true].map Foo.mk1 def Foo.toBool : Foo → Bool | Foo.mk1 b => b | Foo.mk2 b => b #eval #[Foo.mk1 false, Foo.mk2 true].map Foo.toBool