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
48a976d329ad109bdd7809b13c1ad503bffd0cb5
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category/traversable/derive.lean
fe2e3419961d8af0f87304e3f706af5a1c439c5e
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
16,382
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₀ rec_call : list expr) : tactic expr := do g ← target, args' ← mmap (map_field n g.app_fn f α β) args₀, constr ← mk_const c, let r := constr.mk_app (args' ++ rec_call), 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], 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, let args₀ := args.take $ args.length - rec_call.length, 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,rec_call) ← vs'.mpartition $ λ e, ((≠ n) ∘ expr.const_name ∘ expr.get_app_fn) <$> infer_type 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₀ rec_call : list expr) : tactic expr := do g ← target, args' ← mmap (traverse_field n appl_inst g.app_fn f α) 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' ++ rec_call.map sum.inr), 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], 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, let args₀ := args.take $ args.length - rec_call.length, 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,rec_call) ← vs'.mpartition $ λ e, ((≠ n) ∘ expr.const_name ∘ expr.get_app_fn) <$> infer_type 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
3d3e04c1fb52046f12a7e21ca776a0bb0acc2861
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/big_operators/basic.lean
4848199f03e9483f90076a16a89784a77f6bfef7
[ "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,040
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_cons (h : a ∉ s) : (∏ x in (cons a s h), f x) = f a * ∏ x in s, f x := fold_cons h @[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 @[to_additive] lemma prod_filter_mul_prod_filter_not (s : finset α) (p : α → Prop) [decidable_pred p] [decidable_pred (λ x, ¬p x)] (f : α → β) : (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬p x), f x) = ∏ x in s, f x := begin haveI := classical.dec_eq α, rw [← prod_union (filter_inter_filter_neg_eq p s).le, filter_union_filter_neg_eq] end 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 β] /-- Multiplying the products of a function over `s` and over `sᶜ` gives the whole product. For a version expressed with subtypes, see `fintype.prod_subtype_mul_prod_subtype`. -/ @[to_additive "Adding the sums of a function over `s` and over `sᶜ` gives the whole sum. For a version expressed with subtypes, see `fintype.sum_subtype_add_sum_subtype`. "] 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_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_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_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 prod_subset_one_on_sdiff h (by simpa) (λ _ _, rfl) @[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_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} [decidable_pred (λ x, ¬ p x)] (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)) := calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = (∏ 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_filter_mul_prod_filter_not s p _).symm ... = (∏ 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_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 @[to_additive] 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 induction s using multiset.induction_on with a s ih, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, simp only [multiset.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 @[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₂, add_sub_cancel_of_le 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`. See also `finset.prod_image`. -/ lemma prod_comp [decidable_eq γ] (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 lemma dvd_prod_of_mem (f : α → β) {a : α} {s : finset α} (ha : a ∈ s) : f a ∣ ∏ i in s, f i := begin classical, rw finset.prod_eq_mul_prod_diff_singleton ha, exact dvd_mul_right _ _, end /-- 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 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 γ] (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`. See also `finset.sum_image`."] 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 @[to_additive] lemma prod_subtype_mul_prod_subtype {α β : Type*} [fintype α] [comm_monoid β] (p : α → Prop) (f : α → β) [decidable_pred p] : (∏ (i : {x // p x}), f i) * (∏ i : {x // ¬ p x}, f i) = ∏ i, f i := begin classical, let s := {x | p x}.to_finset, rw [← finset.prod_subtype s, ← finset.prod_subtype sᶜ], { exact finset.prod_mul_prod_compl _ _ }, { simp }, { simp } 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
767634943aa5f286b5c88bdb4c1e682a635d29a5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/sesquilinear_form.lean
088ef30ba2f0b8cc1d5be40e53cc57d8234c92ab
[ "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
28,940
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import algebra.module.linear_map import linear_algebra.bilinear_map import algebra.euclidean_domain.instances import ring_theory.non_zero_divisors /-! # Sesquilinear form This files provides properties about sesquilinear forms. The maps considered are of the form `M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R`, where `I₁ : R₁ →+* R` and `I₂ : R₂ →+* R` are ring homomorphisms and `M₁` is a module over `R₁` and `M₂` is a module over `R₂`. Sesquilinear forms are the special case that `M₁ = M₂`, `R₁ = R₂ = R`, and `I₁ = ring_hom.id R`. Taking additionally `I₂ = ring_hom.id R`, then one obtains bilinear forms. These forms are a special case of the bilinear maps defined in `bilinear_map.lean` and all basic lemmas about construction and elementary calculations are found there. ## Main declarations * `is_ortho`: states that two vectors are orthogonal with respect to a sesquilinear form * `is_symm`, `is_alt`: states that a sesquilinear form is symmetric and alternating, respectively * `orthogonal_bilin`: provides the orthogonal complement with respect to sesquilinear form ## References * <https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings> ## Tags Sesquilinear form, -/ open_locale big_operators variables {R R₁ R₂ R₃ M M₁ M₂ Mₗ₁ Mₗ₁' Mₗ₂ Mₗ₂' K K₁ K₂ V V₁ V₂ n : Type*} namespace linear_map /-! ### Orthogonal vectors -/ section comm_ring -- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps variables [comm_semiring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁] [comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂] {I₁ : R₁ →+* R} {I₂ : R₂ →+* R} {I₁' : R₁ →+* R} /-- The proposition that two elements of a sesquilinear form space are orthogonal -/ def is_ortho (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) (x y) : Prop := B x y = 0 lemma is_ortho_def {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} {x y} : B.is_ortho x y ↔ B x y = 0 := iff.rfl lemma is_ortho_zero_left (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) (x) : is_ortho B (0 : M₁) x := by { dunfold is_ortho, rw [ map_zero B, zero_apply] } lemma is_ortho_zero_right (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) (x) : is_ortho B x (0 : M₂) := map_zero (B x) lemma is_ortho_flip {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R} {x y} : B.is_ortho x y ↔ B.flip.is_ortho y x := by simp_rw [is_ortho_def, flip_apply] /-- A set of vectors `v` is orthogonal with respect to some bilinear form `B` if and only if for all `i ≠ j`, `B (v i) (v j) = 0`. For orthogonality between two elements, use `bilin_form.is_ortho` -/ def is_Ortho (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R) (v : n → M₁) : Prop := pairwise (B.is_ortho on v) lemma is_Ortho_def {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R} {v : n → M₁} : B.is_Ortho v ↔ ∀ i j : n, i ≠ j → B (v i) (v j) = 0 := iff.rfl lemma is_Ortho_flip (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R) {v : n → M₁} : B.is_Ortho v ↔ B.flip.is_Ortho v := begin simp_rw is_Ortho_def, split; intros h i j hij, { rw flip_apply, exact h j i (ne.symm hij) }, simp_rw flip_apply at h, exact h j i (ne.symm hij), end end comm_ring section field variables [field K] [field K₁] [add_comm_group V₁] [module K₁ V₁] [field K₂] [add_comm_group V₂] [module K₂ V₂] {I₁ : K₁ →+* K} {I₂ : K₂ →+* K} {I₁' : K₁ →+* K} {J₁ : K →+* K} {J₂ : K →+* K} -- todo: this also holds for [comm_ring R] [is_domain R] when J₁ is invertible lemma ortho_smul_left {B : V₁ →ₛₗ[I₁] V₂ →ₛₗ[I₂] K} {x y} {a : K₁} (ha : a ≠ 0) : (is_ortho B x y) ↔ (is_ortho B (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [map_smulₛₗ₂, H, smul_zero]}, { rw [map_smulₛₗ₂, smul_eq_zero] at H, cases H, { rw map_eq_zero I₁ at H, trivial }, { exact H }} end -- todo: this also holds for [comm_ring R] [is_domain R] when J₂ is invertible lemma ortho_smul_right {B : V₁ →ₛₗ[I₁] V₂ →ₛₗ[I₂] K} {x y} {a : K₂} {ha : a ≠ 0} : (is_ortho B x y) ↔ (is_ortho B x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [map_smulₛₗ, H, smul_zero] }, { rw [map_smulₛₗ, smul_eq_zero] at H, cases H, { simp at H, exfalso, exact ha H }, { exact H }} end /-- A set of orthogonal vectors `v` with respect to some sesquilinear form `B` is linearly independent if for all `i`, `B (v i) (v i) ≠ 0`. -/ lemma linear_independent_of_is_Ortho {B : V₁ →ₛₗ[I₁] V₁ →ₛₗ[I₁'] K} {v : n → V₁} (hv₁ : B.is_Ortho v) (hv₂ : ∀ i, ¬ B.is_ortho (v i) (v i)) : linear_independent K₁ v := begin classical, rw linear_independent_iff', intros s w hs i hi, have : B (s.sum $ λ (i : n), w i • v i) (v i) = 0, { rw [hs, map_zero, zero_apply] }, have hsum : s.sum (λ (j : n), I₁(w j) * B (v j) (v i)) = I₁(w i) * B (v i) (v i), { apply finset.sum_eq_single_of_mem i hi, intros j hj hij, rw [is_Ortho_def.1 hv₁ _ _ hij, mul_zero], }, simp_rw [B.map_sum₂, map_smulₛₗ₂, smul_eq_mul, hsum] at this, apply (map_eq_zero I₁).mp, exact eq_zero_of_ne_zero_of_mul_right_eq_zero (hv₂ i) this, end end field /-! ### Reflexive bilinear forms -/ section reflexive variables [comm_semiring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁] {I₁ : R₁ →+* R} {I₂ : R₁ →+* R} {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R} /-- The proposition that a sesquilinear form is reflexive -/ def is_refl (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R) : Prop := ∀ (x y), B x y = 0 → B y x = 0 namespace is_refl variable (H : B.is_refl) lemma eq_zero : ∀ {x y}, B x y = 0 → B y x = 0 := λ x y, H x y lemma ortho_comm {x y} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩ lemma dom_restrict_refl (H : B.is_refl) (p : submodule R₁ M₁) : (B.dom_restrict₁₂ p p).is_refl := λ _ _, by { simp_rw dom_restrict₁₂_apply, exact H _ _} @[simp] lemma flip_is_refl_iff : B.flip.is_refl ↔ B.is_refl := ⟨λ h x y H, h y x ((B.flip_apply _ _).trans H), λ h x y, h y x⟩ lemma ker_flip_eq_bot (H : B.is_refl) (h : B.ker = ⊥) : B.flip.ker = ⊥ := begin refine ker_eq_bot'.mpr (λ _ hx, ker_eq_bot'.mp h _ _), ext, exact H _ _ (linear_map.congr_fun hx _), end lemma ker_eq_bot_iff_ker_flip_eq_bot (H : B.is_refl) : B.ker = ⊥ ↔ B.flip.ker = ⊥ := begin refine ⟨ker_flip_eq_bot H, λ h, _⟩, exact (congr_arg _ B.flip_flip.symm).trans (ker_flip_eq_bot (flip_is_refl_iff.mpr H) h), end end is_refl end reflexive /-! ### Symmetric bilinear forms -/ section symmetric variables [comm_semiring R] [add_comm_monoid M] [module R M] {I : R →+* R} {B : M →ₛₗ[I] M →ₗ[R] R} /-- The proposition that a sesquilinear form is symmetric -/ def is_symm (B : M →ₛₗ[I] M →ₗ[R] R) : Prop := ∀ (x y), I (B x y) = B y x namespace is_symm protected lemma eq (H : B.is_symm) (x y) : I (B x y) = B y x := H x y lemma is_refl (H : B.is_symm) : B.is_refl := λ x y H1, by { rw ←H.eq, simp [H1] } lemma ortho_comm (H : B.is_symm) {x y} : is_ortho B x y ↔ is_ortho B y x := H.is_refl.ortho_comm lemma dom_restrict_symm (H : B.is_symm) (p : submodule R M) : (B.dom_restrict₁₂ p p).is_symm := λ _ _, by { simp_rw dom_restrict₁₂_apply, exact H _ _} end is_symm lemma is_symm_iff_eq_flip {B : M →ₗ[R] M →ₗ[R] R} : B.is_symm ↔ B = B.flip := begin split; intro h, { ext, rw [←h, flip_apply, ring_hom.id_apply] }, intros x y, conv_lhs { rw h }, rw [flip_apply, ring_hom.id_apply], end end symmetric /-! ### Alternating bilinear forms -/ section alternating variables [comm_ring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁] {I₁ : R₁ →+* R} {I₂ : R₁ →+* R} {I : R₁ →+* R} {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R} /-- The proposition that a sesquilinear form is alternating -/ def is_alt (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R) : Prop := ∀ x, B x x = 0 namespace is_alt variable (H : B.is_alt) include H lemma self_eq_zero (x) : B x x = 0 := H x lemma neg (x y) : - B x y = B y x := begin have H1 : B (y + x) (y + x) = 0, { exact self_eq_zero H (y + x) }, simp [map_add, self_eq_zero H] at H1, rw [add_eq_zero_iff_neg_eq] at H1, exact H1, end lemma is_refl : B.is_refl := begin intros x y h, rw [←neg H, h, neg_zero], end lemma ortho_comm {x y} : is_ortho B x y ↔ is_ortho B y x := H.is_refl.ortho_comm end is_alt lemma is_alt_iff_eq_neg_flip [no_zero_divisors R] [char_zero R] {B : M₁ →ₛₗ[I] M₁ →ₛₗ[I] R} : B.is_alt ↔ B = -B.flip := begin split; intro h, { ext, simp_rw [neg_apply, flip_apply], exact (h.neg _ _).symm }, intros x, let h' := congr_fun₂ h x x, simp only [neg_apply, flip_apply, ←add_eq_zero_iff_eq_neg] at h', exact add_self_eq_zero.mp h', end end alternating end linear_map namespace submodule /-! ### The orthogonal complement -/ variables [comm_ring R] [comm_ring R₁] [add_comm_group M₁] [module R₁ M₁] {I₁ : R₁ →+* R} {I₂ : R₁ →+* R} {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R} /-- The orthogonal complement of a submodule `N` with respect to some bilinear form is the set of elements `x` which are orthogonal to all elements of `N`; i.e., for all `y` in `N`, `B x y = 0`. Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a chirality; in addition to this "left" orthogonal complement one could define a "right" orthogonal complement for which, for all `y` in `N`, `B y x = 0`. This variant definition is not currently provided in mathlib. -/ def orthogonal_bilin (N : submodule R₁ M₁) (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R) : submodule R₁ M₁ := { carrier := { m | ∀ n ∈ N, B.is_ortho n m }, zero_mem' := λ x _, B.is_ortho_zero_right x, add_mem' := λ x y hx hy n hn, by rw [linear_map.is_ortho, map_add, show B n x = 0, by exact hx n hn, show B n y = 0, by exact hy n hn, zero_add], smul_mem' := λ c x hx n hn, by rw [linear_map.is_ortho, linear_map.map_smulₛₗ, show B n x = 0, by exact hx n hn, smul_zero] } variables {N L : submodule R₁ M₁} @[simp] lemma mem_orthogonal_bilin_iff {m : M₁} : m ∈ N.orthogonal_bilin B ↔ ∀ n ∈ N, B.is_ortho n m := iff.rfl lemma orthogonal_bilin_le (h : N ≤ L) : L.orthogonal_bilin B ≤ N.orthogonal_bilin B := λ _ hn l hl, hn l (h hl) lemma le_orthogonal_bilin_orthogonal_bilin (b : B.is_refl) : N ≤ (N.orthogonal_bilin B).orthogonal_bilin B := λ n hn m hm, b _ _ (hm n hn) end submodule namespace linear_map section orthogonal variables [field K] [add_comm_group V] [module K V] [field K₁] [add_comm_group V₁] [module K₁ V₁] {J : K →+* K} {J₁ : K₁ →+* K} {J₁' : K₁ →+* K} -- ↓ This lemma only applies in fields as we require `a * b = 0 → a = 0 ∨ b = 0` lemma span_singleton_inf_orthogonal_eq_bot (B : V₁ →ₛₗ[J₁] V₁ →ₛₗ[J₁'] K) (x : V₁) (hx : ¬ B.is_ortho x x) : (K₁ ∙ x) ⊓ submodule.orthogonal_bilin (K₁ ∙ x) B = ⊥ := begin rw ← finset.coe_singleton, refine eq_bot_iff.2 (λ y h, _), rcases mem_span_finset.1 h.1 with ⟨μ, rfl⟩, have := h.2 x _, { rw finset.sum_singleton at this ⊢, suffices hμzero : μ x = 0, { rw [hμzero, zero_smul, submodule.mem_bot] }, change B x (μ x • x) = 0 at this, rw [map_smulₛₗ, smul_eq_mul] at this, exact or.elim (zero_eq_mul.mp this.symm) (λ y, by { simp at y, exact y }) (λ hfalse, false.elim $ hx hfalse) }, { rw submodule.mem_span; exact λ _ hp, hp $ finset.mem_singleton_self _ } end -- ↓ This lemma only applies in fields since we use the `mul_eq_zero` lemma orthogonal_span_singleton_eq_to_lin_ker {B : V →ₗ[K] V →ₛₗ[J] K} (x : V) : submodule.orthogonal_bilin (K ∙ x) B = (B x).ker := begin ext y, simp_rw [submodule.mem_orthogonal_bilin_iff, linear_map.mem_ker, submodule.mem_span_singleton ], split, { exact λ h, h x ⟨1, one_smul _ _⟩ }, { rintro h _ ⟨z, rfl⟩, rw [is_ortho, map_smulₛₗ₂, smul_eq_zero], exact or.intro_right _ h } end -- todo: Generalize this to sesquilinear maps lemma span_singleton_sup_orthogonal_eq_top {B : V →ₗ[K] V →ₗ[K] K} {x : V} (hx : ¬ B.is_ortho x x) : (K ∙ x) ⊔ submodule.orthogonal_bilin (K ∙ x) B = ⊤ := begin rw orthogonal_span_singleton_eq_to_lin_ker, exact (B x).span_singleton_sup_ker_eq_top hx, end -- todo: Generalize this to sesquilinear maps /-- Given a bilinear form `B` and some `x` such that `B x x ≠ 0`, the span of the singleton of `x` is complement to its orthogonal complement. -/ lemma is_compl_span_singleton_orthogonal {B : V →ₗ[K] V →ₗ[K] K} {x : V} (hx : ¬ B.is_ortho x x) : is_compl (K ∙ x) (submodule.orthogonal_bilin (K ∙ x) B) := { disjoint := disjoint_iff.2 $ span_singleton_inf_orthogonal_eq_bot B x hx, codisjoint := codisjoint_iff.2 $ span_singleton_sup_orthogonal_eq_top hx } end orthogonal /-! ### Adjoint pairs -/ section adjoint_pair section add_comm_monoid variables [comm_semiring R] variables [add_comm_monoid M] [module R M] variables [add_comm_monoid M₁] [module R M₁] variables [add_comm_monoid M₂] [module R M₂] variables {I : R →+* R} variables {B F : M →ₗ[R] M →ₛₗ[I] R} {B' : M₁ →ₗ[R] M₁ →ₛₗ[I] R} {B'' : M₂ →ₗ[R] M₂ →ₛₗ[I] R} variables {f f' : M →ₗ[R] M₁} {g g' : M₁ →ₗ[R] M} variables (B B' f g) /-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of maps between them to be mutually adjoint. -/ def is_adjoint_pair := ∀ x y, B' (f x) y = B x (g y) variables {B B' f g} lemma is_adjoint_pair_iff_comp_eq_compl₂ : is_adjoint_pair B B' f g ↔ B'.comp f = B.compl₂ g := begin split; intros h, { ext x y, rw [comp_apply, compl₂_apply], exact h x y }, { intros _ _, rw [←compl₂_apply, ←comp_apply, h] }, end lemma is_adjoint_pair_zero : is_adjoint_pair B B' 0 0 := λ _ _, by simp only [zero_apply, map_zero] lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl lemma is_adjoint_pair.add (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') : is_adjoint_pair B B' (f + f') (g + g') := λ x _, by rw [f.add_apply, g.add_apply, B'.map_add₂, (B x).map_add, h, h'] lemma is_adjoint_pair.comp {f' : M₁ →ₗ[R] M₂} {g' : M₂ →ₗ[R] M₁} (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B' B'' f' g') : is_adjoint_pair B B'' (f'.comp f) (g.comp g') := λ _ _, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h] lemma is_adjoint_pair.mul {f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') : is_adjoint_pair B B (f * f') (g' * g) := h'.comp h end add_comm_monoid section add_comm_group variables [comm_ring R] variables [add_comm_group M] [module R M] variables [add_comm_group M₁] [module R M₁] variables {B F : M →ₗ[R] M →ₗ[R] R} {B' : M₁ →ₗ[R] M₁ →ₗ[R] R} variables {f f' : M →ₗ[R] M₁} {g g' : M₁ →ₗ[R] M} lemma is_adjoint_pair.sub (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') : is_adjoint_pair B B' (f - f') (g - g') := λ x _, by rw [f.sub_apply, g.sub_apply, B'.map_sub₂, (B x).map_sub, h, h'] lemma is_adjoint_pair.smul (c : R) (h : is_adjoint_pair B B' f g) : is_adjoint_pair B B' (c • f) (c • g) := λ _ _, by simp only [smul_apply, map_smul, smul_eq_mul, h _ _] end add_comm_group end adjoint_pair /-! ### Self-adjoint pairs-/ section selfadjoint_pair section add_comm_monoid variables [comm_semiring R] variables [add_comm_monoid M] [module R M] variables {I : R →+* R} variables (B F : M →ₗ[R] M →ₛₗ[I] R) /-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms on the underlying module. In the case that these two forms are identical, this is the usual concept of self adjointness. In the case that one of the forms is the negation of the other, this is the usual concept of skew adjointness. -/ def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B F f f /-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an adjoint for itself. -/ protected def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f end add_comm_monoid section add_comm_group variables [comm_ring R] variables [add_comm_group M] [module R M] variables [add_comm_group M₁] [module R M₁] (B F : M →ₗ[R] M →ₗ[R] R) /-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/ def is_pair_self_adjoint_submodule : submodule R (module.End R M) := { carrier := { f | is_pair_self_adjoint B F f }, zero_mem' := is_adjoint_pair_zero, add_mem' := λ f g hf hg, hf.add hg, smul_mem' := λ c f h, h.smul c, } /-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation serves as an adjoint. -/ def is_skew_adjoint (f : module.End R M) := is_adjoint_pair B B f (-f) /-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Jordan subalgebra.) -/ def self_adjoint_submodule := is_pair_self_adjoint_submodule B B /-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Lie subalgebra.) -/ def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B) B variables {B F} @[simp] lemma mem_is_pair_self_adjoint_submodule (f : module.End R M) : f ∈ is_pair_self_adjoint_submodule B F ↔ is_pair_self_adjoint B F f := iff.rfl lemma is_pair_self_adjoint_equiv (e : M₁ ≃ₗ[R] M) (f : module.End R M) : is_pair_self_adjoint B F f ↔ is_pair_self_adjoint (B.compl₁₂ ↑e ↑e) (F.compl₁₂ ↑e ↑e) (e.symm.conj f) := begin have hₗ : (F.compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M)).comp (e.symm.conj f) = (F.comp f).compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M) := by { ext, simp only [linear_equiv.symm_conj_apply, coe_comp, linear_equiv.coe_coe, compl₁₂_apply, linear_equiv.apply_symm_apply], }, have hᵣ : (B.compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M)).compl₂ (e.symm.conj f) = (B.compl₂ f).compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M) := by { ext, simp only [linear_equiv.symm_conj_apply, compl₂_apply, coe_comp, linear_equiv.coe_coe, compl₁₂_apply, linear_equiv.apply_symm_apply] }, have he : function.surjective (⇑(↑e : M₁ →ₗ[R] M) : M₁ → M) := e.surjective, simp_rw [is_pair_self_adjoint, is_adjoint_pair_iff_comp_eq_compl₂, hₗ, hᵣ, compl₁₂_inj he he], end lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R M) : B.is_skew_adjoint f ↔ is_adjoint_pair (-B) B f f := show (∀ x y, B (f x) y = B x ((-f) y)) ↔ ∀ x y, B (f x) y = (-B) x (f y), by simp @[simp] lemma mem_self_adjoint_submodule (f : module.End R M) : f ∈ B.self_adjoint_submodule ↔ B.is_self_adjoint f := iff.rfl @[simp] lemma mem_skew_adjoint_submodule (f : module.End R M) : f ∈ B.skew_adjoint_submodule ↔ B.is_skew_adjoint f := by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl } end add_comm_group end selfadjoint_pair /-! ### Nondegenerate bilinear forms -/ section nondegenerate section comm_semiring variables [comm_semiring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁] [comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂] {I₁ : R₁ →+* R} {I₂ : R₂ →+* R} {I₁' : R₁ →+* R} /-- A bilinear form is called left-separating if the only element that is left-orthogonal to every other element is `0`; i.e., for every nonzero `x` in `M₁`, there exists `y` in `M₂` with `B x y ≠ 0`.-/ def separating_left (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) : Prop := ∀ x : M₁, (∀ y : M₂, B x y = 0) → x = 0 variables (M₁ M₂ I₁ I₂) /-- In a non-trivial module, zero is not non-degenerate. -/ lemma not_separating_left_zero [nontrivial M₁] : ¬(0 : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R).separating_left := let ⟨m, hm⟩ := exists_ne (0 : M₁) in λ h, hm (h m $ λ n, rfl) variables {M₁ M₂ I₁ I₂} lemma separating_left.ne_zero [nontrivial M₁] {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} (h : B.separating_left) : B ≠ 0 := λ h0, not_separating_left_zero M₁ M₂ I₁ I₂ $ h0 ▸ h section linear variables [add_comm_monoid Mₗ₁] [add_comm_monoid Mₗ₂] [add_comm_monoid Mₗ₁'] [add_comm_monoid Mₗ₂'] variables [module R Mₗ₁] [module R Mₗ₂] [module R Mₗ₁'] [module R Mₗ₂'] variables {B : Mₗ₁ →ₗ[R] Mₗ₂ →ₗ[R] R} (e₁ : Mₗ₁ ≃ₗ[R] Mₗ₁') (e₂ : Mₗ₂ ≃ₗ[R] Mₗ₂') lemma separating_left.congr (h : B.separating_left) : (e₁.arrow_congr (e₂.arrow_congr (linear_equiv.refl R R)) B).separating_left := begin intros x hx, rw ←e₁.symm.map_eq_zero_iff, refine h (e₁.symm x) (λ y, _), specialize hx (e₂ y), simp only [linear_equiv.arrow_congr_apply, linear_equiv.symm_apply_apply, linear_equiv.map_eq_zero_iff] at hx, exact hx, end @[simp] lemma separating_left_congr_iff : (e₁.arrow_congr (e₂.arrow_congr (linear_equiv.refl R R)) B).separating_left ↔ B.separating_left := ⟨λ h, begin convert h.congr e₁.symm e₂.symm, ext x y, simp, end, separating_left.congr e₁ e₂⟩ end linear /-- A bilinear form is called right-separating if the only element that is right-orthogonal to every other element is `0`; i.e., for every nonzero `y` in `M₂`, there exists `x` in `M₁` with `B x y ≠ 0`.-/ def separating_right (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) : Prop := ∀ y : M₂, (∀ x : M₁, B x y = 0) → y = 0 /-- A bilinear form is called non-degenerate if it is left-separating and right-separating. -/ def nondegenerate (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) : Prop := separating_left B ∧ separating_right B @[simp] lemma flip_separating_right {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.flip.separating_right ↔ B.separating_left := ⟨λ hB x hy, hB x hy, λ hB x hy, hB x hy⟩ @[simp] lemma flip_separating_left {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.flip.separating_left ↔ separating_right B := by rw [←flip_separating_right, flip_flip] @[simp] lemma flip_nondegenerate {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.flip.nondegenerate ↔ B.nondegenerate := iff.trans and.comm (and_congr flip_separating_right flip_separating_left) lemma separating_left_iff_linear_nontrivial {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.separating_left ↔ ∀ x : M₁, B x = 0 → x = 0 := begin split; intros h x hB, { let h' := h x, simp only [hB, zero_apply, eq_self_iff_true, forall_const] at h', exact h' }, have h' : B x = 0 := by { ext, rw [zero_apply], exact hB _ }, exact h x h', end lemma separating_right_iff_linear_flip_nontrivial {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.separating_right ↔ ∀ y : M₂, B.flip y = 0 → y = 0 := by rw [←flip_separating_left, separating_left_iff_linear_nontrivial] /-- A bilinear form is left-separating if and only if it has a trivial kernel. -/ theorem separating_left_iff_ker_eq_bot {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.separating_left ↔ B.ker = ⊥ := iff.trans separating_left_iff_linear_nontrivial linear_map.ker_eq_bot'.symm /-- A bilinear form is right-separating if and only if its flip has a trivial kernel. -/ theorem separating_right_iff_flip_ker_eq_bot {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} : B.separating_right ↔ B.flip.ker = ⊥ := by rw [←flip_separating_left, separating_left_iff_ker_eq_bot] end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] {I I' : R →+* R} lemma is_refl.nondegenerate_of_separating_left {B : M →ₗ[R] M →ₗ[R] R} (hB : B.is_refl) (hB' : B.separating_left) : B.nondegenerate := begin refine ⟨hB', _⟩, rw [separating_right_iff_flip_ker_eq_bot, hB.ker_eq_bot_iff_ker_flip_eq_bot.mp], rwa ←separating_left_iff_ker_eq_bot, end lemma is_refl.nondegenerate_of_separating_right {B : M →ₗ[R] M →ₗ[R] R} (hB : B.is_refl) (hB' : B.separating_right) : B.nondegenerate := begin refine ⟨_, hB'⟩, rw [separating_left_iff_ker_eq_bot, hB.ker_eq_bot_iff_ker_flip_eq_bot.mpr], rwa ←separating_right_iff_flip_ker_eq_bot, end /-- The restriction of a reflexive bilinear form `B` onto a submodule `W` is nondegenerate if `W` has trivial intersection with its orthogonal complement, that is `disjoint W (W.orthogonal_bilin B)`. -/ lemma nondegenerate_restrict_of_disjoint_orthogonal {B : M →ₗ[R] M →ₗ[R] R} (hB : B.is_refl) {W : submodule R M} (hW : disjoint W (W.orthogonal_bilin B)) : (B.dom_restrict₁₂ W W).nondegenerate := begin refine (hB.dom_restrict_refl W).nondegenerate_of_separating_left _, rintro ⟨x, hx⟩ b₁, rw [submodule.mk_eq_zero, ← submodule.mem_bot R], refine hW.le_bot ⟨hx, λ y hy, _⟩, specialize b₁ ⟨y, hy⟩, simp_rw [dom_restrict₁₂_apply, submodule.coe_mk] at b₁, rw hB.ortho_comm, exact b₁, end /-- An orthogonal basis with respect to a left-separating bilinear form has no self-orthogonal elements. -/ lemma is_Ortho.not_is_ortho_basis_self_of_separating_left [nontrivial R] {B : M →ₛₗ[I] M →ₛₗ[I'] R} {v : basis n R M} (h : B.is_Ortho v) (hB : B.separating_left) (i : n) : ¬B.is_ortho (v i) (v i) := begin intro ho, refine v.ne_zero i (hB (v i) $ λ m, _), obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m, rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, map_sum], apply finset.sum_eq_zero, rintros j -, rw map_smulₛₗ, convert mul_zero _ using 2, obtain rfl | hij := eq_or_ne i j, { exact ho }, { exact h hij }, end /-- An orthogonal basis with respect to a right-separating bilinear form has no self-orthogonal elements. -/ lemma is_Ortho.not_is_ortho_basis_self_of_separating_right [nontrivial R] {B : M →ₛₗ[I] M →ₛₗ[I'] R} {v : basis n R M} (h : B.is_Ortho v) (hB : B.separating_right) (i : n) : ¬B.is_ortho (v i) (v i) := begin rw is_Ortho_flip at h, rw is_ortho_flip, exact h.not_is_ortho_basis_self_of_separating_left (flip_separating_left.mpr hB) i, end /-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is left-separating if the basis has no elements which are self-orthogonal. -/ lemma is_Ortho.separating_left_of_not_is_ortho_basis_self [no_zero_divisors R] {B : M →ₗ[R] M →ₗ[R] R} (v : basis n R M) (hO : B.is_Ortho v) (h : ∀ i, ¬B.is_ortho (v i) (v i)) : B.separating_left := begin intros m hB, obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m, rw linear_equiv.map_eq_zero_iff, ext i, rw [finsupp.zero_apply], specialize hB (v i), simp_rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, map_sum₂, map_smulₛₗ₂, smul_eq_mul] at hB, rw finset.sum_eq_single i at hB, { exact eq_zero_of_ne_zero_of_mul_right_eq_zero (h i) hB, }, { intros j hj hij, convert mul_zero _ using 2, exact hO hij, }, { intros hi, convert zero_mul _ using 2, exact finsupp.not_mem_support_iff.mp hi } end /-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is right-separating if the basis has no elements which are self-orthogonal. -/ lemma is_Ortho.separating_right_iff_not_is_ortho_basis_self [no_zero_divisors R] {B : M →ₗ[R] M →ₗ[R] R} (v : basis n R M) (hO : B.is_Ortho v) (h : ∀ i, ¬B.is_ortho (v i) (v i)) : B.separating_right := begin rw is_Ortho_flip at hO, rw [←flip_separating_left], refine is_Ortho.separating_left_of_not_is_ortho_basis_self v hO (λ i, _), rw is_ortho_flip, exact h i, end /-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is nondegenerate if the basis has no elements which are self-orthogonal. -/ lemma is_Ortho.nondegenerate_of_not_is_ortho_basis_self [no_zero_divisors R] {B : M →ₗ[R] M →ₗ[R] R} (v : basis n R M) (hO : B.is_Ortho v) (h : ∀ i, ¬B.is_ortho (v i) (v i)) : B.nondegenerate := ⟨is_Ortho.separating_left_of_not_is_ortho_basis_self v hO h, is_Ortho.separating_right_iff_not_is_ortho_basis_self v hO h⟩ end comm_ring end nondegenerate end linear_map
83375008f66a9cf8bfaba40b541c7da3ea1cce40
2f4707593665f4eac651cd5e5b39ea8eabafe0d6
/src/phomeo.lean
b0ec0836c97ba4a8975bf04ff2221fd24c12c386
[]
no_license
PatrickMassot/lean-differential-topology
941d2ac639b2c8bcfcbad85fe5ff0a4676d159e9
5b020daa5f935140c53408748a9f11ba02e7bf42
refs/heads/master
1,543,081,959,510
1,536,089,170,000
1,536,089,170,000
112,875,905
12
5
null
1,520,841,685,000
1,512,247,905,000
Lean
UTF-8
Lean
false
false
855
lean
import analysis.topology.topological_space import pequiv structure phomeo α β [topological_space α] [topological_space β] extends pequiv α β := (to_cont : ∀ V : set β, is_open V → is_open (to_fun ⁻¹' (V ∩ range) ∩ domain)) (inv_cont : ∀ U : set α, is_open U → is_open (inv_fun ⁻¹' (U ∩ domain) ∩ range)) namespace phomeo variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] instance : has_coe (phomeo α β) (pequiv α β) := ⟨λ f, f.to_pequiv⟩ def symm (f : phomeo α β) : phomeo β α := ⟨f.to_pequiv.symm, f.inv_cont, f.to_cont⟩ lemma is_open_map {f : phomeo α β} {U : set α} (H : is_open U) : is_open (f '' (U ∩ f.domain)) := begin change is_open ((f.to_pequiv) '' (U ∩ (f.to_pequiv).domain)), rw pequiv.image_eq_preimage, exact f.inv_cont U H end end phomeo
45a82d94b3229d8cf43cd7fb9b266f1f462315a7
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Compiler/IR/EmitC.lean
64a36eca1d28500af0ec3964a3d76792880af45c
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,164
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.IR.EmitC open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName) def leanMainFn := "_lean_main" structure Context where 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 let env ← getEnv match findEnvDecl env n with | some d => pure d | none => throw s!"unknown declaration '{n}'" @[inline] def emit {α : Type} [ToString α] (a : α) : M Unit := modify fun out => out ++ toString a @[inline] def emitLn {α : Type} [ToString α] (a : α) : M Unit := do emit a; emit "\n" def emitLns {α : Type} [ToString α] (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 s!"invalid export name '{n}'" def toCName (n : Name) : M String := do let 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 let 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 let env ← getEnv if ps.isEmpty && addExternForConsts then 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 if i > 0 then emit ", " emit (toCType ps[i].ty) emit ")" emitLn ";" def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do let cppBaseName ← toCName decl.name emitFnDeclAux decl cppBaseName addExternForConsts def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do let cName := Name.mkSimple cNameStr let env ← getEnv let extC := isExternC env decl.name emitFnDeclAux decl cNameStr (!extC) def emitFnDecls : M Unit := do let 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 let 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 let d ← getDecl `main match d with | Decl.fdecl (f := f) (xs := xs) (type := t) (body := b) .. => do unless xs.size == 2 || xs.size == 1 do throw "invalid main function, incorrect arity when generating code" let 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();" let modName ← getModName emitLn ("res = " ++ mkModuleInitializationFunctionName modName ++ "(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 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 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 let env ← getEnv let decls := getDecls env pure $ decls.any (fun d => d.name == `main) def emitMainFnIfNeeded : M Unit := do if (← hasMainFn) then emitMainFn def emitFileHeader : M Unit := do let env ← getEnv let 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 s!"unknown variable '{x}'" def getJPParams (j : JoinPointId) : M (Array Param) := do let 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 let ctx ← read if isTailCallTo ctx.mainFn e then pure d else declareVar x t; declareVars b true | FnBody.jdecl j xs _ b, d => do 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[0] with | Alt.ctor c b => some (c.cidx, b, alts[1].body) | _ => none 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 if n != 1 then 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; if n != 1 then 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 := do if n > 0 then emit "sizeof(void*)*"; emit n; if offset > 0 then 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 let ps ← getJPParams j unless xs.size == ps.size do throw "invalid goto" xs.size.forM fun i => do let p := ps[i] let x := xs[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 if i > 0 then emit ", " emitArg ys[i] def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := do 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[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 ";"; if updtHeader then 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. discard <| ys.size.foldM (fun i (first : Bool) => if ps[i].ty.isIrrelevant then pure first else do unless first do emit ", " emitArg ys[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 s!"failed to emit extern application '{f}'" def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do emitLhs z let decl ← getDecl f match decl with | Decl.extern _ ps _ extData => emitExternCall f ps extData ys | _ => emitCName f if ys.size > 0 then emit "("; emitArgs ys; emit ")" emitLn ";" def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do let 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[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 := do if t.isObj then if v < UInt32.size 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 := do emitLhs z; match v with | LitVal.num v => emitNumLit t v; emitLn ";" | LitVal.str v => 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 let 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[i] (i+1, n).anyI fun j => paramEqArg p ys[j] def emitTailCall (v : Expr) : M Unit := match v with | Expr.fap _ ys => do let ctx ← read let ps := ctx.mainParams unless ps.size == ys.size do throw "invalid tail call" if overwriteParam ps ys then emitLn "{" ps.size.forM fun i => do let p := ps[i] let y := ys[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[i] let y := ys[i] unless paramEqArg p y do emit p.x; emit " = _tmp_"; emit i; emitLn ";" emitLn "}" else ys.size.forM fun i => do let p := ps[i] let y := ys[i] unless paramEqArg p y do emit p.x; emit " = "; emitArg y; emitLn ";" emitLn "goto _start;" | _ => throw "bug at emitTailCall" mutual partial def emitIf (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")"; emitFnBody t; emitLn "else"; emitFnBody e partial def emitCase (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit := match isIf alts with | some (tag, t, e) => emitIf x xType tag t e | _ => do emit "switch ("; emitTag x xType; emitLn ") {"; let alts := ensureHasDefault alts; alts.forM fun alt => do match alt with | Alt.ctor c b => emit "case "; emit c.cidx; emitLn ":"; emitFnBody b | Alt.default b => emitLn "default: "; emitFnBody b emitLn "}" partial def emitBlock (b : FnBody) : M Unit := do match b with | FnBody.jdecl j xs v b => emitBlock b | d@(FnBody.vdecl x t v b) => let 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 do emitInc x n c emitBlock b | FnBody.dec x n c p b => unless p do 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 x xType alts | FnBody.jmp j xs => emitJmp j xs | FnBody.unreachable => emitLn "lean_panic_unreachable();" partial def emitJPs : FnBody → M Unit | FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitFnBody v; emitJPs b | e => do unless e.isTerminal do emitJPs e.body partial def emitFnBody (b : FnBody) : M Unit := do emitLn "{" let declared ← declareVars b false if declared then emitLn "" emitBlock b emitJPs b emitLn "}" end def emitDeclAux (d : Decl) : M Unit := do let env ← getEnv let (vMap, jpMap) := mkVarJPMaps d withReader (fun ctx => { ctx with jpMap := jpMap }) do unless hasInitAttr env d.name do match d with | Decl.fdecl (f := f) (xs := xs) (type := t) (body := b) .. => let baseName ← toCName f; if xs.size == 0 then emit "static " emit (toCType t); emit " "; if xs.size > 0 then emit baseName; emit "("; if xs.size > closureMaxArgs && isBoxedName d.name then emit "lean_object** _args" else xs.size.forM fun i => do if i > 0 then emit ", " let x := xs[i] emit (toCType x.ty); emit " "; emit x.x emit ")" else emit ("_init_" ++ baseName ++ "()") emitLn " {"; if xs.size > closureMaxArgs && isBoxedName d.name then xs.size.forM fun i => do let x := xs[i] emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];" emitLn "_start:"; withReader (fun ctx => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b); emitLn "}" | _ => pure () def emitDecl (d : Decl) : M Unit := do let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices try emitDeclAux d catch err => throw s!"{err}\ncompiling:\n{d}" def emitFns : M Unit := do let env ← getEnv; let decls := getDecls env; decls.reverse.forM emitDecl def emitMarkPersistent (d : Decl) (n : Name) : M Unit := do if d.resultType.isObj then emit "lean_mark_persistent(" emitCName n emitLn ");" def emitDeclInit (d : Decl) : M Unit := do let env ← getEnv let n := d.name if isIOUnitInitFn env n then 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 if d.params.size == 0 then match getInitFnNameFor? env d.name with | some initFn => 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);" | _ => emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n def emitInitFn : M Unit := do let env ← getEnv let modName ← getModName env.imports.forM fun imp => emitLn ("lean_object* " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_object*);") emitLns [ "static bool _G_initialized = false;", "lean_object* " ++ mkModuleInitializationFunctionName modName ++ "(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 = " ++ mkModuleInitializationFunctionName imp.module ++ "(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 Lean.IR
b256747e010a342449ccc852883a2591cc9348a1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/uniform_space/compact_separated.lean
f4ca26da60db0e4bcafddeda78dcc1e83d4aec70
[ "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
10,654
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.separation /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ open_locale classical uniformity topological_space filter open filter uniform_space set variables {α β : Type*} [uniform_space α] [uniform_space β] /-! ### Uniformity on compact separated spaces -/ /-- On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. -/ lemma compact_space_uniformity [compact_space α] [separated_space α] : 𝓤 α = ⨆ x : α, 𝓝 (x, x) := begin symmetry, refine le_antisymm supr_nhds_le_uniformity _, by_contra H, obtain ⟨V, hV, h⟩ : ∃ V : set (α × α), (∀ x : α, V ∈ 𝓝 (x, x)) ∧ 𝓤 α ⊓ 𝓟 Vᶜ ≠ ⊥, { simpa [le_iff_forall_inf_principal_compl] using H }, let F := 𝓤 α ⊓ 𝓟 Vᶜ, haveI : ne_bot F := ⟨h⟩, obtain ⟨⟨x, y⟩, hx⟩ : ∃ (p : α × α), cluster_pt p F := cluster_point_of_compact F, have : cluster_pt (x, y) (𝓤 α) := hx.of_inf_left, have hxy : x = y := eq_of_uniformity_inf_nhds this, subst hxy, have : cluster_pt (x, x) (𝓟 Vᶜ) := hx.of_inf_right, have : (x, x) ∉ interior V, { have : (x, x) ∈ closure Vᶜ, by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have : (x, x) ∈ interior V, { rw mem_interior_iff_mem_nhds, exact hV x }, contradiction end lemma unique_uniformity_of_compact_t2 {α : Type*} [t : topological_space α] [compact_space α] [t2_space α] {u u' : uniform_space α} (h : u.to_topological_space = t) (h' : u'.to_topological_space = t) : u = u' := begin apply uniform_space_eq, change uniformity _ = uniformity _, haveI : @compact_space α u.to_topological_space := by rw h ; assumption, haveI : @compact_space α u'.to_topological_space := by rw h' ; assumption, haveI : @separated_space α u := by rwa [separated_iff_t2, h], haveI : @separated_space α u' := by rwa [separated_iff_t2, h'], rw [compact_space_uniformity, compact_space_uniformity, h, h'] end /-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/ def uniform_space_of_compact_t2 {α : Type*} [topological_space α] [compact_space α] [t2_space α] : uniform_space α := { uniformity := ⨆ x, 𝓝 (x, x), refl := begin simp_rw [filter.principal_le_iff, mem_supr_sets], rintros V V_in ⟨x, _⟩ ⟨⟩, exact mem_of_mem_nhds (V_in x), end, symm := begin refine le_of_eq _, rw map_supr, congr' with x : 1, erw [nhds_prod_eq, ← prod_comm], end, comp := begin /- This is the difficult part of the proof. We need to prove that, for each neighborhood W of the diagonal Δ, W ○ W is still a neighborhood of the diagonal. -/ set 𝓝Δ := ⨆ x : α, 𝓝 (x, x), -- The filter of neighborhoods of Δ set F := 𝓝Δ.lift' (λ (s : set (α × α)), s ○ s), -- Compositions of neighborhoods of Δ -- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥ rw le_iff_forall_inf_principal_compl, intros V V_in, by_contra H, haveI : ne_bot (F ⊓ 𝓟 Vᶜ) := ⟨H⟩, -- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ obtain ⟨⟨x, y⟩, hxy⟩ : ∃ (p : α × α), cluster_pt p (F ⊓ 𝓟 Vᶜ) := cluster_point_of_compact _, -- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V, -- and a fortiori not in Δ, so x ≠ y have clV : cluster_pt (x, y) (𝓟 $ Vᶜ) := hxy.of_inf_right, have : (x, y) ∉ interior V, { have : (x, y) ∈ closure (Vᶜ), by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have diag_subset : diagonal α ⊆ interior V, { rw subset_interior_iff_nhds, rintros ⟨x, x⟩ ⟨⟩, exact (mem_supr_sets.mp V_in : _) x }, have x_ne_y : x ≠ y, { intro h, apply this, apply diag_subset, simp [h] }, -- Since α is compact and Hausdorff, it is normal, hence regular. haveI : normal_space α := normal_of_compact_t2, -- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods -- U₁ and U₂. obtain ⟨U₁, V₁, U₁_in, V₁_in, U₂, V₂, U₂_in₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := disjoint_nested_nhds x_ne_y, -- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃) is an open -- neighborhood of Δ. let U₃ := (V₁ ∪ V₂)ᶜ, have U₃_op : is_open U₃ := is_open_compl_iff.mpr (is_closed.union V₁_cl V₂_cl), let W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃), have W_in : W ∈ 𝓝Δ, { rw mem_supr_sets, intros x, apply is_open.mem_nhds (is_open.union (is_open.union _ _) _), { by_cases hx : x ∈ V₁ ∪ V₂, { left, cases hx with hx hx ; [left, right] ; split ; tauto }, { right, rw mem_prod, tauto }, }, all_goals { simp only [is_open.prod, *] } }, -- So W ○ W ∈ F by definition of F have : W ○ W ∈ F, by simpa only using mem_lift' W_in, -- And V₁.prod V₂ ∈ 𝓝 (x, y) have hV₁₂ : V₁.prod V₂ ∈ 𝓝 (x, y) := prod_is_open.mem_nhds V₁_in V₂_in, -- But (x, y) is also a cluster point of F so (V₁.prod V₂) ∩ (W ○ W) ≠ ∅ have clF : cluster_pt (x, y) F := hxy.of_inf_left, obtain ⟨p, p_in⟩ : ∃ p, p ∈ (V₁.prod V₂) ∩ (W ○ W) := cluster_pt_iff.mp clF hV₁₂ this, -- However the construction of W implies (V₁.prod V₂) ∩ (W ○ W) = ∅. -- Indeed assume for contradiction there is some (u, v) in the intersection. -- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W. -- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁.prod U₁. -- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂.prod U₂. -- Hence w ∈ U₁ ∩ U₂ which is empty. have inter_empty : (V₁.prod V₂) ∩ (W ○ W) = ∅, { rw eq_empty_iff_forall_not_mem, rintros ⟨u, v⟩ ⟨⟨u_in, v_in⟩, w, huw, hwv⟩, have uw_in : (u, w) ∈ U₁.prod U₁ := set.mem_prod.2 ((huw.resolve_right (λ h, (h.1 $ or.inl u_in))).resolve_right (λ h, have u ∈ U₁ ∩ U₂, from ⟨VU₁ u_in, h.1⟩, by rwa hU₁₂ at this)), have wv_in : (w, v) ∈ U₂.prod U₂ := set.mem_prod.2 ((hwv.resolve_right (λ h, (h.2 $ or.inr v_in))).resolve_left (λ h, have v ∈ U₁ ∩ U₂, from ⟨h.2, VU₂ v_in⟩, by rwa hU₁₂ at this)), have : w ∈ U₁ ∩ U₂ := ⟨uw_in.2, wv_in.1⟩, rwa hU₁₂ at this }, -- So we have a contradiction rwa inter_empty at p_in, end, is_open_uniformity := begin -- Here we need to prove the topology induced by the constructed uniformity is the -- topology we started with. suffices : ∀ x : α, comap (prod.mk x) (⨆ y, 𝓝 (y ,y)) = 𝓝 x, { intros s, change is_open s ↔ _, simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity_aux, this] }, intros x, simp_rw [comap_supr, nhds_prod_eq, comap_prod, show prod.fst ∘ prod.mk x = λ y : α, x, by ext ; simp, show prod.snd ∘ (prod.mk x) = (id : α → α), by ext ; refl, comap_id], rw [supr_split_single _ x, comap_const_of_mem (λ V, mem_of_mem_nhds)], suffices : ∀ y ≠ x, comap (λ (y : α), x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x, by simpa, intros y hxy, simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (by simp)], end } /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly continuous. -/ lemma compact_space.uniform_continuous_of_continuous [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := calc map (prod.map f f) (𝓤 α) = map (prod.map f f) (⨆ x, 𝓝 (x, x)) : by rw compact_space_uniformity ... = ⨆ x, map (prod.map f f) (𝓝 (x, x)) : by rw map_supr ... ≤ ⨆ x, 𝓝 (f x, f x) : supr_le_supr (λ x, (h.prod_map h).continuous_at) ... ≤ ⨆ y, 𝓝 (y, y) : supr_comp_le (λ y, 𝓝 (y, y)) f ... ≤ 𝓤 β : supr_nhds_le_uniformity /-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous' {s : set α} {f : α → β} (hs : is_compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s := begin rw uniform_continuous_on_iff_restrict, rw is_separated_iff_induced at hs', rw is_compact_iff_compact_space at hs, rw continuous_on_iff_continuous_restrict at hf, resetI, exact compact_space.uniform_continuous_of_continuous hf, end /-- Heine-Cantor: a continuous function on a compact set of a separated uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous [separated_space α] {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s := hs.uniform_continuous_on_of_continuous' (is_separated_of_separated_space s) hf
6117429d3eda4f1830aefa4605979833b51f4ae3
297c4ceafbbaed2a59b6215504d09e6bf201a2ee
/finset/comb.lean
c1e7febd0eafd306e70976bd29271fa148613106
[]
no_license
minchaowu/Kruskal.lean3
559c91b82033ce44ea61593adcec9cfff725c88d
a14516f47b21e636e9df914fc6ebe64cbe5cd38d
refs/heads/master
1,611,010,001,429
1,497,935,421,000
1,497,935,421,000
82,000,982
1
0
null
null
null
null
UTF-8
Lean
false
false
7,495
lean
import .basic open list quot subtype decidable function namespace finset /- image (corresponds to map on list) -/ section image variables {A B : Type} variable [h : decidable_eq B] include h definition image (f : A → B) (s : finset A) : finset B := quot.lift_on s (λ l, to_finset (list.map f l.1)) (λ l₁ l₂ p, quot.sound (perm.perm_erase_dup_of_perm (perm.perm_map _ p))) infix `'` := image theorem image_empty (f : A → B) : image f empty = empty := rfl theorem mem_image_of_mem (f : A → B) {s : finset A} {a : A} : a ∈ s → f a ∈ image f s := quot.induction_on s (take l, assume H : a ∈ l.1, mem_to_finset (mem_map f H)) theorem mem_image {f : A → B} {s : finset A} {a : A} {b : B} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : A → B} {s : finset A} {b : B} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := quot.induction_on s (take l, assume H : b ∈ erase_dup (list.map f l.1), exists_of_mem_map (mem_of_mem_erase_dup H)) theorem mem_image_iff (f : A → B) {s : finset A} {y : B} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := iff.intro exists_of_mem_image (assume H, let ⟨x,H₁,H₂⟩ := H in mem_image H₁ H₂) theorem mem_image_eq (f : A → B) {s : finset A} {y : B} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : A → B} {s t : finset A} {y : B} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := let ⟨x, H3, H4⟩ := exists_of_mem_image H1 in have H5 : x ∈ t, from mem_of_subset_of_mem H2 H3, show y ∈ image f t, from mem_image H5 H4 theorem image_insert [h' : decidable_eq A] (f : A → B) (s : finset A) (a : A) : image f (insert a s) = insert (f a) (image f s) := ext (take y, iff.intro (assume H : y ∈ image f (insert a s), let ⟨x,H1l,H1r⟩ := exists_of_mem_image H in have x = a ∨ x ∈ s, from eq_or_mem_of_mem_insert H1l, or.elim this (suppose x = a, have f a = y, from eq.subst this H1r, show y ∈ insert (f a) (image f s), from eq.subst this (mem_insert _ _)) (suppose x ∈ s, have f x ∈ image f s, from mem_image_of_mem f this, show y ∈ insert (f a) (image f s), from eq.subst H1r (mem_insert_of_mem _ this))) (suppose y ∈ insert (f a) (image f s), have y = f a ∨ y ∈ image f s, from eq_or_mem_of_mem_insert this, or.elim this (assume eq : y = f a, have f a ∈ image f (insert a s), from mem_image_of_mem f (mem_insert _ _), show y ∈ image f (insert a s), by rw eq;exact this) (suppose y ∈ image f s, show y ∈ image f (insert a s), from mem_image_of_mem_image_of_subset this (subset_insert _ _) ))) lemma image_comp {C : Type} [deceqC : decidable_eq C] {f : B → C} {g : A → B} {s : finset A} : image (f∘g) s = image f (image g s) := ext (take z, iff.intro (suppose z ∈ image (f∘g) s, let ⟨x,Hx,Hgfx⟩ := exists_of_mem_image this in by rewrite -Hgfx; apply mem_image_of_mem _ (mem_image_of_mem _ Hx)) (suppose z ∈ image f (image g s), let ⟨y,Hy,Hfy⟩ := exists_of_mem_image this in let ⟨x,Hx,Hgx⟩ := exists_of_mem_image Hy in mem_image Hx (begin simp [comp, Hgx, Hfy] end))) lemma image_subset {a b : finset A} (f : A → B) (H : a ⊆ b) : image f a ⊆ image f b := subset_of_forall (take y, assume Hy : y ∈ image f a, let ⟨x,Hx₁,Hx₂⟩ := exists_of_mem_image Hy in mem_image (mem_of_subset_of_mem H Hx₁) Hx₂) theorem image_union [h' : decidable_eq A] (f : A → B) (s t : finset A) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), let ⟨x,xst,fxy⟩ := exists_of_mem_image H in or.elim (mem_or_mem_of_mem_union xst) (assume xs, mem_union_l (mem_image xs fxy)) (assume xt, mem_union_r (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim (mem_or_mem_of_mem_union H) (assume yifs : y ∈ image f s, let ⟨x,xs,fxy⟩ := exists_of_mem_image yifs in mem_image (mem_union_l xs) fxy) (assume yift : y ∈ image f t, let ⟨x,xt,fxy⟩ := exists_of_mem_image yift in mem_image (mem_union_r xt) fxy))) end image /- separation and set-builder notation -/ section sep variables {A : Type} [deceq : decidable_eq A] include deceq variables (p : A → Prop) [decp : decidable_pred p] (s : finset A) {x : A} include decp definition sep : finset A := quot.lift_on s (λl, to_finset_of_nodup (list.filter p l.1) (list.nodup_filter p l.2)) (λ l₁ l₂ u, quot.sound (perm.perm_filter u)) -- notation [priority finset.prio] `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r theorem sep_empty : sep p empty = empty := rfl variables {p s} theorem of_mem_sep : x ∈ sep p s → p x := quot.induction_on s (take l, list.of_mem_filter) theorem mem_of_mem_sep : x ∈ sep p s → x ∈ s := quot.induction_on s (take l, list.mem_of_mem_filter) theorem mem_sep_of_mem {x : A} : x ∈ s → p x → x ∈ sep p s := quot.induction_on s (take l, list.mem_filter_of_mem) variables (p s) theorem mem_sep_iff : x ∈ sep p s ↔ x ∈ s ∧ p x := iff.intro (assume H, and.intro (mem_of_mem_sep H) (of_mem_sep H)) (assume H, mem_sep_of_mem (and.left H) (and.right H)) theorem mem_sep_eq : x ∈ sep p s = (x ∈ s ∧ p x) := propext (mem_sep_iff _ _) variable t : finset A theorem mem_sep_union_iff : x ∈ sep p (s ∪ t) ↔ x ∈ sep p s ∨ x ∈ sep p t := by repeat {rw mem_sep_iff}; rw [mem_union_iff]; super end sep section variables {A : Type} [deceqA : decidable_eq A] include deceqA theorem eq_sep_of_subset {s t : finset A} (ssubt : s ⊆ t) : s = sep (λ x, x ∈ s) t := ext (take x, iff.intro (suppose x ∈ s, mem_sep_of_mem (mem_of_subset_of_mem ssubt this) this) (suppose x ∈ sep (λ x, x ∈ s) t, @of_mem_sep _ _ _ _ _ _ this)) end /- set difference -/ section diff variables {A : Type} [deceq : decidable_eq A] include deceq definition diff (s t : finset A) : finset A := sep (λ x, x ∉ t) s infix ` \ ` := diff theorem mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∈ s := mem_of_mem_sep H theorem not_mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∉ t := @of_mem_sep _ _ _ _ _ _ H theorem mem_diff {s t : finset A} {x : A} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := mem_sep_of_mem H1 H2 theorem mem_diff_iff (s t : finset A) (x : A) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.intro (assume H, and.intro (mem_of_mem_diff H) (not_mem_of_mem_diff H)) (assume H, mem_diff (and.left H) (and.right H)) theorem mem_diff_eq (s t : finset A) (x : A) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := propext (mem_diff_iff _ _ _) theorem union_diff_cancel {s t : finset A} (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (suppose x ∈ s ∪ (t \ s), or.elim (mem_or_mem_of_mem_union this) (suppose x ∈ s, mem_of_subset_of_mem H this) (suppose x ∈ t \ s, mem_of_mem_diff this)) (assume h, decidable.by_cases (suppose x ∈ s, mem_union_left _ this) (suppose x ∉ s, mem_union_right _ (mem_diff h this)))) theorem diff_union_cancel {s t : finset A} (H : s ⊆ t) : (t \ s) ∪ s = t := @eq.subst _ (λ x, x = t) _ _ (union_comm _ _) (union_diff_cancel H) end diff /- set complement -/ section complement -- TODO end complement end finset
7bd0112b5343303eaf64450ed6ee875c1ac4256d
ce89339993655da64b6ccb555c837ce6c10f9ef4
/zeptometer/topprover/6.lean
3b791ca4d42f59d41bb0e192f0dee0ce58eaf30e
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
2,116
lean
lemma no_space_in_one : ∀ n m : ℕ , ¬ (n < m ∧ nat.succ n > m) := begin intros n, induction n, { intros m, intro h, cases m, cases h.left, cases h.right, cases a }, { intros m, intro h, induction m, cases h.left, have pl : n_n < m_n := begin apply nat.lt_of_succ_lt_succ, exact h.left, end, have pr : nat.succ n_n > m_n := begin apply nat.lt_of_succ_lt_succ, exact h.right end, apply n_ih m_n, constructor; assumption } end example : ∀ n m : ℕ , n < m ∨ n = m ∨ n > m := begin intros n, induction n, { intros m, induction m, {simp}, cases m_ih, { left, apply nat.lt.step, assumption }, { cases m_ih, { left, rw ←m_ih, apply nat.lt.base }, { cases m_ih } } }, { intros m, induction m, right, right, apply nat.zero_lt_succ, cases m_ih, { left, apply nat.lt.step, assumption }, { cases m_ih, { left, rw m_ih, apply nat.lt.base }, { have n_ih2 := n_ih m_n, cases n_ih2, { have f : false := begin apply no_space_in_one, constructor, assumption, apply nat.succ_lt_succ, assumption end, trivial }, { cases n_ih2, { right, left, rw n_ih2 }, { right, right, apply nat.succ_lt_succ, assumption } } } } } end
7d1a1c53e4c10a44e386b2fbf835bfc3505aa5dd
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/dual.lean
0807d169d352b923442c545ecf87b8870d17da5c
[ "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
10,991
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Fabian Glöckle -/ import linear_algebra.tensor_product import linear_algebra.finite_dimensional import tactic.apply_fun noncomputable theory /-! # Dual vector spaces The dual space of an R-module M is the R-module of linear maps `M → R`. ## Main definitions * `dual R M` defines the dual space of M over R. * Given a basis for a K-vector space `V`, `is_basis.to_dual` produces a map from `V` to `dual K V`. * Given families of vectors `e` and `ε`, `dual_pair e ε` states that these families have the characteristic properties of a basis and a dual. ## Main results * `to_dual_equiv` : the dual space is linearly equivalent to the primal space. * `dual_pair.is_basis` and `dual_pair.eq_dual`: if `e` and `ε` form a dual pair, `e` is a basis and `ε` is its dual basis. ## Notation We sometimes use `V'` as local notation for `dual K V`. ## Implementation details Because of unresolved type class issues, the following local instance can be of use: ``` private def help_tcs : has_scalar K V := mul_action.to_has_scalar _ _ local attribute [instance] help_tcs ``` -/ namespace module variables (R : Type*) (M : Type*) variables [comm_ring R] [add_comm_group M] [module R M] /-- The dual space of an R-module M is the R-module of linear maps `M → R`. -/ @[derive [add_comm_group, module R]] def dual := M →ₗ[R] R namespace dual instance : inhabited (dual R M) := by unfold dual; apply_instance instance : has_coe_to_fun (dual R M) := ⟨_, linear_map.to_fun⟩ /-- Maps a module M to the dual of the dual of M. See `vector_space.eval_range` and `vector_space.eval_equiv`. -/ def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.id.flip lemma eval_apply (v : M) (a : dual R M) : (eval R M v) a = a v := begin dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply] end end dual end module namespace is_basis universes u v w variables {K : Type u} {V : Type v} {ι : Type w} variables [field K] [add_comm_group V] [vector_space K V] open vector_space module module.dual submodule linear_map cardinal function instance dual.vector_space : vector_space K (dual K V) := { ..module.dual.inst K V } variables [de : decidable_eq ι] variables {B : ι → V} (h : is_basis K B) include de h /-- The linear map from a vector space equipped with basis to its dual vector space, taking basis elements to corresponding dual basis elements. -/ def to_dual : V →ₗ[K] module.dual K V := h.constr $ λ v, h.constr $ λ w, if w = v then 1 else 0 lemma to_dual_apply (i j : ι) : (h.to_dual (B i)) (B j) = if i = j then 1 else 0 := by erw [constr_basis h, constr_basis h]; ac_refl def to_dual_flip (v : V) : (V →ₗ[K] K) := (linear_map.flip h.to_dual).to_fun v omit de h /-- Evaluation of finitely supported functions at a fixed point `i`, as a `K`-linear map. -/ def eval_finsupp_at (i : ι) : (ι →₀ K) →ₗ[K] K := { to_fun := λ f, f i, add := by intros; rw finsupp.add_apply, smul := by intros; rw finsupp.smul_apply } include h set_option class.instance_max_depth 50 def coord_fun (i : ι) : (V →ₗ[K] K) := (eval_finsupp_at i).comp h.repr lemma coord_fun_eq_repr (v : V) (i : ι) : h.coord_fun i v = h.repr v i := rfl include de lemma to_dual_swap_eq_to_dual (v w : V) : h.to_dual_flip v w = h.to_dual w v := rfl lemma to_dual_eq_repr (v : V) (i : ι) : (h.to_dual v) (B i) = h.repr v i := begin rw [←coord_fun_eq_repr, ←to_dual_swap_eq_to_dual], apply congr_fun, dsimp, congr', apply h.ext, { intros, rw [to_dual_swap_eq_to_dual, to_dual_apply], { split_ifs with hx, { rwa [hx, coord_fun_eq_repr, repr_eq_single, finsupp.single_apply, if_pos rfl] }, { rw [coord_fun_eq_repr, repr_eq_single, finsupp.single_apply], symmetry, convert if_neg hx } } } end lemma to_dual_inj (v : V) (a : h.to_dual v = 0) : v = 0 := begin rw [← mem_bot K, ← h.repr_ker, mem_ker], apply finsupp.ext, intro b, rw [←to_dual_eq_repr _ _ _, a], refl end theorem to_dual_ker : h.to_dual.ker = ⊥ := ker_eq_bot'.mpr h.to_dual_inj theorem to_dual_range [fin : fintype ι] : h.to_dual.range = ⊤ := begin rw eq_top_iff', intro f, rw linear_map.mem_range, let lin_comb : ι →₀ K := finsupp.on_finset fin.elems (λ i, f.to_fun (B i)) _, { use finsupp.total ι V K B lin_comb, apply h.ext, { intros i, rw [h.to_dual_eq_repr _ i, repr_total h], { refl }, { rw [finsupp.mem_supported], exact λ _ _, set.mem_univ _ } } }, { intros a _, apply fin.complete } end /-- Maps a basis for `V` to a basis for the dual space. -/ def dual_basis : ι → dual K V := λ i, h.to_dual (B i) theorem dual_lin_independent : linear_independent K h.dual_basis := begin apply linear_independent.image h.1, rw to_dual_ker, exact disjoint_bot_right end /-- A vector space is linearly equivalent to its dual space. -/ def to_dual_equiv [fintype ι] : V ≃ₗ[K] (dual K V) := linear_equiv.of_bijective h.to_dual h.to_dual_ker h.to_dual_range theorem dual_basis_is_basis [fintype ι] : is_basis K h.dual_basis := h.to_dual_equiv.is_basis h @[simp] lemma to_dual_to_dual [fintype ι] : (h.dual_basis_is_basis.to_dual).comp h.to_dual = eval K V := begin apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ h, intros i, apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ h.dual_basis_is_basis, intros j, dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply, linear_map.comp_apply], apply eq.trans (to_dual_apply h.dual_basis_is_basis i j), { dunfold dual_basis, rw to_dual_apply, split_ifs with h₁ h₂; try {refl}, { exfalso, apply h₂ h₁.symm }, { exfalso, apply ne.symm h₁ (by assumption) } } end omit de theorem dual_dim_eq [fintype ι] : cardinal.lift.{v u} (dim K V) = dim K (dual K V) := begin classical, have := linear_equiv.dim_eq_lift h.to_dual_equiv, simp only [cardinal.lift_umax] at this, rw [this, ← cardinal.lift_umax], apply cardinal.lift_id, end end is_basis namespace vector_space universes u v variables {K : Type u} {V : Type v} variables [field K] [add_comm_group V] [vector_space K V] open module module.dual submodule linear_map cardinal is_basis theorem eval_ker : (eval K V).ker = ⊥ := begin haveI := classical.dec_eq K, haveI := classical.dec_eq V, haveI := classical.dec_eq (dual K V), rw ker_eq_bot', intros v h, rw linear_map.ext_iff at h, by_contradiction H, rcases exists_subset_is_basis (linear_independent_singleton H) with ⟨b, hv, hb⟩, swap 4, assumption, have hv' : v = (λ (i : b), i.val) ⟨v, hv (set.mem_singleton v)⟩ := rfl, let hx := h (hb.to_dual v), erw [eval_apply, hv', to_dual_apply, if_pos rfl, zero_apply _] at hx, exact one_ne_zero hx end theorem dual_dim_eq (h : dim K V < omega) : cardinal.lift.{v u} (dim K V) = dim K (dual K V) := begin letI := classical.dec_eq (dual K V), letI := classical.dec_eq V, rcases exists_is_basis_fintype h with ⟨b, hb, ⟨hf⟩⟩, resetI, exact hb.dual_dim_eq end set_option class.instance_max_depth 70 lemma eval_range (h : dim K V < omega) : (eval K V).range = ⊤ := begin haveI := classical.dec_eq (dual K V), haveI := classical.dec_eq (dual K (dual K V)), letI := classical.dec_eq V, rcases exists_is_basis_fintype h with ⟨b, hb, ⟨hf⟩⟩, resetI, rw [← hb.to_dual_to_dual, range_comp, hb.to_dual_range, map_top, to_dual_range _], apply_instance end /-- A vector space is linearly equivalent to the dual of its dual space. -/ def eval_equiv (h : dim K V < omega) : V ≃ₗ[K] dual K (dual K V) := linear_equiv.of_bijective (eval K V) eval_ker (eval_range h) end vector_space section dual_pair open vector_space module module.dual linear_map function universes u v w variables {K : Type u} {V : Type v} {ι : Type w} [decidable_eq ι] variables [field K] [add_comm_group V] [vector_space K V] local notation `V'` := dual K V /-- `e` and `ε` have characteristic properties of a basis and its dual -/ structure dual_pair (e : ι → V) (ε : ι → V') := (eval : ∀ i j : ι, ε i (e j) = if i = j then 1 else 0) (total : ∀ {v : V}, (∀ i, ε i v = 0) → v = 0) [finite : ∀ v : V, fintype {i | ε i v ≠ 0}] end dual_pair namespace dual_pair open vector_space module module.dual linear_map function universes u v w variables {K : Type u} {V : Type v} {ι : Type w} [dι : decidable_eq ι] variables [field K] [add_comm_group V] [vector_space K V] variables {e : ι → V} {ε : ι → dual K V} (h : dual_pair e ε) include h /-- The coefficients of `v` on the basis `e` -/ def coeffs (v : V) : ι →₀ K := { to_fun := λ i, ε i v, support := by { haveI := h.finite v, exact {i : ι | ε i v ≠ 0}.to_finset }, mem_support_to_fun := by {intro i, rw set.mem_to_finset, exact iff.rfl } } @[simp] lemma coeffs_apply (v : V) (i : ι) : h.coeffs v i = ε i v := rfl omit h private def help_tcs : has_scalar K V := mul_action.to_has_scalar local attribute [instance] help_tcs /-- linear combinations of elements of `e`. This is a convenient abbreviation for `finsupp.total _ V K e l` -/ def lc (e : ι → V) (l : ι →₀ K) : V := l.sum (λ (i : ι) (a : K), a • (e i)) include h lemma dual_lc (l : ι →₀ K) (i : ι) : ε i (dual_pair.lc e l) = l i := begin erw linear_map.map_sum, simp only [h.eval, map_smul, smul_eq_mul], rw finset.sum_eq_single i, { simp }, { intros q q_in q_ne, simp [q_ne.symm] }, { intro p_not_in, simp [finsupp.not_mem_support_iff.1 p_not_in] }, end @[simp] lemma coeffs_lc (l : ι →₀ K) : h.coeffs (dual_pair.lc e l) = l := by { ext i, rw [h.coeffs_apply, h.dual_lc] } /-- For any v : V n, \sum_{p ∈ Q n} (ε p v) • e p = v -/ lemma decomposition (v : V) : dual_pair.lc e (h.coeffs v) = v := begin refine eq_of_sub_eq_zero (h.total _), intros i, simp [-sub_eq_add_neg, linear_map.map_sub, h.dual_lc, sub_eq_zero_iff_eq] end lemma mem_of_mem_span {H : set ι} {x : V} (hmem : x ∈ submodule.span K (e '' H)) : ∀ i : ι, ε i x ≠ 0 → i ∈ H := begin intros i hi, rcases (finsupp.mem_span_iff_total _).mp hmem with ⟨l, supp_l, sum_l⟩, change dual_pair.lc e l = x at sum_l, rw finsupp.mem_supported' at supp_l, apply classical.by_contradiction, intro i_not, apply hi, rw ← sum_l, simpa [h.dual_lc] using supp_l i i_not end lemma is_basis : is_basis K e := begin split, { rw linear_independent_iff, intros l H, change dual_pair.lc e l = 0 at H, ext i, apply_fun ε i at H, simpa [h.dual_lc] using H }, { rw submodule.eq_top_iff', intro v, rw [← set.image_univ, finsupp.mem_span_iff_total], exact ⟨h.coeffs v, by simp, h.decomposition v⟩ }, end lemma eq_dual : ε = is_basis.dual_basis h.is_basis := begin funext i, refine h.is_basis.ext (λ _, _), erw [is_basis.to_dual_apply, h.eval] end end dual_pair
cbf2bc3fe7f121fead71c083f9059308273bf233
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/tuple.lean
8bd35a027b29237374f7a7e5610fa9722bb6ac7d
[ "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
156
lean
open nat prod set_option pp.universes true definition {u} tuple (A : Type (u+1)) (n : nat) : Type (u+1) := nat.rec_on n A (λ n r, r × A) check @tuple
cb1073f0233c4565316cdd9ceaf4e0f53fac1f9c
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/bicategory/natural_transformation.lean
08f8db6d452fe61dada189cb28d8b812c316ab93
[ "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
9,357
lean
/- Copyright (c) 2022 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import category_theory.bicategory.functor /-! # Oplax natural transformations Just as there are natural transformations between functors, there are oplax natural transformations between oplax functors. The equality in the naturality of natural transformations is replaced by a specified 2-morphism `F.map f ≫ app b ⟶ app a ≫ G.map f` in the case of oplax natural transformations. ## Main definitions * `oplax_nat_trans F G` : oplax natural transformations between oplax functors `F` and `G` * `oplax_nat_trans.vcomp η θ` : the vertical composition of oplax natural transformations `η` and `θ` * `oplax_nat_trans.category F G` : the category structure on the oplax natural transformations between `F` and `G` -/ namespace category_theory open category bicategory open_locale bicategory universes w₁ w₂ v₁ v₂ u₁ u₂ variables {B : Type u₁} [bicategory.{w₁ v₁} B] {C : Type u₂} [bicategory.{w₂ v₂} C] /-- If `η` is an oplax natural transformation between `F` and `G`, we have a 1-morphism `η.app a : F.obj a ⟶ G.obj a` for each object `a : B`. We also have a 2-morphism `η.naturality f : F.map f ≫ app b ⟶ app a ≫ G.map f` for each 1-morphism `f : a ⟶ b`. These 2-morphisms satisfies the naturality condition, and preserve the identities and the compositions modulo some adjustments of domains and codomains of 2-morphisms. -/ structure oplax_nat_trans (F G : oplax_functor B C) := (app (a : B) : F.obj a ⟶ G.obj a) (naturality {a b : B} (f : a ⟶ b) : F.map f ≫ app b ⟶ app a ≫ G.map f) (naturality_naturality' : ∀ {a b : B} {f g : a ⟶ b} (η : f ⟶ g), F.map₂ η ▷ app b ≫ naturality g = naturality f ≫ app a ◁ G.map₂ η . obviously) (naturality_id' : ∀ a : B, naturality (𝟙 a) ≫ app a ◁ G.map_id a = F.map_id a ▷ app a ≫ (λ_ (app a)).hom ≫ (ρ_ (app a)).inv . obviously) (naturality_comp' : ∀ {a b c : B} (f : a ⟶ b) (g : b ⟶ c), naturality (f ≫ g) ≫ app a ◁ G.map_comp f g = F.map_comp f g ▷ app c ≫ (α_ _ _ _).hom ≫ F.map f ◁ naturality g ≫ (α_ _ _ _).inv ≫ naturality f ▷ G.map g ≫ (α_ _ _ _).hom . obviously) restate_axiom oplax_nat_trans.naturality_naturality' restate_axiom oplax_nat_trans.naturality_id' restate_axiom oplax_nat_trans.naturality_comp' attribute [simp, reassoc] oplax_nat_trans.naturality_naturality oplax_nat_trans.naturality_id oplax_nat_trans.naturality_comp namespace oplax_nat_trans section variables (F : oplax_functor B C) /-- The identity oplax natural transformation. -/ @[simps] def id : oplax_nat_trans F F := { app := λ a, 𝟙 (F.obj a), naturality := λ a b f, (ρ_ (F.map f)).hom ≫ (λ_ (F.map f)).inv } instance : inhabited (oplax_nat_trans F F) := ⟨id F⟩ variables {F} {G H : oplax_functor B C} (η : oplax_nat_trans F G) (θ : oplax_nat_trans G H) section variables {a b c : B} {a' : C} @[simp, reassoc] lemma whisker_left_naturality_naturality (f : a' ⟶ G.obj a) {g h : a ⟶ b} (β : g ⟶ h) : f ◁ G.map₂ β ▷ θ.app b ≫ f ◁ θ.naturality h = f ◁ θ.naturality g ≫ f ◁ θ.app a ◁ H.map₂ β := by simp_rw [←bicategory.whisker_left_comp, naturality_naturality] @[simp, reassoc] lemma whisker_right_naturality_naturality {f g : a ⟶ b} (β : f ⟶ g) (h : G.obj b ⟶ a') : F.map₂ β ▷ η.app b ▷ h ≫ η.naturality g ▷ h = η.naturality f ▷ h ≫ (α_ _ _ _).hom ≫ η.app a ◁ G.map₂ β ▷ h ≫ (α_ _ _ _).inv := by rw [←comp_whisker_right, naturality_naturality, comp_whisker_right, whisker_assoc] @[simp, reassoc] lemma whisker_left_naturality_comp (f : a' ⟶ G.obj a) (g : a ⟶ b) (h : b ⟶ c) : f ◁ θ.naturality (g ≫ h) ≫ f ◁ θ.app a ◁ H.map_comp g h = f ◁ G.map_comp g h ▷ θ.app c ≫ f ◁ (α_ _ _ _).hom ≫ f ◁ G.map g ◁ θ.naturality h ≫ f ◁ (α_ _ _ _).inv ≫ f ◁ θ.naturality g ▷ H.map h ≫ f ◁ (α_ _ _ _).hom := by simp_rw [←bicategory.whisker_left_comp, naturality_comp] @[simp, reassoc] lemma whisker_right_naturality_comp (f : a ⟶ b) (g : b ⟶ c) (h : G.obj c ⟶ a') : η.naturality (f ≫ g) ▷ h ≫ (α_ _ _ _).hom ≫ η.app a ◁ G.map_comp f g ▷ h = F.map_comp f g ▷ η.app c ▷ h ≫ (α_ _ _ _).hom ▷ h ≫ (α_ _ _ _).hom ≫ F.map f ◁ η.naturality g ▷ h ≫ (α_ _ _ _).inv ≫ (α_ _ _ _).inv ▷ h ≫ η.naturality f ▷ G.map g ▷ h ≫ (α_ _ _ _).hom ▷ h ≫ (α_ _ _ _).hom := by { rw [←associator_naturality_middle, ←comp_whisker_right_assoc, naturality_comp], simp } @[simp, reassoc] lemma whisker_left_naturality_id (f : a' ⟶ G.obj a) : f ◁ θ.naturality (𝟙 a) ≫ f ◁ θ.app a ◁ H.map_id a = f ◁ G.map_id a ▷ θ.app a ≫ f ◁ (λ_ (θ.app a)).hom ≫ f ◁ (ρ_ (θ.app a)).inv := by simp_rw [←bicategory.whisker_left_comp, naturality_id] @[simp, reassoc] lemma whisker_right_naturality_id (f : G.obj a ⟶ a') : η.naturality (𝟙 a) ▷ f ≫ (α_ _ _ _).hom ≫ η.app a ◁ G.map_id a ▷ f = F.map_id a ▷ η.app a ▷ f ≫ (λ_ (η.app a)).hom ▷ f ≫ (ρ_ (η.app a)).inv ▷ f ≫ (α_ _ _ _).hom := by { rw [←associator_naturality_middle, ←comp_whisker_right_assoc, naturality_id], simp } end /-- Vertical composition of oplax natural transformations. -/ @[simps] def vcomp (η : oplax_nat_trans F G) (θ : oplax_nat_trans G H) : oplax_nat_trans F H := { app := λ a, η.app a ≫ θ.app a, naturality := λ a b f, (α_ _ _ _).inv ≫ η.naturality f ▷ θ.app b ≫ (α_ _ _ _).hom ≫ η.app a ◁ θ.naturality f ≫ (α_ _ _ _).inv, naturality_comp' := λ a b c f g, by { calc _ = _ ≫ F.map_comp f g ▷ η.app c ▷ θ.app c ≫ _ ≫ F.map f ◁ η.naturality g ▷ θ.app c ≫ _ ≫ (F.map f ≫ η.app b) ◁ θ.naturality g ≫ η.naturality f ▷ (θ.app b ≫ H.map g) ≫ _ ≫ η.app a ◁ θ.naturality f ▷ H.map g ≫ _ : _ ... = _ : _, exact (α_ _ _ _).inv, exact (α_ _ _ _).hom ▷ _ ≫ (α_ _ _ _).hom, exact _ ◁ (α_ _ _ _).hom ≫ (α_ _ _ _).inv, exact (α_ _ _ _).hom ≫ _ ◁ (α_ _ _ _).inv, exact _ ◁ (α_ _ _ _).hom ≫ (α_ _ _ _).inv, { rw [whisker_exchange_assoc], simp }, { simp } } } variables (B C) @[simps] instance : category_struct (oplax_functor B C) := { hom := oplax_nat_trans, id := oplax_nat_trans.id, comp := λ F G H, oplax_nat_trans.vcomp } end section variables {F G : oplax_functor B C} /-- A modification `Γ` between oplax natural transformations `η` and `θ` consists of a family of 2-morphisms `Γ.app a : η.app a ⟶ θ.app a`, which satisfies the equation `(F.map f ◁ app b) ≫ θ.naturality f = η.naturality f ≫ (app a ▷ G.map f)` for each 1-morphism `f : a ⟶ b`. -/ @[ext] structure modification (η θ : F ⟶ G) := (app (a : B) : η.app a ⟶ θ.app a) (naturality' : ∀ {a b : B} (f : a ⟶ b), (F.map f ◁ app b) ≫ θ.naturality f = η.naturality f ≫ (app a ▷ G.map f) . obviously) restate_axiom modification.naturality' attribute [simp, reassoc] modification.naturality variables {η θ ι : F ⟶ G} namespace modification variables (η) /-- The identity modification. -/ @[simps] def id : modification η η := { app := λ a, 𝟙 (η.app a) } instance : inhabited (modification η η) := ⟨modification.id η⟩ variables {η} section variables (Γ : modification η θ) {a b c : B} {a' : C} @[simp, reassoc] lemma whisker_left_naturality (f : a' ⟶ F.obj b) (g : b ⟶ c) : f ◁ F.map g ◁ Γ.app c ≫ f ◁ θ.naturality g = f ◁ η.naturality g ≫ f ◁ Γ.app b ▷ G.map g := by simp_rw [←bicategory.whisker_left_comp, naturality] @[simp, reassoc] lemma whisker_right_naturality (f : a ⟶ b) (g : G.obj b ⟶ a') : F.map f ◁ Γ.app b ▷ g ≫ (α_ _ _ _).inv ≫ θ.naturality f ▷ g = (α_ _ _ _).inv ≫ η.naturality f ▷ g ≫ Γ.app a ▷ G.map f ▷ g := by simp_rw [associator_inv_naturality_middle_assoc, ←comp_whisker_right, naturality] end /-- Vertical composition of modifications. -/ @[simps] def vcomp (Γ : modification η θ) (Δ : modification θ ι) : modification η ι := { app := λ a, Γ.app a ≫ Δ.app a } end modification /-- Category structure on the oplax natural transformations between oplax_functors. -/ @[simps] instance category (F G : oplax_functor B C) : category (F ⟶ G) := { hom := modification, id := modification.id, comp := λ η θ ι, modification.vcomp } /-- Construct a modification isomorphism between oplax natural transformations by giving object level isomorphisms, and checking naturality only in the forward direction. -/ @[simps] def modification_iso.of_components (app : ∀ a, η.app a ≅ θ.app a) (naturality : ∀ {a b} (f : a ⟶ b), F.map f ◁ (app b).hom ≫ θ.naturality f = η.naturality f ≫ (app a).hom ▷ G.map f) : η ≅ θ := { hom := { app := λ a, (app a).hom }, inv := { app := λ a, (app a).inv, naturality' := λ a b f, by simpa using congr_arg (λ f, _ ◁ (app b).inv ≫ f ≫ (app a).inv ▷ _) (naturality f).symm } } end end oplax_nat_trans end category_theory
52498746b04eee4e5f8dcff0e8558c3d3e1a7cf0
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/finset/lattice.lean
f78feb594e6c2ba934c4b8cc5ca11c88fce16a32
[ "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
30,906
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.finset.fold import data.multiset.lattice import order.order_dual import order.complete_lattice /-! # Lattice operations on finsets -/ variables {α β γ : Type*} namespace finset open multiset order_dual /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma sup_const {s : finset β} (h : s.nonempty) (c : α) : s.sup (λ _, c) = c := eq_of_forall_ge_iff $ λ b, sup_le_iff.trans h.forall_const lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb @[simp] lemma map_sup (f : γ ↪ β) (g : β → α) (s : finset γ) : (s.map f).sup g = s.sup (g ∘ f) := by simp [finset.sup] lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [g_sup] {contextual := tt}) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot /-- Computating `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ lemma sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)} (t : finset β) (f : β → {x : α // P x}) : (@sup _ _ (subtype.semilattice_sup_bot Pbot Psup) t f : α) = t.sup (λ x, f x) := by { classical, rw [comp_sup_eq_sup_comp coe]; intros; refl } @[simp] lemma sup_to_finset {α β} [decidable_eq β] (s : finset α) (f : α → multiset β) : (s.sup f).to_finset = s.sup (λ x, (f x).to_finset) := comp_sup_eq_sup_comp multiset.to_finset to_finset_union rfl theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ lemma sup_subset {α β} [semilattice_sup_bot β] {s t : finset α} (hst : s ⊆ t) (f : α → β) : s.sup f ≤ t.sup f := by classical; calc t.sup f = (s ∪ t).sup f : by rw [finset.union_eq_right_iff_subset.mpr hst] ... = s.sup f ⊔ t.sup f : by rw finset.sup_union ... ≥ s.sup f : le_sup_left lemma sup_closed_of_sup_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊔ b ∈ s) : t.sup id ∈ s := begin classical, induction t using finset.induction_on with x t h₀ h₁, { exfalso, apply finset.not_nonempty_empty htne, }, { rw [finset.coe_insert, set.insert_subset] at h_subset, cases t.eq_empty_or_nonempty with hte htne, { subst hte, simp only [insert_emptyc_eq, id.def, finset.sup_singleton, h_subset], }, { rw [finset.sup_insert, id.def], exact h h_subset.1 (h₁ htne h_subset.2), }, }, end lemma sup_le_of_le_directed {α : Type*} [semilattice_sup_bot α] (s : set α) (hs : s.nonempty) (hdir : directed_on (≤) s) (t : finset α): (∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x, x ∈ s ∧ t.sup id ≤ x := begin classical, apply finset.induction_on t, { simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff, sup_empty, forall_true_iff, not_mem_empty], }, { intros a r har ih h, have incs : ↑r ⊆ ↑(insert a r), by { rw finset.coe_subset, apply finset.subset_insert, }, -- x ∈ s is above the sup of r obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih (λ x hx, h x $ incs hx), -- y ∈ s is above a obtain ⟨y, hys, hay⟩ := h a (finset.mem_insert_self a r), -- z ∈ s is above x and y obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys, use [z, hzs], rw [sup_insert, id.def, _root_.sup_le_iff], exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩, }, end end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) lemma sup_eq_Sup [complete_lattice α] (s : finset α) : s.sup id = Sup s := by simp [Sup_eq_supr, sup_eq_supr] lemma exists_mem_eq_sup [complete_linear_order β] (s : finset α) (h : s.nonempty) (f : α → β) : ∃ a, a ∈ s ∧ s.sup f = f a := begin classical, induction s using finset.induction_on with x xs hxm ih, { exact (not_nonempty_empty h).elim, }, { rw sup_insert, by_cases hx : xs.sup f ≤ f x, { refine ⟨x, mem_insert_self _ _, sup_eq_left.mpr hx⟩, }, by_cases hxs : xs.nonempty, { obtain ⟨a, ham, ha⟩ := ih hxs, refine ⟨a, mem_insert_of_mem ham, _⟩, simpa only [ha, sup_eq_right] using le_of_not_le hx, }, { rw not_nonempty_iff_eq_empty.mp hxs, refine ⟨x, mem_singleton_self _, _⟩, simp, } } end /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union (order_dual α) _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 @[simp] lemma map_inf (f : γ ↪ β) (g : β → α) (s : finset γ) : (s.map f).inf g = s.inf (g ∘ f) := by simp [finset.inf] lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf_iff [h : is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ (@is_total.swap α _ h) _ ha lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top /-- Computating `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ lemma inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)} (t : finset β) (f : β → {x : α // P x}) : (@inf _ _ (subtype.semilattice_inf_top Ptop Pinf) t f : α) = t.inf (λ x, f x) := by { classical, rw [comp_inf_eq_inf_comp coe]; intros; refl } end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ lemma inf_eq_Inf [complete_lattice α] (s : finset α) : s.inf id = Inf s := by simp [Inf_eq_infi, inf_eq_infi] lemma exists_mem_eq_inf [complete_linear_order β] (s : finset α) (h : s.nonempty) (f : α → β) : ∃ a, a ∈ s ∧ s.inf f = f a := @exists_mem_eq_sup _ (order_dual β) _ _ h _ /-! ### max and min of finite sets -/ section max_min variables [linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := @mem_of_max (order_dual α) _ s theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ theorem is_least_min' : is_least ↑s (s.min' H) := ⟨min'_mem _ _, min'_le _⟩ @[simp] lemma le_min'_iff {x} : x ≤ s.min' H ↔ ∀ y ∈ s, x ≤ y := le_is_glb_iff (is_least_min' s H).is_glb /-- `{a}.min' _` is `a`. -/ @[simp] lemma min'_singleton (a : α) : ({a} : finset α).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ theorem is_greatest_max' : is_greatest ↑s (s.max' H) := ⟨max'_mem _ _, le_max' _⟩ @[simp] lemma max'_le_iff {x} : s.max' H ≤ x ↔ ∀ y ∈ s, y ≤ x := is_lub_le_iff (is_greatest_max' s H).is_lub /-- `{a}.max' _` is `a`. -/ @[simp] lemma max'_singleton (a : α) : ({a} : finset α).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := is_glb_lt_is_lub_of_ne (s.is_least_min' _).is_glb (s.is_greatest_max' _).is_lub H1 H2 H3 /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) < s.max' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) := begin rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩, exact s.min'_lt_max' ha hb hab end lemma max'_eq_of_dual_min' {s : finset α} (hs : s.nonempty) : max' s hs = of_dual (min' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end lemma min'_eq_of_dual_max' {s : finset α} (hs : s.nonempty) : min' s hs = of_dual (max' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end @[simp] lemma of_dual_max_eq_min_of_dual {a b : α} : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_min_eq_max_of_dual {a b : α} : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl lemma max'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) : s.max' H ≤ t.max' (H.mono hst) := le_max' _ _ (hst (s.max'_mem H)) lemma min'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) : t.min' (H.mono hst) ≤ s.min' H := min'_le _ _ (hst (s.min'_mem H)) lemma max'_insert (a : α) (s : finset α) (H : s.nonempty) : (insert a s).max' (s.insert_nonempty a) = max (s.max' H) a := (is_greatest_max' _ _).unique $ by { rw [coe_insert, max_comm], exact (is_greatest_max' _ _).insert _ } lemma min'_insert (a : α) (s : finset α) (H : s.nonempty) : (insert a s).min' (s.insert_nonempty a) = min (s.min' H) a := (is_least_min' _ _).unique $ by { rw [coe_insert, min_comm], exact (is_least_min' _ _).insert _ } /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` strictly greater than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_max [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, x < a) → p s → p (insert a s)) : p s := begin induction hn : s.card with n ihn generalizing s, { rwa [card_eq_zero.1 hn] }, { have A : s.nonempty, from card_pos.1 (hn.symm ▸ n.succ_pos), have B : s.max' A ∈ s, from max'_mem s A, rw [← insert_erase B], refine step _ _ (λ x hx, _) (ihn _ _), { rw [mem_erase] at hx, exact (le_max' s x hx.2).lt_of_ne hx.1 }, { rw [card_erase_of_mem B, hn, nat.pred_succ] } } end /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` strictly less than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_min [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, a < x) → p s → p (insert a s)) : p s := @induction_on_max (order_dual α) _ _ _ s h0 step end max_min section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → multiset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin classical, apply s.induction_on, { simp }, { intros a s has hxs, rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union], split, { intro hxi, cases hxi with hf hf, { refine ⟨a, _, hf⟩, simp only [true_or, eq_self_iff_true, finset.mem_insert] }, { rcases hxs.mp hf with ⟨v, hv, hfv⟩, refine ⟨v, _, hfv⟩, simp only [hv, or_true, finset.mem_insert] } }, { rintros ⟨v, hv, hfv⟩, rw [finset.mem_insert] at hv, rcases hv with rfl | hv, { exact or.inl hfv }, { refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } }, end end multiset namespace finset lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → finset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin change _ ↔ ∃ v ∈ s, x ∈ (f v).val, rw [←multiset.mem_sup, ←multiset.mem_to_finset, sup_to_finset], simp_rw [val_to_finset], end lemma sup_eq_bUnion {α β} [decidable_eq β] (s : finset α) (t : α → finset β) : s.sup t = s.bUnion t := by { ext, rw [mem_sup, mem_bUnion], } end finset section lattice variables {ι : Type*} {ι' : Sort*} [complete_lattice α] /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `supr_eq_supr_finset'` for a version that works for `ι : Sort*`. -/ lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset ι, ⨆i∈t, s i) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `supr_eq_supr_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma supr_eq_supr_finset' (s : ι' → α) : (⨆i, s i) = (⨆t:finset (plift ι'), ⨆i∈t, s (plift.down i)) := by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `infi_eq_infi_finset'` for a version that works for `ι : Sort*`. -/ lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset ι, ⨅i∈t, s i) := @supr_eq_supr_finset (order_dual α) _ _ _ /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `infi_eq_infi_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma infi_eq_infi_finset' (s : ι' → α) : (⨅i, s i) = (⨅t:finset (plift ι'), ⨅i∈t, s (plift.down i)) := @supr_eq_supr_finset' (order_dual α) _ _ _ end lattice namespace set variables {ι : Type*} {ι' : Sort*} /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version assumes `ι : Type*`. See also `Union_eq_Union_finset'` for a version that works for `ι : Sort*`. -/ lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset ι, ⋃i∈t, s i) := supr_eq_supr_finset s /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version works for `ι : Sort*`. See also `Union_eq_Union_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Union_eq_Union_finset' (s : ι' → set α) : (⋃i, s i) = (⋃t:finset (plift ι'), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset' s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ι : Type*`. See also `Inter_eq_Inter_finset'` for a version that works for `ι : Sort*`. -/ lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset ι, ⋂i∈t, s i) := infi_eq_infi_finset s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version works for `ι : Sort*`. See also `Inter_eq_Inter_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Inter_eq_Inter_finset' (s : ι' → set α) : (⋂i, s i) = (⋂t:finset (plift ι'), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset' s end set namespace finset open function /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp lemma supr_option_to_finset (o : option α) (f : α → β) : (⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x := by { congr, ext, rw [option.mem_to_finset] } lemma infi_option_to_finset (o : option α) (f : α → β) : (⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x := @supr_option_to_finset _ (order_dual β) _ _ _ variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := by simp [infi_or, infi_inf_eq] lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := by { rw insert_eq, simp only [infi_union, finset.infi_singleton] } lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma sup_finset_image {β γ : Type*} [semilattice_sup_bot β] (f : γ → α) (g : α → β) (s : finset γ) : (s.image f).sup g = s.sup (g ∘ f) := begin classical, apply finset.induction_on s, { simp }, { intros a s' ha ih, rw [sup_insert, image_insert, sup_insert, ih] } end lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] lemma supr_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨆ (i ∈ insert x t), function.update f x s i) = (s ⊔ ⨆ (i ∈ t), f i) := begin simp only [finset.supr_insert, update_same], rcongr i hi, apply update_noteq, rintro rfl, exact hx hi end lemma infi_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨅ (i ∈ insert x t), update f x s i) = (s ⊓ ⨅ (i ∈ t), f i) := @supr_insert_update α (order_dual β) _ _ _ _ f _ hx lemma supr_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := calc (⨆ y ∈ s.bUnion t, f y) = ⨆ y (hy : ∃ x ∈ s, y ∈ t x), f y : congr_arg _ $ funext $ λ y, by rw [mem_bUnion] ... = _ : by simp only [supr_exists, @supr_comm _ α] lemma infi_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨅ y ∈ s.bUnion t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y := @supr_bUnion _ (order_dual β) _ _ _ _ _ _ end lattice @[simp] theorem set_bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl @[simp] theorem set_bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl @[simp] theorem set_bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s @[simp] theorem set_bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s @[simp] lemma set_bUnion_preimage_singleton (f : α → β) (s : finset β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' ↑s := set.bUnion_preimage_singleton f ↑s @[simp] lemma set_bUnion_option_to_finset (o : option α) (f : α → set β) : (⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x := supr_option_to_finset o f @[simp] lemma set_bInter_option_to_finset (o : option α) (f : α → set β) : (⋂ x ∈ o.to_finset, f x) = ⋂ x ∈ o, f x := infi_option_to_finset o f variables [decidable_eq α] lemma set_bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma set_bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union @[simp] lemma set_bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t @[simp] lemma set_bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t @[simp] lemma set_bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image @[simp] lemma set_bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image lemma set_bUnion_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∪ ⋃ (i ∈ t), f i) := supr_insert_update f hx lemma set_bInter_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋂ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ ⋂ (i ∈ t), f i) := infi_insert_update f hx @[simp] lemma set_bUnion_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋃ y ∈ s.bUnion t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y := supr_bUnion s t f @[simp] lemma set_bInter_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋂ y ∈ s.bUnion t, f y) = ⋂ (x ∈ s) (y ∈ t x), f y := infi_bUnion s t f end finset
c241a26f38745b722482878c3f150420673e83b8
4f065978c49388d188224610d9984673079f7d91
/direct_limit.lean
0c38b2737d07f27d6f0eb6e80a39ade5b81e2905
[]
no_license
kckennylau/Lean
b323103f52706304907adcfaee6f5cb8095d4a33
907d0a4d2bd8f23785abd6142ad53d308c54fdcb
refs/heads/master
1,624,623,720,653
1,563,901,820,000
1,563,901,820,000
109,506,702
3
1
null
null
null
null
UTF-8
Lean
false
false
21,300
lean
import algebra.ring order.lattice data.pnat data.rat universes u v theorem congr_arg₂ {α β γ : Type*} (f : α → β → γ) {x₁ x₂ : α} {y₁ y₂ : β} (Hx : x₁ = x₂) (Hy : y₁ = y₂) : f x₁ y₁ = f x₂ y₂ := eq.drec (eq.drec rfl Hy) Hx open lattice def is_add_group_hom {α : Type*} {β : Type*} [add_group α] [add_group β] (f : α → β) : Prop := @is_group_hom (multiplicative α) (multiplicative β) _ _ f attribute [class] is_add_group_hom namespace is_add_group_hom variables {α : Type*} {β : Type*} [add_group α] [add_group β] (f : α → β) [hf : is_add_group_hom f] theorem mk (H : ∀ x y, f (x + y) = f x + f y) : is_add_group_hom f := ⟨H⟩ theorem add (x y) : f (x + y) = f x + f y := @is_group_hom.mul (multiplicative α) (multiplicative β) _ _ f hf x y theorem zero : f 0 = 0 := @is_group_hom.one (multiplicative α) (multiplicative β) _ _ f hf theorem neg (x) : f (-x) = -f x := @is_group_hom.inv (multiplicative α) (multiplicative β) _ _ f hf x end is_add_group_hom instance is_ring_hom.to_is_add_group_hom {α : Type*} {β : Type*} [ring α] [ring β] (f : α → β) [is_ring_hom f] : is_add_group_hom f := ⟨λ _ _, is_ring_hom.map_add f⟩ class directed_order (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) theorem le_sup_left {α : Type u} [directed_order α] {x y : α} : x ≤ x ⊔ y := directed_order.le_sup_left x y theorem le_sup_right {α : Type u} [directed_order α] {x y : α} : y ≤ x ⊔ y := directed_order.le_sup_right x y variables {ι : out_param (Type u)} [inhabited ι] [directed_order ι] variables {G : ι → Type v} class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (Hcomp : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) def direct_limit.setoid (f : Π i j, i ≤ j → G i → G j) [directed_system f] : setoid (sigma G) := ⟨λ i j, ∃ k (hik : i.1 ≤ k) (hjk : j.1 ≤ k), f i.1 k hik i.2 = f j.1 k hjk j.2, λ i, ⟨i.1, le_refl i.1, le_refl i.1, rfl⟩, λ i j ⟨k, hik, hjk, H⟩, ⟨k, hjk, hik, H.symm⟩, λ i j k ⟨ij, hiij, hjij, hij⟩ ⟨jk, hjjk, hkjk, hjk⟩, ⟨ij ⊔ jk, le_trans hiij le_sup_left, le_trans hkjk le_sup_right, calc f i.1 (ij ⊔ jk) _ i.2 = f ij (ij ⊔ jk) _ (f i.1 ij _ i.2) : eq.symm $ directed_system.Hcomp f _ _ _ _ _ _ ... = f ij (ij ⊔ jk) _ (f j.1 ij _ j.2) : congr_arg _ hij ... = f j.1 (ij ⊔ jk) _ j.2 : directed_system.Hcomp f _ _ _ _ _ _ ... = f jk (ij ⊔ jk) _ (f j.1 jk _ j.2) : eq.symm $ directed_system.Hcomp f _ _ _ _ _ _ ... = f jk (ij ⊔ jk) _ (f k.1 jk _ k.2) : congr_arg _ hjk ... = f k.1 (ij ⊔ jk) _ k.2 : directed_system.Hcomp f _ _ _ _ _ _⟩⟩ local attribute [instance] direct_limit.setoid def direct_limit (f : Π i j, i ≤ j → G i → G j) [directed_system f] : Type (max u v) := quotient (direct_limit.setoid f) namespace direct_limit variables (f : Π i j, i ≤ j → G i → G j) [directed_system f] def of (i x) : direct_limit f := ⟦⟨i, x⟩⟧ theorem of_f {i j hij x} : (of f j (f i j hij x)) = of f i x := quotient.sound ⟨j, le_refl j, hij, directed_system.Hcomp f _ _ _ _ _ _⟩ variables {P : Type*} (g : Π i, G i → P) variable (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) def rec (x : direct_limit f) : P := quotient.lift_on x (λ i, g i.1 i.2) $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨t, hpt, hqt, hpqt⟩, calc g p xp = g t (f p t hpt xp) : eq.symm $ Hg p t hpt xp ... = g t (f q t hqt xq) : congr_arg _ hpqt ... = g q xq : Hg q t hqt xq lemma rec_of {i} (x) : rec f g Hg (of f i x) = g i x := rfl end direct_limit namespace directed_system variables [∀ i, add_comm_group (G i)] (f : Π i j, i ≤ j → G i → G j) variables [∀ i j h, is_add_group_hom (f i j h)] [directed_system f] theorem map_add {i j k m xi xj hik hjk hkm} : f k m hkm (f i k hik xi + f j k hjk xj) = f i m (le_trans hik hkm) xi + f j m (le_trans hjk hkm) xj := (is_add_group_hom.add _ _ _).trans $ congr_arg₂ (+) (directed_system.Hcomp f _ _ _ _ _ _) (directed_system.Hcomp f _ _ _ _ _ _) theorem add {i j hij x y} : f i j hij (x + y) = f i j hij x + f i j hij y := is_add_group_hom.add _ _ _ theorem zero {i j hij} : f i j hij 0 = 0 := is_add_group_hom.zero _ theorem neg {i j hij x} : f i j hij (-x) = -f i j hij x := is_add_group_hom.neg _ _ end directed_system namespace directed_system variables [∀ i, ring (G i)] (f : Π i j, i ≤ j → G i → G j) variables [∀ i j h, is_ring_hom (f i j h)] [directed_system f] theorem map_mul {i j k m xi xj hik hjk hkm} : f k m hkm (f i k hik xi * f j k hjk xj) = f i m (le_trans hik hkm) xi * f j m (le_trans hjk hkm) xj := (is_ring_hom.map_mul _).trans $ congr_arg₂ (*) (directed_system.Hcomp f _ _ _ _ _ _) (directed_system.Hcomp f _ _ _ _ _ _) theorem mul {i j hij x y} : f i j hij (x * y) = f i j hij x * f i j hij y := is_ring_hom.map_mul _ theorem one {i j hij} : f i j hij 1 = 1 := is_ring_hom.map_one _ end directed_system namespace direct_limit variables [∀ i, add_comm_group (G i)] (f : Π i j, i ≤ j → G i → G j) variables [∀ i j h, is_add_group_hom (f i j h)] [directed_system f] local attribute [instance] direct_limit.setoid instance add_comm_group' : add_comm_group (quotient (direct_limit.setoid f)) := { add := λ i j, quotient.lift_on₂ i j (λ xi xj, ⟦⟨xi.1 ⊔ xj.1, f xi.1 (xi.1 ⊔ xj.1) le_sup_left xi.2 + f xj.1 (xi.1 ⊔ xj.1) le_sup_right xj.2⟩⟧ : sigma G → sigma G → quotient (direct_limit.setoid f)) (λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩ ⟨s, xs⟩ ⟨t, hpt, hrt, hprt⟩ ⟨u, hqu, hsu, hqsu⟩, quotient.sound $ ⟨(p ⊔ q) ⊔ (r ⊔ s) ⊔ (t ⊔ u), le_trans le_sup_left le_sup_left, le_trans le_sup_right le_sup_left, calc f (p ⊔ q) (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans le_sup_left le_sup_left) (f p (p ⊔ q) le_sup_left xp + f q (p ⊔ q) le_sup_right xq) = f p (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans hpt (le_trans le_sup_left le_sup_right)) xp + f q (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans hqu (le_trans le_sup_right le_sup_right)) xq : directed_system.map_add f ... = f t (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f p t hpt xp) + f u (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f q u hqu xq) : congr_arg₂ (+) (directed_system.Hcomp f _ _ _ _ _ _).symm (directed_system.Hcomp f _ _ _ _ _ _).symm ... = f t (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f r t hrt xr) + f u (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f s u hsu xs) : congr_arg₂ (+) (congr_arg _ hprt) (congr_arg _ hqsu) ... = f r (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ xr + f s (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ xs : congr_arg₂ (+) (directed_system.Hcomp f _ _ _ _ _ _) (directed_system.Hcomp f _ _ _ _ _ _) ... = f (r ⊔ s) (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans le_sup_right le_sup_left) (f r (r ⊔ s) le_sup_left xr + f s (r ⊔ s) le_sup_right xs) : eq.symm $ directed_system.map_add f⟩), add_assoc := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨((p ⊔ q) ⊔ r) ⊔ (p ⊔ (q ⊔ r)), le_sup_left, le_sup_right, by dsimp; simp [directed_system.map_add f, directed_system.add f, directed_system.Hcomp f, -add_comm]⟩, zero := ⟦⟨default _, 0⟩⟧, zero_add := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound ⟨default _ ⊔ p, le_refl _, le_sup_right, by dsimp; simp [directed_system.map_add f, directed_system.zero f, directed_system.Hcomp f]⟩, add_zero := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound ⟨p ⊔ default ι, le_refl _, le_sup_left, by dsimp; simp [directed_system.map_add f, directed_system.zero f, directed_system.Hcomp f]⟩, neg := λ i, quotient.lift_on i (λ p, ⟦⟨p.1, -p.2⟩⟧ : sigma G → quotient (direct_limit.setoid f)) $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨t, hpt, hqt, hpqt⟩, quotient.sound $ ⟨t, hpt, hqt, by dsimp at hpqt ⊢; simp [directed_system.neg f, hpqt]⟩, add_left_neg := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound $ ⟨(p ⊔ p) ⊔ default ι, le_sup_left, le_sup_right, by dsimp; simp [directed_system.map_add f, directed_system.neg f, directed_system.zero f]⟩, add_comm := λ i j, quotient.induction_on₂ i j $ λ ⟨p, xp⟩ ⟨q, xq⟩, quotient.sound ⟨(p ⊔ q) ⊔ (q ⊔ p), le_sup_left, le_sup_right, by dsimp; simp [directed_system.map_add f]⟩ } instance : add_comm_group (direct_limit f) := direct_limit.add_comm_group' f instance of.is_add_group_hom {i} : is_add_group_hom (direct_limit.of f i) := is_add_group_hom.mk _ $ λ x y, quotient.sound ⟨i ⊔ i, le_sup_left, le_refl _, by dsimp; simp [directed_system.map_add f]; simp [directed_system.add f]⟩ theorem of.zero_exact {i x} (H : of f i x = 0) : ∃ p hp1, f i p hp1 x = (0 : G p) := let ⟨p, hp1, hp2, hp3⟩ := quotient.exact H in ⟨p, hp1, hp3.trans $ is_add_group_hom.zero _⟩ variables {P : Type*} [add_comm_group P] variables (g : Π i, G i → P) (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables [∀ i, is_add_group_hom (g i)] def rec.is_add_group_hom : is_add_group_hom (rec f g Hg) := is_add_group_hom.mk _ $ λ i j, quotient.induction_on₂ i j $ λ ⟨p, xp⟩ ⟨q, xq⟩, calc _ = _ : is_add_group_hom.add _ _ _ ... = _ : congr_arg₂ (+) (Hg _ _ _ _) (Hg _ _ _ _) end direct_limit namespace direct_limit variables [∀ i, ring (G i)] (f : Π i j, i ≤ j → G i → G j) variables [∀ i j h, is_ring_hom (f i j h)] [directed_system f] local attribute [instance] direct_limit.setoid instance ring' : ring (quotient (direct_limit.setoid f)) := { mul := λ i j, quotient.lift_on₂ i j (λ xi xj, ⟦⟨xi.1 ⊔ xj.1, f xi.1 (xi.1 ⊔ xj.1) le_sup_left xi.2 * f xj.1 (xi.1 ⊔ xj.1) le_sup_right xj.2⟩⟧ : sigma G → sigma G → quotient (direct_limit.setoid f)) (λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩ ⟨s, xs⟩ ⟨t, hpt, hrt, hprt⟩ ⟨u, hqu, hsu, hqsu⟩, quotient.sound $ ⟨(p ⊔ q) ⊔ (r ⊔ s) ⊔ (t ⊔ u), le_trans le_sup_left le_sup_left, le_trans le_sup_right le_sup_left, calc f (p ⊔ q) (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans le_sup_left le_sup_left) (f p (p ⊔ q) le_sup_left xp * f q (p ⊔ q) le_sup_right xq) = f p (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans hpt (le_trans le_sup_left le_sup_right)) xp * f q (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans hqu (le_trans le_sup_right le_sup_right)) xq : directed_system.map_mul f ... = f t (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f p t hpt xp) * f u (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f q u hqu xq) : congr_arg₂ (*) (directed_system.Hcomp f _ _ _ _ _ _).symm (directed_system.Hcomp f _ _ _ _ _ _).symm ... = f t (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f r t hrt xr) * f u (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ (f s u hsu xs) : congr_arg₂ (*) (congr_arg _ hprt) (congr_arg _ hqsu) ... = f r (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ xr * f s (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) _ xs : congr_arg₂ (*) (directed_system.Hcomp f _ _ _ _ _ _) (directed_system.Hcomp f _ _ _ _ _ _) ... = f (r ⊔ s) (p ⊔ q ⊔ (r ⊔ s) ⊔ (t ⊔ u)) (le_trans le_sup_right le_sup_left) (f r (r ⊔ s) le_sup_left xr * f s (r ⊔ s) le_sup_right xs) : eq.symm $ directed_system.map_mul f⟩), mul_assoc := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨((p ⊔ q) ⊔ r) ⊔ (p ⊔ (q ⊔ r)), le_sup_left, le_sup_right, by dsimp; simp [directed_system.map_mul f, directed_system.mul f, directed_system.Hcomp f, mul_assoc]⟩, one := ⟦⟨default _, 1⟩⟧, one_mul := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound ⟨default _ ⊔ p, le_refl _, le_sup_right, by dsimp; simp [directed_system.map_mul f, directed_system.one f, directed_system.Hcomp f]⟩, mul_one := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound ⟨p ⊔ default ι, le_refl _, le_sup_left, by dsimp; simp [directed_system.map_mul f, directed_system.one f, directed_system.Hcomp f]⟩, left_distrib := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨p ⊔ (q ⊔ r) ⊔ (p ⊔ q ⊔ (p ⊔ r)), le_sup_left, le_sup_right, by dsimp; simp [directed_system.add f, directed_system.mul f, directed_system.Hcomp f, mul_add]⟩, right_distrib := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨p ⊔ q ⊔ r ⊔ (p ⊔ r ⊔ (q ⊔ r)), le_sup_left, le_sup_right, by dsimp; simp [directed_system.add f, directed_system.mul f, directed_system.Hcomp f, add_mul]⟩, .. direct_limit.add_comm_group' f } instance: ring (direct_limit f) := direct_limit.ring' f instance of.is_ring_hom {i} : is_ring_hom (direct_limit.of f i) := { map_add := is_add_group_hom.add _, map_mul := λ x y, quotient.sound ⟨i ⊔ i, le_sup_left, le_refl _, by dsimp; simp [directed_system.mul f, directed_system.Hcomp f]⟩, map_one := quotient.sound ⟨i ⊔ default _, le_sup_left, le_sup_right, by dsimp; simp [directed_system.one f]⟩ } theorem of.one_exact {i x} (H : of f i x = 1) : ∃ p hp1, f i p hp1 x = (1 : G p) := let ⟨p, hp1, hp2, hp3⟩ := quotient.exact H in ⟨p, hp1, hp3.trans $ is_ring_hom.map_one _⟩ variables {P : Type*} [ring P] variables (g : Π i, G i → P) (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables [∀ i, is_ring_hom (g i)] local attribute [instance] rec.is_add_group_hom def rec.is_ring_hom : is_ring_hom (rec f g Hg) := { map_add := is_add_group_hom.add _, map_mul := λ i j, quotient.induction_on₂ i j $ λ ⟨p, xp⟩ ⟨q, xq⟩, calc _ = _ : is_ring_hom.map_mul _ ... = _ : congr_arg₂ (*) (Hg _ _ _ _) (Hg _ _ _ _), map_one := show g (default _) 1 = 1, from is_ring_hom.map_one _ } end direct_limit namespace test instance : has_dvd ℕ+ := ⟨λ m n, m.1 ∣ n.1⟩ instance : directed_order pnat := { le := λ m n, m ∣ n, le_refl := λ _, ⟨1, by simp⟩, le_trans := λ _ _ _ ⟨k1, hk1⟩ ⟨k2, hk2⟩, ⟨k1 * k2, by rw [hk2, hk1, mul_assoc]⟩, le_antisymm := λ _ _ h1 h2, pnat.eq $ nat.dvd_antisymm h1 h2, sup := (*), le_sup_left := λ _ n, ⟨n, rfl⟩, le_sup_right := λ m _, ⟨m, nat.mul_comm _ _⟩ } def ff : Π i j : pnat, i ≤ j → ℤ → ℤ := λ i j h n, n * (j / i : nat) instance : inhabited pnat := ⟨1⟩ instance ds : directed_system ff := ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ⟨k, hk⟩ ⟨p, hp⟩ ⟨q, hq⟩ n, by unfold ff; clear _fun_match; dsimp at hp hq ⊢; rw [mul_assoc, hq, nat.mul_div_cancel_left _ hj, hp, nat.mul_div_cancel_left _ hi]; rw [mul_assoc, nat.mul_div_cancel_left _ hi]; refl⟩ instance agh (i j h) : is_add_group_hom (ff i j h) := is_add_group_hom.mk _ $ λ x y, by unfold ff; rw add_mul theorem pnat.div_mul_div {p q t u : ℕ+} (H1 : p ∣ t) (H2 : q ∣ u) : ↑t * ↑u / (↑p * ↑q) = (t / p : nat) * (u / q : nat) := begin cases p with p hp, cases q with q hq, cases t with t ht, cases u with u hu, dsimp at *, rw [← nat.div_div_eq_div_mul, nat.mul_comm, nat.mul_div_assoc _ H1], rw [nat.mul_comm, nat.mul_div_assoc _ H2] end theorem pnat.dvd_mul {p q t u : ℕ+} (H1 : p ∣ t) (H2 : q ∣ u) : (p * q) ∣ (t * u) := begin cases H1 with m hm, cases H2 with n hn, existsi m * n, change (t : ℕ) = p * m at hm, change (u : ℕ) = q * n at hn, change (t : ℕ) * u = p * q * _, rw [hm, hn], ac_refl end instance : comm_ring (direct_limit ff) := { mul := λ i j, quotient.lift_on₂ i j (λ p q, (⟦⟨p.1 * q.1, p.2 * q.2⟩⟧ : direct_limit ff)) $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩ ⟨s, xs⟩ ⟨t, hpt, hrt, hprt⟩ ⟨u, hqu, hsu, hqsu⟩, quotient.sound ⟨t * u, pnat.dvd_mul hpt hqu, pnat.dvd_mul hrt hsu, begin repeat { clear _x _fun_match }, dsimp [ff] at *, rw [pnat.div_mul_div hpt hqu, pnat.div_mul_div hrt hsu], simp [int.coe_nat_mul], cc end⟩, mul_assoc := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨p * q * r, le_refl _, by simp [mul_assoc], by simp [mul_assoc]⟩, one := ⟦⟨1, 1⟩⟧, one_mul := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound ⟨p, by simp, by simp, by simp⟩, mul_one := λ i, quotient.induction_on i $ λ ⟨p, xp⟩, quotient.sound ⟨p, by simp, by simp, by simp⟩, left_distrib := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨_, le_sup_left, le_sup_right, begin repeat { clear _x _fun_match }, simp [mul_add], rw [directed_system.map_add ff], dsimp [ff, (⊔)] at *, rw [nat.mul_div_cancel_left, nat.mul_div_cancel_left, nat.mul_div_cancel], rw [nat.mul_div_assoc, nat.mul_div_cancel_left], rw [nat.mul_div_assoc, nat.mul_div_cancel], simp [add_mul, int.coe_nat_mul], cc, repeat { apply mul_pos <|> simp } end⟩, right_distrib := λ i j k, quotient.induction_on₃ i j k $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨r, xr⟩, quotient.sound ⟨_, le_sup_left, le_sup_right, begin repeat { clear _x _fun_match }, dsimp at *, rw [directed_system.map_add ff, add_mul], dsimp [ff, (⊔)] at *, rw [nat.mul_div_cancel_left, nat.mul_div_cancel_left, nat.mul_div_cancel], rw [nat.mul_div_assoc, nat.mul_div_cancel_left], rw [nat.mul_div_assoc, nat.mul_div_cancel], simp [add_mul, int.coe_nat_mul], cc, repeat { apply mul_pos <|> simp } end⟩, mul_comm := λ i j, quotient.induction_on₂ i j $ λ ⟨p, xp⟩ ⟨q, xq⟩, quotient.sound ⟨p * q, by simp, by simp [mul_comm], by simp [mul_comm]⟩, .. direct_limit.add_comm_group ff } theorem rat.mk_pnat_eq_iff (a b c d) : rat.mk_pnat a b = rat.mk_pnat c d ↔ a * d = c * b := begin cases b with b hb, cases d with d hd, simp [rat.mk_pnat_eq], rw [rat.mk_eq], exact ne_of_gt (int.coe_nat_pos.2 hb), exact ne_of_gt (int.coe_nat_pos.2 hd), end theorem pnat.eq_of_mul_of_mul {a b : ℕ} (c : ℕ+) (H : a * c = b * c) : a = b := begin rcases nat.lt_trichotomy a b with H1 | H1 | H1, { replace H1 := nat.mul_lt_mul_of_pos_right H1 c.2, exfalso, exact ne_of_lt H1 H }, { exact H1 }, { replace H1 := nat.mul_lt_mul_of_pos_right H1 c.2, exfalso, exact ne_of_lt H1 H.symm } end theorem nat.eq_of_mul_of_mul_of_pos {a b : ℕ} (c : ℕ) (Hc : c > 0) (H : a * c = b * c) : a = b := pnat.eq_of_mul_of_mul ⟨c, Hc⟩ H theorem nat.pos_and_pos_of_mul_pos {a b : ℕ} (H : a * b > 0) : a > 0 ∧ b > 0 := ⟨nat.pos_of_ne_zero $ λ Ha, by subst Ha; simp at H; cases H, nat.pos_of_ne_zero $ λ Hb, by subst Hb; simp at H; cases H⟩ theorem nat.div_self_div {a b : ℕ} (Ha : a > 0) (H : b ∣ a) : a / (a / b) = b := let ⟨n, hn⟩ := H in have H1 : b * n > 0, from hn ▸ Ha, let ⟨Hb, Hn⟩ := nat.pos_and_pos_of_mul_pos H1 in by rw [hn, nat.mul_div_cancel_left _ Hb, nat.mul_div_cancel _ Hn] def to_rat (x : direct_limit ff) : ℚ := quotient.lift_on x (λ i, (rat.mk_pnat i.2 i.1 : ℚ)) $ λ ⟨p, xp⟩ ⟨q, xq⟩ ⟨t, hpt, hqt, hpqt⟩, begin cases hpt with m hm, cases hqt with n hn, change (t : ℕ) = p * m at hm, change (t : ℕ) = q * n at hn, dsimp [ff] at hpqt, dsimp, rw rat.mk_pnat_eq_iff, rw [hm, nat.mul_div_cancel_left, ← hm, hn, nat.mul_div_cancel_left] at hpqt, have H : (m:ℤ) * n ≠ 0, { intro H, rcases eq_zero_or_eq_zero_of_mul_eq_zero H; simp at h, { subst h, simp at hm, exact hm }, { subst h, simp at hn, exact hn } }, apply eq_of_mul_eq_mul_right H, rw [← mul_assoc, ← mul_assoc, mul_assoc xq, mul_right_comm, mul_assoc xp], simp, rw [← int.coe_nat_mul, ← int.coe_nat_mul, ← hm, ← hn], rw [mul_right_comm xp, mul_right_comm xq, hpqt], simp, simp end def of_rat (x : ℚ) : direct_limit ff := ⟦⟨⟨x.denom, x.pos⟩, x.num⟩⟧ def equiv : direct_limit ff ≃ ℚ := { to_fun := to_rat, inv_fun := of_rat, left_inv := λ x, quotient.induction_on x $ λ ⟨⟨p, hp⟩, xp⟩, quotient.sound ⟨⟨p, hp⟩, ⟨nat.gcd (int.nat_abs xp) p, by simp [to_rat, rat.mk_pnat, nat.div_mul_cancel (nat.gcd_dvd_right _ _)]⟩, le_refl _, begin dsimp [ff, to_rat], dsimp at xp, simp [nat.div_self hp, rat.mk_pnat], rw [nat.div_self_div hp (nat.gcd_dvd_right _ _)], rw [mul_comm, ← int.mul_div_assoc, int.mul_div_cancel_left], { simp, apply nat.pos_iff_ne_zero.1, exact nat.gcd_pos_of_pos_right _ hp }, { rw [← int.dvd_nat_abs, int.coe_nat_dvd], apply nat.gcd_dvd_left } end⟩, right_inv := λ x, rat.num_denom_cases_on x $ λ n d p c, (rat.mk_pnat_eq _ _ _).trans $ eq.symm $ rat.num_denom _ } end test
18630c89a0fa3dd8f3a342d2b34d428db8b63f39
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/filter/archimedean.lean
4b013379d784d6cfc3a81aba1d5bab0b702add9a
[ "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
6,656
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import algebra.order.archimedean import order.filter.at_top_bot /-! # `at_top` filter and archimedean (semi)rings/fields In this file we prove that for a linear ordered archimedean semiring `R` and a function `f : α → ℕ`, the function `coe ∘ f : α → R` tends to `at_top` along a filter `l` if and only if so does `f`. We also prove that `coe : ℕ → R` tends to `at_top` along `at_top`, as well as version of these two results for `ℤ` (and a ring `R`) and `ℚ` (and a field `R`). -/ variables {α R : Type*} open filter set @[simp] lemma nat.comap_coe_at_top [ordered_semiring R] [nontrivial R] [archimedean R] : comap (coe : ℕ → R) at_top = at_top := comap_embedding_at_top (λ _ _, nat.cast_le) exists_nat_ge lemma tendsto_coe_nat_at_top_iff [ordered_semiring R] [nontrivial R] [archimedean R] {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : R)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) exists_nat_ge lemma tendsto_coe_nat_at_top_at_top [ordered_semiring R] [archimedean R] : tendsto (coe : ℕ → R) at_top at_top := nat.mono_cast.tendsto_at_top_at_top exists_nat_ge @[simp] lemma int.comap_coe_at_top [ordered_ring R] [nontrivial R] [archimedean R] : comap (coe : ℤ → R) at_top = at_top := comap_embedding_at_top (λ _ _, int.cast_le) $ λ r, let ⟨n, hn⟩ := exists_nat_ge r in ⟨n, hn⟩ @[simp] lemma int.comap_coe_at_bot [ordered_ring R] [nontrivial R] [archimedean R] : comap (coe : ℤ → R) at_bot = at_bot := comap_embedding_at_bot (λ _ _, int.cast_le) $ λ r, let ⟨n, hn⟩ := exists_nat_ge (-r) in ⟨-n, by simpa [neg_le] using hn⟩ lemma tendsto_coe_int_at_top_iff [ordered_ring R] [nontrivial R] [archimedean R] {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : R)) l at_top ↔ tendsto f l at_top := by rw [← tendsto_comap_iff, int.comap_coe_at_top] lemma tendsto_coe_int_at_bot_iff [ordered_ring R] [nontrivial R] [archimedean R] {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : R)) l at_bot ↔ tendsto f l at_bot := by rw [← tendsto_comap_iff, int.comap_coe_at_bot] lemma tendsto_coe_int_at_top_at_top [ordered_ring R] [archimedean R] : tendsto (coe : ℤ → R) at_top at_top := int.cast_mono.tendsto_at_top_at_top $ λ b, let ⟨n, hn⟩ := exists_nat_ge b in ⟨n, hn⟩ @[simp] lemma rat.comap_coe_at_top [linear_ordered_field R] [archimedean R] : comap (coe : ℚ → R) at_top = at_top := comap_embedding_at_top (λ _ _, rat.cast_le) $ λ r, let ⟨n, hn⟩ := exists_nat_ge r in ⟨n, by simpa⟩ @[simp] lemma rat.comap_coe_at_bot [linear_ordered_field R] [archimedean R] : comap (coe : ℚ → R) at_bot = at_bot := comap_embedding_at_bot (λ _ _, rat.cast_le) $ λ r, let ⟨n, hn⟩ := exists_nat_ge (-r) in ⟨-n, by simpa [neg_le]⟩ lemma tendsto_coe_rat_at_top_iff [linear_ordered_field R] [archimedean R] {f : α → ℚ} {l : filter α} : tendsto (λ n, (f n : R)) l at_top ↔ tendsto f l at_top := by rw [← tendsto_comap_iff, rat.comap_coe_at_top] lemma tendsto_coe_rat_at_bot_iff [linear_ordered_field R] [archimedean R] {f : α → ℚ} {l : filter α} : tendsto (λ n, (f n : R)) l at_bot ↔ tendsto f l at_bot := by rw [← tendsto_comap_iff, rat.comap_coe_at_bot] lemma at_top_countable_basis_of_archimedean [linear_ordered_semiring R] [archimedean R] : (at_top : filter R).has_countable_basis (λ n : ℕ, true) (λ n, Ici n) := { countable := countable_encodable _, to_has_basis := at_top_basis.to_has_basis (λ x hx, let ⟨n, hn⟩ := exists_nat_ge x in ⟨n, trivial, Ici_subset_Ici.2 hn⟩) (λ n hn, ⟨n, trivial, subset.rfl⟩) } lemma at_bot_countable_basis_of_archimedean [linear_ordered_ring R] [archimedean R] : (at_bot : filter R).has_countable_basis (λ m : ℤ, true) (λ m, Iic m) := { countable := countable_encodable _, to_has_basis := at_bot_basis.to_has_basis (λ x hx, let ⟨m, hm⟩ := exists_int_lt x in ⟨m, trivial, Iic_subset_Iic.2 hm.le⟩) (λ m hm, ⟨m, trivial, subset.rfl⟩) } @[priority 100] instance at_top_countably_generated_of_archimedean [linear_ordered_semiring R] [archimedean R] : (at_top : filter R).is_countably_generated := at_top_countable_basis_of_archimedean.is_countably_generated @[priority 100] instance at_bot_countably_generated_of_archimedean [linear_ordered_ring R] [archimedean R] : (at_bot : filter R).is_countably_generated := at_bot_countable_basis_of_archimedean.is_countably_generated variables [linear_ordered_semiring R] [archimedean R] variables {l : filter α} {f : α → R} {r : R} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is given in `filter.tendsto.const_mul_at_top`). -/ lemma filter.tendsto.const_mul_at_top' (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := begin apply tendsto_at_top.2 (λb, _), obtain ⟨n : ℕ, hn : 1 ≤ n • r⟩ := archimedean.arch 1 hr, rw nsmul_eq_mul' at hn, filter_upwards [tendsto_at_top.1 hf (n * max b 0)] with x hx, calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ } ... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn (le_max_right _ _) ... = r * (n * max b 0) : by rw [mul_assoc] ... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr) end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is given in `filter.tendsto.at_top_mul_const`). -/ lemma filter.tendsto.at_top_mul_const' (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := begin apply tendsto_at_top.2 (λb, _), obtain ⟨n : ℕ, hn : 1 ≤ n • r⟩ := archimedean.arch 1 hr, have hn' : 1 ≤ (n : R) * r, by rwa nsmul_eq_mul at hn, filter_upwards [tendsto_at_top.1 hf (max b 0 * n)] with x hx, calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ } ... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _) ... = (max b 0 * n) * r : by rw [mul_assoc] ... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr) end
d172bc2807c50d863d66a7fb8ae959cdaf1de639
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/normed_space/operator_norm.lean
5c5d865e5b7ffd3531645218d096667fb4ddbcf0
[ "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
27,931
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ import topology.metric_space.lipschitz analysis.normed_space.riesz_lemma import analysis.asymptotics noncomputable theory open_locale classical set_option class.instance_max_depth 70 variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem linear_map.antilipschitz_of_bound {K : nnreal} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ @[simp, elim_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, elim_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg', norm_nonneg, inv_nonneg.2, norm_nonneg] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg' (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `δ`. The nondiscreteness is then used to rescale any element into an element of norm in `[δ/C, δ]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases metric.tendsto_nhds_nhds.1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨δ⁻¹ * ∥c∥, mul_pos (inv_pos.2 δ_pos) (lt_trans zero_lt_one hc), (λx, _)⟩, by_cases h : x = 0, { simp only [h, norm_zero, mul_zero, linear_map.map_zero] }, { rcases rescale_to_shell hc δ_pos h with ⟨d, hd, dxle, ledx, dinv⟩, calc ∥f x∥ = ∥f ((d⁻¹ * d) • x)∥ : by rwa [inv_mul_cancel, one_smul] ... = ∥d∥⁻¹ * ∥f (d • x)∥ : by rw [mul_smul, linear_map.map_smul, norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left (H dxle) (by { rw ← normed_field.norm_inv, exact norm_nonneg _ }) ... ≤ δ⁻¹ * ∥c∥ * ∥x∥ : by { rw mul_one, exact dinv } } end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in is_O_of_le' l hM theorem is_O_comp {E : Type*} (g : F →L[𝕜] G) (f : E → F) (l : filter E) : is_O (λ x', g (f x')) f l := (g.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l end section op_norm open set real set_option class.instance_max_depth 100 /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf { c | c ≥ 0 ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from norm_pos_iff.2 hne, le_mul_of_div_le hlt ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, div_le_of_le_mul hlt (by { rw mul_comm, apply hc })))) theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := (or.elim (lt_or_eq_of_le (norm_nonneg _)) (λ hlt, div_le_of_le_mul hlt (by { rw mul_comm, apply le_op_norm })) (λ heq, by { rw [←heq, div_zero], apply op_norm_nonneg })) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : nnreal} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := show ∥f + g∥ ≤ (coe : nnreal → ℝ) (⟨_, f.op_norm_nonneg⟩ + ⟨_, g.op_norm_nonneg⟩), from op_norm_le_of_lipschitz (f.lipschitz.add g.lipschitz) /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) @[simp] lemma norm_zero : ∥(0 : E →L[𝕜] F)∥ = 0 := by rw op_norm_zero_iff /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥(id : E →L[𝕜] E)∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If a space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id (h : ∃ x : E, x ≠ 0) : ∥(id : E →L[𝕜] E)∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := h in have _ := ratio_le_op_norm (id : E →L[𝕜] E) x, by rwa [id_apply, div_self (ne_of_gt $ norm_pos_iff.2 hx)] at this /-- The operator norm is homogeneous. -/ lemma op_norm_smul : ∥c • f∥ = ∥c∥ * ∥f∥ := le_antisymm ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) (lb_le_Inf _ bounds_nonempty (λ _ ⟨hn, hc⟩, (or.elim (lt_or_eq_of_le (norm_nonneg c)) (λ hlt, begin rw mul_comm, exact mul_le_of_le_div hlt (Inf_le _ bounds_bdd_below ⟨div_nonneg hn hlt, λ _, (by { rw div_mul_eq_mul_div, exact le_div_of_mul_le hlt (by { rw [ mul_comm, ←norm_smul ], exact hc _ }) })⟩) end) (λ heq, by { rw [←heq, zero_mul], exact hn })))) lemma op_norm_neg : ∥-f∥ = ∥f∥ := calc ∥-f∥ = ∥(-1:𝕜) • f∥ : by rw neg_one_smul ... = ∥(-1:𝕜)∥ * ∥f∥ : by rw op_norm_smul ... = ∥f∥ : by simp /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end variable (f) theorem uniform_embedding_of_bound {K : nnreal} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { apply le_of_lt, apply hε, simp [dist_eq_norm], exact lt_of_le_of_lt hx (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxle, ledx, dinv⟩, have : ∥f (d • x)∥ ≤ δ, by simpa, have : ∥d • x∥ ≤ 1 := H this, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. -/ instance [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, add := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique filter.at_top_ne_bot A B, end, smul := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique filter.at_top_ne_bot A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto at_top_ne_bot (hG v).norm (eventually_of_forall _ A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto at_top_ne_bot B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, add := begin refine is_closed_property2 h_dense (is_closed_eq _ _) _, { exact cont.comp (continuous_fst.add continuous_snd) }, { exact (cont.comp continuous_fst).add (cont.comp continuous_snd) }, { assume x y, rw ← e.map_add, simp only [eq], exact f.map_add _ _ }, end, smul := λk, begin refine is_closed_property h_dense (is_closed_eq _ _) _, { exact cont.comp (continuous_const.smul continuous_id) }, { exact (continuous_const.smul continuous_id).comp cont }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := begin apply ext, refine is_closed_property h_dense (is_closed_eq _ _) _, { exact (uniform_continuous_uniformly_extend h_e h_dense uniform_continuous_const).continuous }, { simp only [zero_apply], exact continuous_const }, { assume x, exact uniformly_extend_of_ind h_e h_dense uniform_continuous_const x } end end section variables {N : nnreal} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma smul_right_norm {c : E →L[𝕜] 𝕜} {f : F} : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) this) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E' : Type*} [normed_group E'] [normed_space 𝕜' E'] {F' : Type*} [normed_group F'] [normed_space 𝕜' F'] local attribute [instance, priority 500] normed_space.restrict_scalars /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : E' →L[𝕜] F' := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, move_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' →ₗ[𝕜] F') = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, squash_cast] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars end continuous_linear_map namespace continuous_linear_equiv variable (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (nnnorm (e : E →L[𝕜] F)) e := (e : E →L[𝕜] F).lipschitz protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm (h : ∃ x : E, x ≠ 0) : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id h] end lemma norm_pos (h : ∃ x : E, x ≠ 0) : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one (e.one_le_norm_mul_norm_symm h)) (norm_nonneg _) lemma norm_symm_pos (h : ∃ x : E, x ≠ 0) : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one (e.one_le_norm_mul_norm_symm h)) (norm_nonneg _) lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := (subsingleton_or_exists_ne (0 : E)).imp id (λ hE, e.norm_symm_pos hE) lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma linear_map.mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h
a94dc90234018ab2fc2fe818aacbaba0974757ab
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebraic_topology/Moore_complex.lean
c77a36efb02cd1256228f63f2383ed012ae9bb50
[ "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
5,363
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 algebraic_topology.simplicial_object import category_theory.abelian.basic import category_theory.subobject import algebra.homology.homological_complex /-! ## Moore complex We construct the normalized Moore complex, as a functor `simplicial_object C ⥤ chain_complex C ℕ`, for any abelian category `C`. The `n`-th object is intersection of the kernels of `X.δ i : X.obj n ⟶ X.obj (n-1)`, for `i = 1, ..., n`. The differentials are induced from `X.δ 0`, which maps each of these intersections of kernels to the next. This functor is one direction of the Dold-Kan equivalence, which we're still working towards. ### References * https://stacks.math.columbia.edu/tag/0194 * https://ncatlab.org/nlab/show/Moore+complex -/ universes v u noncomputable theory open category_theory category_theory.limits open opposite namespace algebraic_topology variables {C : Type*} [category C] [abelian C] local attribute [instance] abelian.has_pullbacks /-! The definitions in this namespace are all auxiliary definitions for `normalized_Moore_complex` and should usually only be accessed via that. -/ namespace normalized_Moore_complex open category_theory.subobject variables (X : simplicial_object C) /-- The normalized Moore complex in degree `n`, as a subobject of `X n`. -/ @[simp] def obj_X : Π n : ℕ, subobject (X.obj (op (simplex_category.mk n))) | 0 := ⊤ | (n+1) := finset.univ.inf (λ k : fin (n+1), kernel_subobject (X.δ k.succ)) /-- The differentials in the normalized Moore complex. -/ @[simp] def obj_d : Π n : ℕ, (obj_X X (n+1) : C) ⟶ (obj_X X n : C) | 0 := subobject.arrow _ ≫ X.δ (0 : fin 2) ≫ inv ((⊤ : subobject _).arrow) | (n+1) := begin -- The differential is `subobject.arrow _ ≫ X.δ (0 : fin (n+3))`, -- factored through the intersection of the kernels. refine factor_thru _ (arrow _ ≫ X.δ (0 : fin (n+3))) _, -- We now need to show that it factors! -- A morphism factors through an intersection of subobjects if it factors through each. refine ((finset_inf_factors _).mpr (λ i m, _)), -- A morphism `f` factors through the kernel of `g` exactly if `f ≫ g = 0`. apply kernel_subobject_factors, -- Use a simplicial identity dsimp [obj_X], erw [category.assoc, ←X.δ_comp_δ (fin.zero_le i.succ), ←category.assoc], -- It's the first two factors which are zero. convert zero_comp, -- We can rewrite the arrow out of the intersection of all the kernels as a composition -- of a morphism we don't care about with the arrow out of the kernel of `X.δ i.succ.succ`. rw ←factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ i.succ (by simp)), -- It's the second two factors which are zero. rw [category.assoc], convert comp_zero, exact kernel_subobject_arrow_comp _, end lemma d_squared (n : ℕ) : obj_d X (n+1) ≫ obj_d X n = 0 := begin -- It's a pity we need to do a case split here; -- after the first simp the proofs are almost identical cases n; dsimp, { simp only [subobject.factor_thru_arrow_assoc], slice_lhs 2 3 { erw ←X.δ_comp_δ (fin.zero_le 0), }, rw ←factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ (0 : fin 2) (by simp)), slice_lhs 2 3 { rw [kernel_subobject_arrow_comp], }, simp, }, { simp [factor_thru_right], slice_lhs 2 3 { erw ←X.δ_comp_δ (fin.zero_le 0), }, rw ←factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ (0 : fin (n+3)) (by simp)), slice_lhs 2 3 { rw [kernel_subobject_arrow_comp], }, simp, }, end /-- The normalized Moore complex functor, on objects. -/ @[simps] def obj (X : simplicial_object C) : chain_complex C ℕ := chain_complex.of (λ n, (obj_X X n : C)) -- the coercion here picks a representative of the subobject (obj_d X) (d_squared X) variables {X} {Y : simplicial_object C} (f : X ⟶ Y) /-- The normalized Moore complex functor, on morphisms. -/ @[simps] def map (f : X ⟶ Y) : obj X ⟶ obj Y := chain_complex.of_hom _ _ _ _ _ _ (λ n, begin refine factor_thru _ (arrow _ ≫ f.app (op (simplex_category.mk n))) _, cases n; dsimp, { apply top_factors, }, { refine (finset_inf_factors _).mpr (λ i m, _), apply kernel_subobject_factors, slice_lhs 2 3 { erw ←f.naturality, }, rw ←factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ i (by simp)), slice_lhs 2 3 { erw [kernel_subobject_arrow_comp], }, simp, } end) (λ n, begin cases n; dsimp, { ext, simp, erw f.naturality, refl, }, { ext, simp, erw f.naturality, refl, }, end) end normalized_Moore_complex open normalized_Moore_complex variables (C) /-- The (normalized) Moore complex of a simplicial object `X` in an abelian category `C`. The `n`-th object is intersection of the kernels of `X.δ i : X.obj n ⟶ X.obj (n-1)`, for `i = 1, ..., n`. The differentials are induced from `X.δ 0`, which maps each of these intersections of kernels to the next. -/ @[simps] def normalized_Moore_complex : simplicial_object C ⥤ chain_complex C ℕ := { obj := obj, map := λ X Y f, map f, map_id' := λ X, by { ext n, cases n; { dsimp, simp, }, }, map_comp' := λ X Y Z f g, by { ext n, cases n; simp, }, } end algebraic_topology
5a041dca8c7ca6760492d28dae097db2c35d0203
874a8d2247ab9a4516052498f80da2e32d0e3a48
/jensen.lean
2b5b007d87bbe6bf5dc5ae8d5aca56c0bb4fab94
[]
no_license
AlexKontorovich/Spring2020Math492
378b36c643ee029f5ab91c1677889baa591f5e85
659108c5d864ff5c75b9b3b13b847aa5cff4348a
refs/heads/master
1,610,780,595,457
1,588,174,859,000
1,588,174,859,000
243,017,788
0
1
null
null
null
null
UTF-8
Lean
false
false
25,795
lean
-- jensen.lean -- @authors: Colin J Fan, Brandon H Gomes, Yasa Syed /-! # Jensen's Inequality In this file, we prove a famous and important inequality. The file is self-contained and requires no other definitions other than those in the Lean core. We first state the classical Jensen's Inequality: - Theorem. Let `μ` be a positive measure on a σ-algebra `𝔐` in a set `Ω`, so that `μ(Ω) = 1`. If `f` is a real function in `L¹(μ)` such that `∀x ∈ Ω, f(x) ∈ (a,b)` and if `φ` is convex on `(a,b)`, then `φ (∫_Ω f dμ) ≤ ∫_Ω (φ ∘ f) dμ`. More succinctly, `φ (∫ f) ≤ ∫ (φ ∘ f)`. The inequality follows from certain facts about integration, real numbers, convex functions, ... etc. The theorem we prove is a strict generalization in which we state the theorem in as high of an abstract form as possible from facts about subtraction and partial orders. We will define a type-theoretic analogue of integration theory and of the theory of convex functions. More details are discussed below. This theorem has some important corollaries for real analysis, measure theory, probability theory, statistics, and statistical physics: - Corollary 1 (AM-GM). Fix `n ∈ ℕ`. It follows that for any `a₁, a₂, ..., aₙ ∈ ℝ₀` that `ⁿ√(a₁a₂ ⋯ aₙ) ≤ (a₁ + a₂ + ⋯ + aₙ) / n`. - Corollary 2 (Young's Inequality). Fix `a b ∈ ℝ₀` and `p q ∈ ℝ` such that `p > 1`, and `1/p + 1/q = 1`. Then, `ab ≤ a^p / p + b^q / q`. - Corollary 3 (Hölder's Inequality). Fix `p q ∈ ℝ` such that `p > 1`, and `1/p + 1/q = 1`. If `X` is a measure space, with measure `μ` and `f`,`g` measurable functions on `X` with codomain `[0,∞]`, then `∫ fg dμ ≤ (∫ f^p dμ)^1/p * (∫ g^q dμ)^1/q` where the integrals are taken over `X`. - Corollary 4 (Minkowski's Inequality). With the same assumptions as Hölder's Inequality we have `(∫ (f+g)^p dμ)^1/p ≤ (∫ f^p dμ)^1/p + (∫ g^p dμ)^1/p`. In particular, for `p > 1`, the map `f ↦ (∫ |f|^p dμ)^1/p` is a norm for `f` (up to a relevant equivalence relation) such that all `f` have finite `p`-norm. - Corollary 5 (Chandler): `e^(E[X]) ≤ E[e^X]`. - Corollary 6 (Gibb's Inequality). `D_KL(P||Q) ≥ 0`. - Corollary 7: Rao-Blackwell Theorem. Now, we begin our discussion with power sets. -/ --———————————————————————————————————————————————————————————————————————————————————————-- /-- `Power X` (`𝒫 X`) The powerset of a type. Given a type `X : 𝒰i` we can consider the type of functions from `X` into a fixed type universe `𝒰j`. One can view this type of functions `𝒫 X` as the space of characteristic functions on `X`. Classically, we can associate any subset `A ⊆ S` to an appropriate characteristic function `χ_A : S → {0,1}` which takes value `1` on `A` and `0` elsewhere in `S`. This association is a "bijective correspondence", that is, we can freely change our interpretation of the subset `A` either as an actual subset or as a characteristic function. In the language of types there is no natural notion of "subset" but there is a natural (but non-canonical since it depends on the universe level `j`) notion of a characteristic function. In general `𝒫 X` behaves like the classical power set of `X`, i.e. a complete lattice: - Bottom: `⊥ := λ x, 𝟘` - Top: `⊤ := λ x, 𝟙` - Union: `P ∪ Q := λ x, P x ∨ Q x` - Intersection: `P ∩ Q := λ x, P x ∧ Q x` - Aribtrary Union: `⋃ ℱ := λ x, Σ i, (ℱ i) x` - Aribtrary Intersection: `⋂ ℱ := λ x, Π i, (ℱ i) x` where `𝟘` and `𝟙` are the empty type (the type with no terms) and unit type (the type with one canonical term) respectively. The `⊥` element can be called the "empty set" and the `⊤` element can be called the "total space" and can be associated to `X` itself. Classically one can think of the union as the sum of characteristic functions `χ_P + χ_Q` and the intersection as the product `χ_P * χ_Q`. There is a similar story for the arbitrary union/intersection. NB: To know that a term `x : X` is contained in the subset `A : 𝒫 X`, we need a witness of the form `w : A x`, since `A` is a function and concatenation is function application. We will be using the `Power` construction many times throughout since partial functions play an important role in the `jensen_inequality` and also in the theory of integration in general; partial functions only make sense if we have defined the notion of power set. -/ definition {𝒰i 𝒰j} Power (X : Type 𝒰i) := X → Type 𝒰j notation `𝒫` X := Power X /-- `const b` (`↓b`) The constant function at a point. Given a type `X` and a pointed type `⟨Y, b⟩`, we can consider the constant function which takes every point of `X` to the basepoint `b`. Such functions are important for the `jensen_inequality`, and are also important in the study of pointed spaces in general. -/ definition {𝒰x 𝒰y} const {X : Type 𝒰x} {Y : Type 𝒰y} := λ b:Y, (λ x:X, b) notation `↓`:max y:max := const y section difference_domain --—————————————————————————————————————————————————————————————-- universes 𝒰y variables (Y : Type 𝒰y) /-- `DifferenceDomain Y extends has_zero Y, has_sub Y` A good place to do subtraction. A `DifferenceDomain` is a minimal structure that admits a version of subtraction like the one we are familiar with from abelian groups. The main property that distingushes subtraction is that image of the diagonal always vanishes. This property is called `vanishing_diagonal` below. There are other axioms which would make sense to add like the following two: - `zero_is_right_id : Π y, y - 0 = y` - `sub_associativity : Π a b c, a - (b - c) = (a - b) - (0 - c)` which make the subtraction more like the inverse of some addition operation like `a + b := a - (0 - b)`, but such details are not considered here. For the `jensen_inequality`, we need only the `vanishing_diagonal` property. -/ class DifferenceDomain extends has_zero Y, has_sub Y := (vanishing_diagonal : Π y, y - y = zero) /-- `OrderedDifferenceDomain Y extends has_le Y, DifferenceDomain Y` We will need an order structure on `Y` to state and prove the `jensen_inequality` so we add it here. There are no asumptions on the behavior of `≤` like reflexivity/transitivity. -/ class OrderedDifferenceDomain extends has_le Y, DifferenceDomain Y end difference_domain --—————————————————————————————————————————————————————————————————-- section reduction --—————————————————————————————————————————————————————————————————————-- universes 𝒰y 𝒰x variables {Y : Type 𝒰y} {X : Type 𝒰x} (ℱ : 𝒫 (X → Y)) /-- `Reduction` A generalized functional. Given types `X` and `Y`, a `Reduction` is a partial function from the type of functions `X → Y` to the type `Y`. The domain of this function is denoted `ℱ` throughout. One reads the definition of reduction as "a type which takes a function `f : X → Y` and a proof that `f` is contained in the family `ℱ` (`p : ℱ f`, see `Power` above) and sends this pair to term of type `Y`". Examples of reductions: - evaluation at a point (`x₀ : X`, `eval : (X → Y) → Y := λ f, f x₀`) (`ℱ` can be taken to be the total or "everywhere true" predicate) - integration (`∫_Ω (—) dμ : (X → Y) → Y`) (`ℱ` is the appropriate subset corresponding to the integrable functions on `Ω`) - limit of a sequence (`lim : (ℕ → R) → R`) (`ℱ` is the appropriate subset corresponding to the convergent sequences) For the `jensen_inequality` we will be using something like the second example as we want to imitate a weak kind of integration. For a fixed reduction we call a function `f` *reducible* if it is contained in the family corresponding to that reduction, i.e. `reducible f := ℱ f`. We say that a reduction *admits (a reduction of) a function `f`* if `f` is reducible with respect to the family corresponding to the given reduction. -/ definition Reduction := Π f, ℱ f → Y /-- `left_closed_at ℱ f g` Left closedness of `g` at `f`. We say that a function `g : Y → Y` is *left closed at `f` with respect to `ℱ`* when the reducibility of `f` implies the reducibility of the composition `g ∘ f` with respect to the fixed family `ℱ`. -/ definition left_closed_at (f : X → Y) (g : Y → Y) := ℱ f → ℱ (g ∘ f) /-- `left_closed ℱ g` Left closedness of `g`. We say that a function `g : Y → Y` is *left closed with respect to `ℱ`* when it is left closed at every function `f : X → Y`. -/ definition left_closed (g : Y → Y) := Π f, left_closed_at ℱ f g /-- `PointFamily` Family of functions which contains all constant functions. A reasonable reduction family might admit constant functions as a trivial case of some more interesting property. -/ class PointFamily := (has_constants : Π y, ℱ ↓y) section subtraction --———————————————————————————————————————————————————————————————————-- /-- `pointwise_subtraction` Lifting codomain subtraction to pointwise subtraction. If `Y` has a subtraction structure then for any type `X`, the function space `X → Y` has a canonical pointwise subtraction. This `instance` is added to simplify the notation below. -/ instance pointwise_subtraction [has_sub Y] : has_sub (X → Y) := ⟨λ f g, (λ x, f x - g x)⟩ /-- `DifferenceFamily` Family of functions closed under pointwise subtraction. -/ class DifferenceFamily [has_sub Y] := (closure : Π f g (fℱ : ℱ f) (gℱ : ℱ g), ℱ (f - g)) --———————————————————————————————————————————————————————————————————————————————————————-- /-- We fix `Int : Reduction ℱ` which will be written symbolically `∫` to conote something like an integral. This reduction will be used below. -/ variables (Int : Reduction ℱ) /-- `left_factors ℱ β lc_β` Left factorizability of `β`. We say that a left closed function `β` *left factors with respect to `Int`* when for every reducible `f` we have the identity `∫ (β ∘ f) = β (∫ f)`. -/ definition left_factors (β : Y → Y) (lc_β : left_closed ℱ β) := Π f (fℱ : ℱ f), Int (β ∘ f) (lc_β f fℱ) = β (Int f fℱ) --———————————————————————————————————————————————————————————————————————————————————————-- /-- For the rest of this section we assume `ℱ` is a `PointFamily`. -/ variables [PointFamily ℱ] /-- `UnitalReduction` A reduction which is friendly to constant functions. We say that a reduction is unital if it admits all constant functions and that the reduction of a constant function is the constant which defines it, i.e. `∫ ↓y = y`. -/ class UnitalReduction := (constant_reduction : Π y, Int ↓y (PointFamily.has_constants ℱ y) = y) --———————————————————————————————————————————————————————————————————————————————————————-- /-- For the rest of this section we assume `Y` has a `≤` structure. -/ variables [has_le Y] /-- `pointwise_le` Lifting codomain order to pointwise order. If `Y` has an order structure `≤` then for any type `X`, the function space `X → Y` has a canonical pointwise order. This `instance` is added to simplify the notation below. -/ instance pointwise_le : has_le (X → Y) := ⟨λ f g, (Π x, f x ≤ g x)⟩ /-- `MonotonicReduction Y` A reduction which is functorial over `≤`. We can also make a reduction functorial over the order structure on the space of functions `X → Y` (restricted to `ℱ`) by requiring that `Int` be a monotonic operator. -/ class MonotonicReduction := (monotonicity : Π f g {fℱ gℱ}, (f ≤ g) → (Int f fℱ ≤ Int g gℱ)) --———————————————————————————————————————————————————————————————————————————————————————-- /-- For the rest of this section we assume `Y` has a zero element and subtraction structure and that `ℱ` is a `DifferenceFamily`. We want to consider a reduction that interacts with a subtraction structure on its codomain. -/ variables [has_zero Y] [has_sub Y] [DifferenceFamily ℱ] /-- `constant_difference_property` A weak homomorphism property. For a reduction compatible with subtraction, we would like to have that reductions are homomorphisms of difference domains but this turns out to be too strong of a property. In the case of classical integration we do not have in general the property `∫ (f - g) = (∫ f) - (∫ g)` since both integrals on the right may take value at `±∞` so the subtraction is not well defined. We instead use the weaker property that we can commute with subtraction of a constant function. -/ definition constant_difference_property := Π f k {fℱ}, Int (f - ↓k) (DifferenceFamily.closure f ↓k fℱ (PointFamily.has_constants ℱ k)) = Int f fℱ - Int ↓k (PointFamily.has_constants ℱ k) /-- `translation_invariance_property` A weak translation property across inequalities. For a reduction compatible with subtraction, we would like to capture the property from the classical integral that the integral of a difference `f - g` is in the positive cone, then `∫ g ≤ ∫ f`. -/ definition translation_invariance_property := Π f g {fℱ gℱ}, 0 ≤ Int (g - f) (DifferenceFamily.closure g f gℱ fℱ) → Int f fℱ ≤ Int g gℱ /-- `TranslativeReduction` A reduction which is compatible with subtraction. We call a reduction a `TranslativeReduction` when it satisfies the `constant_difference_property` and the `translation_invariance_property` defined above. -/ class TranslativeReduction := (constant_difference : constant_difference_property ℱ Int) (translation_invariance : translation_invariance_property ℱ Int) end subtraction --———————————————————————————————————————————————————————————————————————-- end reduction --—————————————————————————————————————————————————————————————————————————-- section subdifferential --———————————————————————————————————————————————————————————————-- universes 𝒰y variables {Y : Type 𝒰y} [has_zero Y] [has_sub Y] [has_le Y] (φ : Y → Y) (t : Y) (𝒩 : 𝒫 Y) /-- `SubDifferential φ t 𝒩` The subdifferential property. The primary role of convexity in the classical inequality is the following. Given a convex function `φ` on `(a,b)` we know that for any `s,t,u ∈ (a,b)` such that `s < t < u`, it follows that `(φ t - φ s) / (t - s) ≤ (φ u - φ t) / (u - t)` From this we can deduce that there exists the supremum `β := sup_{s ∈ (a,t)} (φ t - φ s) / (t - s)` which then gives us the following inequality: `β ⬝ (s - t) ≤ φ s - φ t` To generalize this to a domain of discourse that does not have convex functions, we instead accept the last inequality by hypothesis and generalize multiplication by `β` from the left to function application. To ensure that this function application behaves well with zero we need that it vanish there which is analogous to the fact that `y ⬝ 0 = 0` in the real numbers. Since the inequality above holds only in `(a,b)` in the classical case, not on all of `ℝ`, we need to restrict the inequality to a specific subset of `Y`. We call this subset `𝒩`. -/ structure SubDifferential := (map : Y → Y) (root_at_zero : map 0 = 0) (lower_bound_property : Π s, 𝒩 s → map (s - t) ≤ (φ s) - (φ t)) --———————————————————————————————————————————————————————————————————————————————————————-- universes 𝒰x variables {X : Type 𝒰x} (ℱ : 𝒫 (X → Y)) (Int : Reduction ℱ) /-- `LeftFactorSubDifferential φ t 𝒩` A left factorizable subdifferential. If we have `β` a subdifferential corresponding to `φ`, `t`, and `𝒩`, then we say that it is a *left factor subdifferential* when `β` left factors with respect to the family `ℱ`. -/ structure LeftFactorSubDifferential extends SubDifferential φ t 𝒩 := (is_left_closed : left_closed ℱ map) (left_factors : left_factors ℱ Int map is_left_closed) end subdifferential --———————————————————————————————————————————————————————————————————-- section jensen_inequality --—————————————————————————————————————————————————————————————-- universes 𝒰y 𝒰x variables {Y : Type 𝒰y} [OrderedDifferenceDomain Y] {X : Type 𝒰x} (ℱ : 𝒫 (X → Y)) [PointFamily ℱ] [DifferenceFamily ℱ] (Int : Reduction ℱ) /-- `JensenReduction` A reduction which is strong enough to prove Jensen's Inequality. We have the following properties inherited from the individual structures: - `UnitalReduction` - `∫ ↓t = t` - `MonotonicReduction` - `(Π x, f x ≤ g x) → (∫ f ≤ ∫ g)` - `TranslativeReduction` - `∫ (f - ↓k) = (∫ f) - (∫ ↓k)` - `(0 ≤ ∫ (g - f)) → (∫ f ≤ ∫ g)` -/ class JensenReduction extends UnitalReduction ℱ Int, MonotonicReduction ℱ Int, TranslativeReduction ℱ Int /-- `jensen_inequality` Jensen's Inequality (`φ (∫ f) ≤ ∫ (φ ∘ f)`). The theorem exactly generalizes the classical Jensen inequality and so it is sufficient to prove that the measure-theoretic integral is a `JensenReduction` and that convex functions have the `LeftFactorSubDifferential` property to apply the following proof to the classical case. Proof sketches for these two facts are discussed above. NB: In this proof, we will be working to find a term which has the type of the goal instead of modifying the goal directly, so it is not necessary to look at the goals. Instead, follow the proof by reading the commentary which describes the change in the main term `inequality` which will satisfy the goal in the end. For simplicity the reducibility proofs are left unspecified while following the main term. -/ theorem jensen_inequality -- Proof that Int is a nice reduction. [JensenReduction ℱ Int] -- A reducible function f. (f : X → Y) (fℱ : ℱ f) -- A distinguished superset of the image of f. (𝒩 : 𝒫 Y) (image_contained_in_𝒩 : Π x, 𝒩 (f x)) -- A function φ which is left closed at f and has a LeftFactorSubDifferential at the -- reduction of f with the above distinguished superset 𝒩. (φ : Y → Y) (φfℱ : ℱ (φ ∘ f)) (subdifferential : LeftFactorSubDifferential φ (Int f fℱ) 𝒩 ℱ Int) -- From above, the Jensen Inequality follows: : φ (Int f fℱ) ≤ Int (φ ∘ f) φfℱ := begin -- We begin by introducing some relevant variables: -- The reduction of f. let t := Int f fℱ, -- The function F := λ x, f x - t and its proof of reducibility. let F := f - ↓t, let Fℱ := DifferenceFamily.closure f ↓t _ _, -- The subderivative of φ. let β := subdifferential.map, /- Π s, 𝒩 s → β (s - t) ≤ (φ s) - (φ t) —————————————————————————————————————— image_contained_in_𝒩 Π x, β (F x) ≤ (φ (f x)) - (φ t) To begin the proof, we use the fact that the subdifferential has the lower bound property inside of 𝒩 which contains the image of f, so we have that the inequality holds for all points of X. This is the main term to follow throughout the proof. -/ let inequality := λ x, subdifferential.lower_bound_property (f x) (image_contained_in_𝒩 x), /- Π x, β (F x) ≤ (φ (f x)) - (φ t) ————————————————————————————————— monotonicity ∫ β ∘ F ≤ ∫ (φ ∘ f - ↓(φ t)) Next, we use the fact that the reduction is monotonic to "integrate" both sides. -/ let inequality := MonotonicReduction.monotonicity Int (β ∘ F) (φ ∘ f - ↓(φ t)) inequality, /- ∫ β ∘ F ≤ ∫ (φ ∘ f - ↓(φ t)) ————————————————————————————— left_factors β (∫ F) ≤ ∫ (φ ∘ f - ↓(φ t)) Here we use the fact that the subdifferential left factors with respect to the reduction family. -/ rewrite subdifferential.left_factors F Fℱ at inequality, /- β (∫ F) ≤ ∫ (φ ∘ f - ↓(φ t)) ———————————————————————————————————————— constant_difference β ((∫ f) - (∫ ↓t)) ≤ ∫ (φ ∘ f - ↓(φ t)) Now we use the fact that our reduction has the constant difference property to distribute the reduction over the difference of functions. -/ rewrite TranslativeReduction.constant_difference Int at inequality, /- β ((∫ f) - (∫ ↓t)) ≤ ∫ (φ ∘ f - ↓(φ t)) ———————————————————————————————————————— constant_reduction β ((∫ f) - t) ≤ ∫ (φ ∘ f - ↓(φ t)) Since our reduction is unital we can replace the reduction of the constant function with the defining constant. -/ rewrite UnitalReduction.constant_reduction Int at inequality, /- β ((∫ f) - t) ≤ ∫ (φ ∘ f - ↓(φ t)) ——————————————————————————————————— vanishing_diagonal β 0 ≤ ∫ (φ ∘ f - ↓(φ t)) Since t := ∫ f we have that, (∫ f) - t := (∫ f) - (∫ f) so we can cancel like terms using the fact that Y is a difference domain. -/ rewrite DifferenceDomain.vanishing_diagonal at inequality, /- β 0 ≤ ∫ (φ ∘ f - ↓(φ t)) ————————————————————————— root_at_zero 0 ≤ ∫ (φ ∘ f - ↓(φ t)) To simplify the left hand side of the inequality we use the fact that the subderivative has a root at zero. -/ rewrite subdifferential.root_at_zero at inequality, /- 0 ≤ ∫ (φ ∘ f - ↓(φ t)) ——————————————————————— translation_invariance ∫ ↓(φ t) ≤ ∫ (φ ∘ f) To split the reduction of a difference, we use the translation invariance property because our reduction is translative. -/ let inequality := TranslativeReduction.translation_invariance Int ↓(φ t) (φ ∘ f) inequality, /- ∫ ↓(φ t) ≤ ∫ (φ ∘ f) ————————————————————— constant_reduction φ t ≤ ∫ (φ ∘ f) Again we use the fact that out reduction is unital to pull out the constant on the left hand side. -/ rewrite UnitalReduction.constant_reduction Int at inequality, /- φ t ≤ ∫ (φ ∘ f) ———————————————————— definition φ (∫ f) ≤ ∫ (φ ∘ f) And now the proof is complete. The inequality has the correct type to satisfy the main goal. All other goals can be deduced canonically by the proof assistant since the relevant proof terms are in the given context. -/ exact inequality, end -- □ end jensen_inequality --—————————————————————————————————————————————————————————————————--
d03d4944aa749b52feaf65ff316d381c61b9eb1b
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/LLVMOutput.lean
002298c8b4242a62cce06422f6662e8cb6d25e26
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
5,735
lean
import Init.Data.Array import Init.Data.Int import Std.Data.RBMap import Init.System.IO import LeanLLVM.AST import LeanLLVM.PP import LeanLLVM.DataLayout import LeanLLVM.LLVMCodes import LeanLLVM.LLVMFFI open Std (RBMap) namespace LLVM namespace Output @[reducible] def SymMap := RBMap Symbol FFI.Value Ord.compare @[reducible] def BlockMap := RBMap BlockLabel FFI.Value Ord.compare @[reducible] def ValueMap := RBMap Ident FFI.Value Ord.compare @[reducible] def TypeMap := RBMap String FFI.Type_ Ord.compare structure ValueContext := (symbolMap : SymMap) (blockMap : BlockMap) (valueMap : ValueMap) (typeMap : TypeMap) def ValueContext.init : ValueContext := { symbolMap := Std.RBMap.empty, blockMap := Std.RBMap.empty, valueMap := Std.RBMap.empty, typeMap := Std.RBMap.empty } end Output def Output (a:Type) : Type := IO.Ref LLVM.Output.ValueContext → IO a namespace Output instance monad : Monad Output := { bind := λmx mf r => mx r >>= λx => mf x r , pure := λ x r => pure x } instance monadExcept : MonadExcept IO.Error Output := { throw := λ err r => throw err, tryCatch := λ m handle r => tryCatch (m r) (λ err => handle err r), } instance mIO : MonadLiftT IO Output := { monadLift := λm r => m } def run {a:Type} (m:Output a) : IO (Output.ValueContext × a) := do let r <- IO.mkRef Output.ValueContext.init; let a <- m r; let vc <- r.get; pure (vc, a) def alterSymbolMap (f:SymMap → SymMap) : Output Unit := λ r => r.modify (λvc => { vc with symbolMap := f vc.symbolMap }) def lookupAlias (nm:String) : Output (Option FFI.Type_) := λr => do let vc <- r.get; pure (vc.typeMap.find? nm) /- def createFunction (m:Module) (nm:symbol) : Output LLVMFunction := do f <- newFunction m nm.symbol; alterSymbolMap (λsm => sm.insert -/ end Output def outputFloatType : FloatType → Code.TypeID | FloatType.half => Code.TypeID.half | FloatType.float => Code.TypeID.float | FloatType.double => Code.TypeID.double | FloatType.fp128 => Code.TypeID.fp128 | FloatType.x86FP80 => Code.TypeID.x86FP80 | FloatType.ppcFP128 => Code.TypeID.ppcFP128 def outputPrimType (ctx:FFI.Context) : PrimType → IO FFI.Type_ | PrimType.label => FFI.newPrimitiveType ctx Code.TypeID.label | PrimType.token => FFI.newPrimitiveType ctx Code.TypeID.token | PrimType.void => FFI.newPrimitiveType ctx Code.TypeID.void | PrimType.floatType ft => FFI.newPrimitiveType ctx (outputFloatType ft) | PrimType.x86mmx => FFI.newPrimitiveType ctx Code.TypeID.x86mmx | PrimType.metadata => FFI.newPrimitiveType ctx Code.TypeID.metadata | PrimType.integer n => FFI.newIntegerType ctx n partial def outputType (ctx:FFI.Context) : LLVMType → Output FFI.Type_ | LLVMType.prim pt => (outputPrimType ctx pt) | LLVMType.alias nm => do let x : Option FFI.Type_ <- Output.lookupAlias nm; match x with | some tp => pure tp | none => throw (IO.userError ("Unknown type alias: " ++ nm)) | LLVMType.array n t => do let t' <- outputType ctx t; FFI.newArrayType n t' | LLVMType.vector n t => do let t' <- outputType ctx t; FFI.newVectorType n t' | LLVMType.ptr t => do let t' <- outputType ctx t; FFI.newPointerType t' | LLVMType.funType ret args varargs => do let ret' <- outputType ctx ret; let args' <- Array.mapM (outputType ctx) args; FFI.newFunctionType ret' args' varargs | LLVMType.struct packed tps => do let tps' <- tps.mapM (outputType ctx); FFI.newLiteralStructType packed tps' def setupTypeAlias (ctx:FFI.Context) (nm:String) : Output FFI.Type_ := λr => do let vc <- r.get; let tp <- FFI.newOpaqueStructType ctx nm; let vc' := { vc with typeMap := vc.typeMap.insert nm tp }; r.set vc'; pure tp def finalizeTypeAlias (ctx:FFI.Context) (ty:FFI.Type_) : TypeDeclBody → Output Unit | TypeDeclBody.opaque => pure () | TypeDeclBody.defn (LLVMType.struct packed tps) => do let tps' <- tps.mapM (outputType ctx); (FFI.setStructTypeBody ty packed tps'); pure () | TypeDeclBody.defn _ => throw (IO.userError "type alias defintion must be a struct body") -- Process type aliases in two phases. First, allocate named, opaque struct -- types for each alias and record them in the value context. Next, process -- the bodies of type aliases and set the body of the non-opaque named struct types. -- -- This two-phase approach ensures that recursive struct groups are properly handled. def outputTypeAliases (ctx:FFI.Context) (tds:Array TypeDecl) : Output Unit := do let fs <- tds.mapM (λtd => setupTypeAlias ctx td.name >>= λty => pure (finalizeTypeAlias ctx ty td.decl)); for action in fs do action def outputDeclare (ctx:FFI.Context) (m:FFI.Module) (d:Declare) : Output Unit := do let funtp <- outputType ctx (LLVMType.funType d.retType d.args d.varArgs); let f <- (FFI.newFunction m funtp d.name.symbol); Output.alterSymbolMap (λsm => sm.insert d.name (FFI.functionToValue f)) def outputDefine (ctx:FFI.Context) (m:FFI.Module) (d:Define) : Output Unit := do let argTypes := d.args.map (λa => a.type); let funtp <- outputType ctx (LLVMType.funType d.retType argTypes d.varArgs); let f <- (FFI.newFunction m funtp d.name.symbol); Output.alterSymbolMap (λsm => sm.insert d.name (FFI.functionToValue f)); -- TODO!!! pure () def outputModule (ctx:FFI.Context) (m:Module) : Output FFI.Module := do outputTypeAliases ctx m.types; let modnm := match m.sourceName with | some nm => nm | none => ""; let ffimod <- (FFI.newModule ctx modnm); for decl in m.declares do outputDeclare ctx ffimod decl for defn in m.defines do outputDefine ctx ffimod defn pure ffimod end LLVM
434c915ff2c6ed872f34fd50a0f191383f28a51f
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/Script/Type.lean
8ab8b168522dc19799e0f2466ccb52138cc11b2b
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,227
lean
import Lean.Parser import Papyrus.Script.ParserUtil import Papyrus.Script.AddressSpace import Papyrus.Script.IntegerType import Papyrus.IR.Type namespace Papyrus.Script open Lean Syntax Parser scoped postfix:max "*" => pointerType -------------------------------------------------------------------------------- -- # Type Category -------------------------------------------------------------------------------- declare_syntax_cat llvmType (behavior := symbol) def typeParser (rbp : Nat := 0) := categoryParser `llvmType rbp macro "type" "(" t:term ")" : llvmType => t macro (priority := low) t:ident : llvmType => t def expandType (stx : Syntax) : MacroM Syntax := expandMacros stx def expandTypeAsRef (stx : Syntax) : MacroM Syntax := do `(Type.getRef $(← expandType stx)) def expandTypeAsRefArrow (stx : Syntax) : MacroM Syntax := do `(← $(← expandTypeAsRef stx)) scoped macro "llvm " &"type " t:llvmType : term => expandType t -------------------------------------------------------------------------------- -- # Primitive Types -------------------------------------------------------------------------------- -- ## Floating Point Types macro t:"half" : llvmType => mkCIdentFrom t ``halfType macro t:"bfloat" : llvmType => mkCIdentFrom t ``bfloatType macro t:"float" : llvmType => mkCIdentFrom t ``floatType macro t:"double" : llvmType => mkCIdentFrom t ``doubleType macro t:"x86_fp80" : llvmType => mkCIdentFrom t ``x86FP80Type macro t:"fp128" : llvmType => mkCIdentFrom t ``fp128Type macro t:"ppc_fp128" : llvmType => mkCIdentFrom t ``ppcFP128Type -- ## Special Types macro t:"void" : llvmType => mkCIdentFrom t ``voidType macro t:"label" : llvmType => mkCIdentFrom t ``labelType macro t:"metadata" : llvmType => mkCIdentFrom t ``metadataType macro t:"x86_mmx" : llvmType => mkCIdentFrom t ``x86MMXType macro t:"x86_amx" : llvmType => mkCIdentFrom t ``x86AMXType macro t:"token" : llvmType => mkCIdentFrom t ``tokenType -------------------------------------------------------------------------------- -- # Derived Type Parsers -------------------------------------------------------------------------------- -- ## Integer Types macro t:intTypeLit : llvmType => expandIntTypeLitAsType t -- ## Function Types @[runParserAttributeHooks] def vararg := leading_parser "..." @[runParserAttributeHooks] def params := leading_parser "(" >> sepBy typeParser "," (allowTrailingSep := true) >> Parser.optional vararg >> ")" def expandParams (stx : Syntax) : MacroM (Array Syntax × Syntax) := do (← stx[1].getSepArgs.mapM expandType, (quote !stx[2].isNone)) def expandFunTypeLit (rty : Syntax) (params : Syntax) : MacroM Syntax := do let (ptys, vararg) ← expandParams params mkCAppFrom rty ``functionType #[← expandType rty, quote ptys, vararg] macro rt:llvmType ps:params : llvmType => expandFunTypeLit rt ps -- ## Pointer Types def expandPtrTypeLit (ty : Syntax) (addrspace? : Option Syntax) : MacroM Syntax := do mkCAppFrom ty ``pointerType #[← expandType ty, ← expandOptAddrspace addrspace?] macro t:llvmType a?:optional(addrspace) "*" : llvmType => expandPtrTypeLit t a? -- ## Struct Types @[runParserAttributeHooks] def packedStructTypeLit := leading_parser "<{" >> sepBy typeParser "," >> "}>" @[runParserAttributeHooks] def unpackedStructTypeLit := leading_parser "{" >> sepBy typeParser "," >> "}" @[runParserAttributeHooks] def structTypeLit := unpackedStructTypeLit <|> packedStructTypeLit def expandStructTypeLit : (stx : Syntax) → MacroM (Array Syntax × Bool) | `(unpackedStructTypeLit| { $[$ts:llvmType],* }) => do (← ts.mapM expandType, false) | `(packedStructTypeLit| $x) => do (← x[1].getSepArgs.mapM expandType, true) | stx => Macro.throwErrorAt stx "ill-formed struct llvmType literal" def expandLiteralStructTypeLit (stx : Syntax) : MacroM Syntax := do let (tys, packed) ← expandStructTypeLit stx mkCAppFrom stx ``literalStructType #[quote tys, quote packed] macro t:structTypeLit : llvmType => expandLiteralStructTypeLit t macro "%" id:ident : llvmType => mkCAppFrom id ``opaqueStructType #[identAsStrLit id] -- ## Array Types def xTk := nonReservedSymbol "x" <|> "×" @[runParserAttributeHooks] def arrayTypeLit := leading_parser "[" >> termParser maxPrec >> xTk >> typeParser >> "]" def expandArrayTypeLit : Macro | stx@`(arrayTypeLit| [$x x $t]) => do mkCAppFrom stx ``arrayType #[← expandType t, x] | stx => Macro.throwErrorAt stx "ill-formed array llvmType literal" macro t:arrayTypeLit : llvmType => expandArrayTypeLit t -- ## Vector Types def optVScale := Parser.optional (nonReservedSymbol "vscale" >> xTk) @[runParserAttributeHooks] def vectorTypeLit := leading_parser "<" >> optVScale >> termParser maxPrec >> xTk >> typeParser >> ">" def expandVectorTypeLit : (stx : Syntax) → MacroM Syntax | stx@`(vectorTypeLit| <$x x $t>) => do mkCAppFrom stx ``fixedVectorType #[← expandType t, x] | stx@`(vectorTypeLit| <vscale x $x x $t>) => do mkCAppFrom stx ``scalableVectorType #[← expandType t, x] | stx => Macro.throwErrorAt stx "ill-formed vector llvmType literal" macro t:vectorTypeLit : llvmType => expandVectorTypeLit t
7c473879f9ced60fd48c55d6da2e4e7612f5886f
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/init/equiv.hlean
ba11648afbeba522483f8f1e56683acf3332e0e9
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,946
hlean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jeremy Avigad, Jakob von Raumer -- Ported from Coq HoTT prelude import .path .function open eq function -- Equivalences -- ------------ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := (inv : B → A) (retr : (f ∘ inv) ∼ id) (sect : (inv ∘ f) ∼ id) (adj : Πx, retr (f x) = ap f (sect x)) -- A more bundled version of equivalence to calculate with structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) -- Some instances and closure properties of equivalences namespace is_equiv postfix `⁻¹` := inv variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B} -- The identity function is an equivalence. definition id_is_equiv : (@is_equiv A A id) := is_equiv.mk id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. protected definition compose [Hf : is_equiv f] [Hg : is_equiv g] : (is_equiv (g ∘ f)) := is_equiv.mk ((inv f) ∘ (inv g)) (λc, ap g (retr f (g⁻¹ c)) ⬝ retr g c) (λa, ap (inv f) (sect g (f a)) ⬝ sect f a) (λa, (whiskerL _ (adj g (f a))) ⬝ (ap_pp g _ _)⁻¹ ⬝ ap02 g (concat_A1p (retr f) (sect g (f a))⁻¹ ⬝ (ap_compose (inv f) f _ ◾ adj f a) ⬝ (ap_pp f _ _)⁻¹ ) ⬝ (ap_compose f g _)⁻¹ ) -- Any function equal to an equivalence is an equivlance as well. definition path_closed [Hf : is_equiv f] (Heq : f = f') : (is_equiv f') := eq.rec_on Heq Hf -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [Hf : is_equiv f] (Hty : f ∼ f') : (is_equiv f') := let sect' := (λ b, (Hty (inv f b))⁻¹ ⬝ retr f b) in let retr' := (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ sect f a) in let adj' := (λ (a : A), let ff'a := Hty a in let invf := inv f in let secta := sect f a in let retrfa := retr f (f a) in let retrf'a := retr f (f' a) in have eq1 : _ = _, from calc ap f secta ⬝ ff'a = retrfa ⬝ ff'a : ap _ (@adj _ _ f _ _) ... = ap (f ∘ invf) ff'a ⬝ retrf'a : concat_A1p ... = ap f (ap invf ff'a) ⬝ retrf'a : ap_compose invf f, have eq2 : _ = _, from calc retrf'a = (ap f (ap invf ff'a))⁻¹ ⬝ (ap f secta ⬝ ff'a) : moveL_Vp _ _ _ (eq1⁻¹) ... = ap f (ap invf ff'a)⁻¹ ⬝ (ap f secta ⬝ Hty a) : ap_V invf ff'a ... = ap f (ap invf ff'a)⁻¹ ⬝ (Hty (invf (f a)) ⬝ ap f' secta) : concat_Ap ... = (ap f (ap invf ff'a)⁻¹ ⬝ Hty (invf (f a))) ⬝ ap f' secta : concat_pp_p ... = (ap f ((ap invf ff'a)⁻¹) ⬝ Hty (invf (f a))) ⬝ ap f' secta : ap_V ... = (Hty (invf (f' a)) ⬝ ap f' ((ap invf ff'a)⁻¹)) ⬝ ap f' secta : concat_Ap ... = (Hty (invf (f' a)) ⬝ (ap f' (ap invf ff'a))⁻¹) ⬝ ap f' secta : ap_V ... = Hty (invf (f' a)) ⬝ ((ap f' (ap invf ff'a))⁻¹ ⬝ ap f' secta) : concat_pp_p, have eq3 : _ = _, from calc (Hty (invf (f' a)))⁻¹ ⬝ retrf'a = (ap f' (ap invf ff'a))⁻¹ ⬝ ap f' secta : moveR_Vp _ _ _ eq2 ... = (ap f' ((ap invf ff'a)⁻¹)) ⬝ ap f' secta : ap_V ... = ap f' ((ap invf ff'a)⁻¹ ⬝ secta) : ap_pp, eq3) in is_equiv.mk (inv f) sect' retr' adj' end is_equiv namespace is_equiv context parameters {A B : Type} (f : A → B) (g : B → A) (ret : f ∘ g ∼ id) (sec : g ∘ f ∼ id) definition adjointify_sect' : g ∘ f ∼ id := (λx, ap g (ap f (inverse (sec x))) ⬝ ap g (ret (f x)) ⬝ sec x) definition adjointify_adj' : Π (x : A), ret (f x) = ap f (adjointify_sect' x) := (λ (a : A), let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f ((sec a)⁻¹))) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : !concat_1p⁻¹ ... = (ret (f a) ⬝ (ret (f a)⁻¹)) ⬝ ap f (sec a) : {!concat_pV⁻¹} ... = ((ret (fgfa))⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : {!concat_pA1⁻¹} ... = ((ret (fgfa))⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : {ap_compose g f _} ... = (ret (fgfa))⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : !concat_pp_p, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !concat_p1 ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : moveL_Vp _ _ _ eq2 ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : !concat_p_pp ... = (ap f ((sec a)⁻¹) ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : {!ap_V⁻¹} ... = ((ap f ((sec a)⁻¹) ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : !concat_p_pp ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f ((sec a)⁻¹))) ⬝ fgretrfa) ⬝ ap f (sec a) : {!concat_pA1⁻¹} ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : {ap_compose g f _} ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : {!concat_p_pp⁻¹} ... = retrfa⁻¹ ⬝ ap f (ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : {!ap_pp⁻¹} ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : !concat_p_pp⁻¹ ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ sec a) : {!ap_pp⁻¹}, have eq4 : ret (f a) = ap f ((ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ sec a), from moveR_M1 _ _ eq3, eq4) definition adjointify : is_equiv f := is_equiv.mk g ret adjointify_sect' adjointify_adj' end end is_equiv namespace is_equiv variables {A B: Type} (f : A → B) --The inverse of an equivalence is, again, an equivalence. definition inv_closed [instance] [Hf : is_equiv f] : (is_equiv (inv f)) := adjointify (inv f) f (sect f) (retr f) end is_equiv namespace is_equiv variables {A : Type} section variables {B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] include Hf definition cancel_R (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv [visible] : is_equiv (f⁻¹), from inv_closed f, @homotopy_closed _ _ _ _ (compose (f⁻¹) (g ∘ f)) (λb, ap g (@retr _ _ f _ b)) definition cancel_L (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv [visible] : is_equiv (f⁻¹), from inv_closed f, @homotopy_closed _ _ _ _ (compose (f ∘ g) (f⁻¹)) (λa, sect f (g a)) --Rewrite rules definition moveR_M {x : A} {y : B} (p : x = (inv f) y) : (f x = y) := (ap f p) ⬝ (@retr _ _ f _ y) definition moveL_M {x : A} {y : B} (p : (inv f) y = x) : (y = f x) := (moveR_M f (p⁻¹))⁻¹ definition moveR_V {x : B} {y : A} (p : x = f y) : (inv f) x = y := ap (f⁻¹) p ⬝ sect f y definition moveL_V {x : B} {y : A} (p : f y = x) : y = (inv f) x := (moveR_V f (p⁻¹))⁻¹ definition ap_closed [instance] (x y : A) : is_equiv (ap f) := adjointify (ap f) (λq, (inverse (sect f x)) ⬝ ap (f⁻¹) q ⬝ sect f y) (λq, !ap_pp ⬝ whiskerR !ap_pp _ ⬝ ((!ap_V ⬝ inverse2 ((adj f _)⁻¹)) ◾ (inverse (ap_compose (f⁻¹) f _)) ◾ (adj f _)⁻¹) ⬝ concat_pA1_p (retr f) _ _ ⬝ whiskerR !concat_Vp _ ⬝ !concat_1p) (λp, whiskerR (whiskerL _ ((ap_compose f (f⁻¹) _)⁻¹)) _ ⬝ concat_pA1_p (sect f) _ _ ⬝ whiskerR !concat_Vp _ ⬝ !concat_1p) -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition equiv_rect (P : B -> Type) : (Πx, P (f x)) → (Πy, P y) := (λg y, eq.transport _ (retr f y) (g (f⁻¹ y))) definition equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = transport P (retr f (f x)) (df (f⁻¹ (f x))) : idp ... = transport P (ap f (sect f x)) (df (f⁻¹ (f x))) : adj f ... = transport (P ∘ f) (sect f x) (df (f⁻¹ (f x))) : transport_compose ... = df x : apD df (sect f x) end --Transporting is an equivalence protected definition transport [instance] (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk (transport P (p⁻¹)) (transport_pV P p) (transport_Vp P p) (transport_pVp P p) end is_equiv namespace equiv attribute to_is_equiv [instance] infix `≃`:25 := equiv context parameters {A B C : Type} (eqf : A ≃ B) private definition f : A → B := to_fun eqf private definition Hf [instance] : is_equiv f := to_is_equiv eqf protected definition refl : A ≃ A := equiv.mk id is_equiv.id_is_equiv theorem trans (eqg: B ≃ C) : A ≃ C := equiv.mk ((to_fun eqg) ∘ f) (is_equiv.compose f (to_fun eqg)) theorem path_closed (f' : A → B) (Heq : to_fun eqf = f') : A ≃ B := equiv.mk f' (is_equiv.path_closed f Heq) theorem symm : B ≃ A := equiv.mk (is_equiv.inv f) !is_equiv.inv_closed theorem cancel_R (g : B → C) [Hgf : is_equiv (g ∘ f)] : B ≃ C := equiv.mk g (is_equiv.cancel_R f _) theorem cancel_L (g : C → A) [Hgf : is_equiv (f ∘ g)] : C ≃ A := equiv.mk g (is_equiv.cancel_L f _) protected theorem transport (P : A → Type) {x y : A} {p : x = y} : (P x) ≃ (P y) := equiv.mk (transport P p) (is_equiv.transport P p) end context parameters {A B : Type} (eqf eqg : A ≃ B) private definition Hf [instance] : is_equiv (to_fun eqf) := to_is_equiv eqf private definition Hg [instance] : is_equiv (to_fun eqg) := to_is_equiv eqg --We need this theorem for the funext_from_ua proof theorem inv_eq (p : eqf = eqg) : is_equiv.inv (to_fun eqf) = is_equiv.inv (to_fun eqg) := eq.rec_on p idp end -- calc enviroment -- Note: Calculating with substitutions needs univalence calc_trans trans calc_refl refl calc_symm symm end equiv
fb134235ee56d1f57b78ffab9b091c32ca6c3f68
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/algebra/group/hom.lean
828ae237bda9494b14c190e4f9d90f96ed9c895b
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
7,865
lean
/- Copyright (c) 2014 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov Homomorphisms of multiplicative and additive (semi)groups and monoids. -/ import algebra.group.to_additive algebra.group.basic universes u v variables {α : Type u} {β : Type v} class is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop := (map_mul : ∀ x y, f (x * y) = f x * f y) class is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) attribute [to_additive is_add_hom] is_mul_hom attribute [to_additive is_add_hom.cases_on] is_mul_hom.cases_on attribute [to_additive is_add_hom.dcases_on] is_mul_hom.dcases_on attribute [to_additive is_add_hom.drec] is_mul_hom.drec attribute [to_additive is_add_hom.drec_on] is_mul_hom.drec_on attribute [to_additive is_add_hom.map_add] is_mul_hom.map_mul attribute [to_additive is_add_hom.mk] is_mul_hom.mk attribute [to_additive is_add_hom.rec] is_mul_hom.rec attribute [to_additive is_add_hom.rec_on] is_mul_hom.rec_on namespace is_mul_hom variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ] @[to_additive is_add_hom.id] instance id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl} @[to_additive is_add_hom.comp] instance comp (f : α → β) (g : β → γ) [is_mul_hom f] [hg : is_mul_hom g] : is_mul_hom (g ∘ f) := { map_mul := λ x y, by simp only [function.comp, map_mul f, map_mul g] } @[to_additive is_add_hom.add] lemma mul {α β} [semigroup α] [comm_semigroup β] (f g : α → β) [is_mul_hom f] [is_mul_hom g] : is_mul_hom (λa, f a * g a) := { map_mul := assume a b, by simp only [map_mul f, map_mul g, mul_comm, mul_assoc, mul_left_comm] } attribute [instance] is_mul_hom.mul is_add_hom.add @[to_additive is_add_hom.neg] lemma inv {α β} [has_mul α] [comm_group β] (f : α → β) [is_mul_hom f] : is_mul_hom (λa, (f a)⁻¹) := { map_mul := assume a b, (map_mul f a b).symm ▸ mul_inv _ _ } attribute [instance] is_mul_hom.inv is_add_hom.neg end is_mul_hom class is_monoid_hom [monoid α] [monoid β] (f : α → β) extends is_mul_hom f : Prop := (map_one : f 1 = 1) class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) extends is_add_hom f : Prop := (map_zero : f 0 = 0) attribute [to_additive is_add_monoid_hom] is_monoid_hom attribute [to_additive is_add_monoid_hom.to_is_add_hom] is_monoid_hom.to_is_mul_hom attribute [to_additive is_add_monoid_hom.mk] is_monoid_hom.mk attribute [to_additive is_add_monoid_hom.cases_on] is_monoid_hom.cases_on attribute [to_additive is_add_monoid_hom.dcases_on] is_monoid_hom.dcases_on attribute [to_additive is_add_monoid_hom.rec] is_monoid_hom.rec attribute [to_additive is_add_monoid_hom.drec] is_monoid_hom.drec attribute [to_additive is_add_monoid_hom.rec_on] is_monoid_hom.rec_on attribute [to_additive is_add_monoid_hom.drec_on] is_monoid_hom.drec_on attribute [to_additive is_add_monoid_hom.map_zero] is_monoid_hom.map_one namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] @[to_additive is_add_monoid_hom.map_add] lemma map_mul (x y) : f (x * y) = f x * f y := is_mul_hom.map_mul f x y end is_monoid_hom @[to_additive is_add_monoid_hom.of_add] theorem is_monoid_hom.of_mul [monoid α] [group β] (f : α → β) [is_mul_hom f] : is_monoid_hom f := { map_one := mul_self_iff_eq_one.1 $ by rw [← is_mul_hom.map_mul f, one_mul] } namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] @[to_additive is_add_monoid_hom.id] instance id : is_monoid_hom (@id α) := { map_one := rfl } @[to_additive is_add_monoid_hom.comp] instance comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] : is_monoid_hom (g ∘ f) := { map_one := show g _ = 1, by rw [map_one f, map_one g] } end is_monoid_hom namespace is_add_monoid_hom instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, x * y) := { map_zero := mul_zero x, map_add := λ y z, mul_add x y z } instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, y * x) := { map_zero := zero_mul x, map_add := λ y z, add_mul y z x } end is_add_monoid_hom /-- Predicate for group homomorphism. -/ class is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop class is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop attribute [to_additive is_add_group_hom] is_group_hom attribute [to_additive is_add_group_hom.to_is_add_hom] is_group_hom.to_is_mul_hom attribute [to_additive is_add_group_hom.cases_on] is_group_hom.cases_on attribute [to_additive is_add_group_hom.dcases_on] is_group_hom.dcases_on attribute [to_additive is_add_group_hom.rec] is_group_hom.rec attribute [to_additive is_add_group_hom.drec] is_group_hom.drec attribute [to_additive is_add_group_hom.rec_on] is_group_hom.rec_on attribute [to_additive is_add_group_hom.drec_on] is_group_hom.drec_on attribute [to_additive is_add_group_hom.mk] is_group_hom.mk /-- Construct `is_group_hom` from its only hypothesis. The default constructor tries to get `is_mul_hom` from class instances, and this makes some proofs fail. -/ @[to_additive is_add_group_hom.mk'] lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) : is_group_hom f := { map_mul := hf } namespace is_group_hom variables [group α] [group β] (f : α → β) [is_group_hom f] open is_mul_hom (map_mul) @[to_additive is_add_group_hom.to_is_add_monoid_hom] instance to_is_monoid_hom : is_monoid_hom f := is_monoid_hom.of_mul f @[to_additive is_add_group_hom.map_zero] lemma map_one : f 1 = 1 := is_monoid_hom.map_one f @[to_additive is_add_group_hom.map_neg] theorem map_inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← map_mul f, inv_mul_self, map_one f] @[to_additive is_add_group_hom.id] instance id : is_group_hom (@id α) := { } @[to_additive is_add_group_hom.comp] instance comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) := { } @[to_additive is_add_group_hom.injective_iff] lemma injective_iff (f : α → β) [is_group_hom f] : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← is_group_hom.map_one f; exact @h _ _, λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← map_inv f, ← map_mul f] at hxy; simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩ @[to_additive is_add_group_hom.add] lemma mul {α β} [group α] [comm_group β] (f g : α → β) [is_group_hom f] [is_group_hom g] : is_group_hom (λa, f a * g a) := { } attribute [instance] is_group_hom.mul is_add_group_hom.add @[to_additive is_add_group_hom.neg] lemma inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] : is_group_hom (λa, (f a)⁻¹) := { } attribute [instance] is_group_hom.inv is_add_group_hom.neg end is_group_hom @[to_additive neg.is_add_group_hom] lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) := { map_mul := mul_inv } attribute [instance] inv.is_group_hom neg.is_add_group_hom namespace is_add_group_hom variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] lemma map_sub (a b) : f (a - b) = f a - f b := calc f (a + -b) = f a + f (-b) : is_add_hom.map_add f _ _ ... = f a + -f b : by rw [map_neg f] end is_add_group_hom lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β] (f g : α → β) [is_add_group_hom f] [is_add_group_hom g] : is_add_group_hom (λa, f a - g a) := is_add_group_hom.add f (λa, - g a) attribute [instance] is_add_group_hom.sub
e90e06268a7cdcd8ed58cffa412709ec1c998dab
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/interactive/num2.lean
21342523ab983e1d063ed6940a7e0d703e636015
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,453
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 logic.inhabited -- pos_num and num are two auxiliary datatypes used when parsing numerals such as 13, 0, 26. -- The parser will generate the terms (pos (bit1 (bit1 (bit0 one)))), zero, and (pos (bit0 (bit1 (bit1 one)))). -- This representation can be coerced in whatever we want (e.g., naturals, integers, reals, etc). inductive pos_num : Type := one : pos_num, bit1 : pos_num → pos_num, bit0 : pos_num → pos_num theorem pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one namespace pos_num definition inc (a : pos_num) : pos_num := rec (bit0 one) (λn r, bit0 r) (λn r, bit1 n) a definition num_bits (a : pos_num) : pos_num := rec one (λn r, inc r) (λn r, inc r) a end pos_num inductive num : Type := zero : num, pos : pos_num → num theorem num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero namespace num definition inc (a : num) : num := rec (pos pos_num.one) (λp, pos (pos_num.inc p)) a definition num_bits (a : num) : num := rec (pos pos_num.one) (λp, pos (pos_num.num_bits p)) a end num
f44871bc0d6c54a09ae9e77180b244aa6f906c73
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/02_Dependent_Type_Theory.org.7.lean
ce43dfc6f3400ce0e100eb06e70b2dfae85e9510
[]
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
55
lean
/- page 14 -/ import standard check Type -- Type
07c0d8f033b83fca4b5e6927821911e2c044b64b
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/fiber_bundle.lean
5ebc7684700b6180d02c3562d1952abc2e9ca7ef
[ "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
59,880
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.bundle import topology.algebra.order.basic import topology.local_homeomorph /-! # Fiber bundles A topological fiber bundle with fiber `F` over a base `B` is a space projecting on `B` for which the fibers are all homeomorphic to `F`, such that the local situation around each point is a direct product. We define a predicate `is_topological_fiber_bundle F p` saying that `p : Z → B` is a topological fiber bundle with fiber `F`. It is in general nontrivial to construct a fiber bundle. A way is to start from the knowledge of how changes of local trivializations act on the fiber. From this, one can construct the total space of the bundle and its topology by a suitable gluing construction. The main content of this file is an implementation of this construction: starting from an object of type `topological_fiber_bundle_core` registering the trivialization changes, one gets the corresponding fiber bundle and projection. Similarly we implement the object `topological_fiber_prebundle` which allows to define a topological fiber bundle from trivializations given as local equivalences with minimum additional properties. ## Main definitions ### Basic definitions * `trivialization F p` : structure extending local homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. * `is_topological_fiber_bundle F p` : Prop saying that the map `p` between topological spaces is a fiber bundle with fiber `F`. * `is_trivial_topological_fiber_bundle F p` : Prop saying that the map `p : Z → B` between topological spaces is a trivial topological fiber bundle, i.e., there exists a homeomorphism `h : Z ≃ₜ B × F` such that `proj x = (h x).1`. ### Operations on bundles We provide the following operations on `trivialization`s. * `trivialization.comap`: given a local trivialization `e` of a fiber bundle `p : Z → B`, a continuous map `f : B' → B` and a point `b' : B'` such that `f b' ∈ e.base_set`, `e.comap f hf b' hb'` is a trivialization of the pullback bundle. The pullback bundle (a.k.a., the induced bundle) has total space `{(x, y) : B' × Z | f x = p y}`, and is given by `λ ⟨(x, y), h⟩, x`. * `is_topological_fiber_bundle.comap`: if `p : Z → B` is a topological fiber bundle, then its pullback along a continuous map `f : B' → B` is a topological fiber bundle as well. * `trivialization.comp_homeomorph`: given a local trivialization `e` of a fiber bundle `p : Z → B` and a homeomorphism `h : Z' ≃ₜ Z`, returns a local trivialization of the fiber bundle `p ∘ h`. * `is_topological_fiber_bundle.comp_homeomorph`: if `p : Z → B` is a topological fiber bundle and `h : Z' ≃ₜ Z` is a homeomorphism, then `p ∘ h : Z' → B` is a topological fiber bundle with the same fiber. ### Construction of a bundle from trivializations * `bundle.total_space E` is a type synonym for `Σ (x : B), E x`, that we can endow with a suitable topology. * `topological_fiber_bundle_core ι B F` : structure registering how changes of coordinates act on the fiber `F` above open subsets of `B`, where local trivializations are indexed by `ι`. Let `Z : topological_fiber_bundle_core ι B F`. Then we define * `Z.fiber x` : the fiber above `x`, homeomorphic to `F` (and defeq to `F` as a type). * `Z.total_space` : the total space of `Z`, defined as a `Type` as `Σ (b : B), F`, but with a twisted topology coming from the fiber bundle structure. It is (reducibly) the same as `bundle.total_space Z.fiber`. * `Z.proj` : projection from `Z.total_space` to `B`. It is continuous. * `Z.local_triv i`: for `i : ι`, bundle trivialization above the set `Z.base_set i`, which is an open set in `B`. * `pretrivialization F proj` : trivialization as a local equivalence, mainly used when the topology on the total space has not yet been defined. * `topological_fiber_prebundle F proj` : structure registering a cover of prebundle trivializations and requiring that the relative transition maps are local homeomorphisms. * `topological_fiber_prebundle.total_space_topology a` : natural topology of the total space, making the prebundle into a bundle. ## Implementation notes A topological fiber bundle with fiber `F` over a base `B` is a family of spaces isomorphic to `F`, indexed by `B`, which is locally trivial in the following sense: there is a covering of `B` by open sets such that, on each such open set `s`, the bundle is isomorphic to `s × F`. To construct a fiber bundle formally, the main data is what happens when one changes trivializations from `s × F` to `s' × F` on `s ∩ s'`: one should get a family of homeomorphisms of `F`, depending continuously on the base point, satisfying basic compatibility conditions (cocycle property). Useful classes of bundles can then be specified by requiring that these homeomorphisms of `F` belong to some subgroup, preserving some structure (the "structure group of the bundle"): then these structures are inherited by the fibers of the bundle. Given such trivialization change data (encoded below in a structure called `topological_fiber_bundle_core`), one can construct the fiber bundle. The intrinsic canonical mathematical construction is the following. The fiber above `x` is the disjoint union of `F` over all trivializations, modulo the gluing identifications: one gets a fiber which is isomorphic to `F`, but non-canonically (each choice of one of the trivializations around `x` gives such an isomorphism). Given a trivialization over a set `s`, one gets an isomorphism between `s × F` and `proj^{-1} s`, by using the identification corresponding to this trivialization. One chooses the topology on the bundle that makes all of these into homeomorphisms. For the practical implementation, it turns out to be more convenient to avoid completely the gluing and quotienting construction above, and to declare above each `x` that the fiber is `F`, but thinking that it corresponds to the `F` coming from the choice of one trivialization around `x`. This has several practical advantages: * without any work, one gets a topological space structure on the fiber. And if `F` has more structure it is inherited for free by the fiber. * In the case of the tangent bundle of manifolds, this implies that on vector spaces the derivative (from `F` to `F`) and the manifold derivative (from `tangent_space I x` to `tangent_space I' (f x)`) are equal. A drawback is that some silly constructions will typecheck: in the case of the tangent bundle, one can add two vectors in different tangent spaces (as they both are elements of `F` from the point of view of Lean). To solve this, one could mark the tangent space as irreducible, but then one would lose the identification of the tangent space to `F` with `F`. There is however a big advantage of this situation: even if Lean can not check that two basepoints are defeq, it will accept the fact that the tangent spaces are the same. For instance, if two maps `f` and `g` are locally inverse to each other, one can express that the composition of their derivatives is the identity of `tangent_space I x`. One could fear issues as this composition goes from `tangent_space I x` to `tangent_space I (g (f x))` (which should be the same, but should not be obvious to Lean as it does not know that `g (f x) = x`). As these types are the same to Lean (equal to `F`), there are in fact no dependent type difficulties here! For this construction of a fiber bundle from a `topological_fiber_bundle_core`, we should thus choose for each `x` one specific trivialization around it. We include this choice in the definition of the `topological_fiber_bundle_core`, as it makes some constructions more functorial and it is a nice way to say that the trivializations cover the whole space `B`. With this definition, the type of the fiber bundle space constructed from the core data is just `Σ (b : B), F `, but the topology is not the product one, in general. We also take the indexing type (indexing all the trivializations) as a parameter to the fiber bundle core: it could always be taken as a subtype of all the maps from open subsets of `B` to continuous maps of `F`, but in practice it will sometimes be something else. For instance, on a manifold, one will use the set of charts as a good parameterization for the trivializations of the tangent bundle. Or for the pullback of a `topological_fiber_bundle_core`, the indexing type will be the same as for the initial bundle. ## Tags Fiber bundle, topological bundle, local trivialization, structure group -/ variables {ι : Type*} {B : Type*} {F : Type*} open topological_space filter set open_locale topological_space classical /-! ### General definition of topological fiber bundles -/ section topological_fiber_bundle variables (F) {Z : Type*} [topological_space B] [topological_space F] {proj : Z → B} /-- This structure contains the information left for a local trivialization (which is implemented below as `trivialization F proj`) if the total space has not been given a topology, but we have a topology on both the fiber and the base space. Through the construction `topological_fiber_prebundle F proj` it will be possible to promote a `pretrivialization F proj` to a `trivialization F proj`. -/ @[nolint has_inhabited_instance] structure topological_fiber_bundle.pretrivialization (proj : Z → B) extends local_equiv Z (B × F) := (open_target : is_open target) (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = base_set ×ˢ (univ : set F)) (proj_to_fun : ∀ p ∈ source, (to_fun p).1 = proj p) open topological_fiber_bundle namespace topological_fiber_bundle.pretrivialization instance : has_coe_to_fun (pretrivialization F proj) (λ _, Z → (B × F)) := ⟨λ e, e.to_fun⟩ variables {F} (e : pretrivialization F proj) {x : Z} @[simp, mfld_simps] lemma coe_coe : ⇑e.to_local_equiv = e := rfl @[simp, mfld_simps] lemma coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_to_fun x ex lemma mem_source : x ∈ e.source ↔ proj x ∈ e.base_set := by rw [e.source_eq, mem_preimage] lemma coe_fst' (ex : proj x ∈ e.base_set) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) protected lemma eq_on : eq_on (prod.fst ∘ e) proj e.source := λ x hx, e.coe_fst hx lemma mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst ex).symm rfl lemma mk_proj_snd' (ex : proj x ∈ e.base_set) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst' ex).symm rfl /-- Composition of inverse and coercion from the subtype of the target. -/ def set_symm : e.target → Z := e.target.restrict e.to_local_equiv.symm lemma mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.base_set := by rw [e.target_eq, prod_univ, mem_preimage] lemma proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.to_local_equiv.symm x) = x.1 := begin have := (e.coe_fst (e.to_local_equiv.map_target hx)).symm, rwa [← e.coe_coe, e.to_local_equiv.right_inv hx] at this end lemma proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : proj (e.to_local_equiv.symm (b, x)) = b := e.proj_symm_apply (e.mem_target.2 hx) lemma proj_surj_on_base_set [nonempty F] : set.surj_on proj e.source e.base_set := λ b hb, let ⟨y⟩ := ‹nonempty F› in ⟨e.to_local_equiv.symm (b, y), e.to_local_equiv.map_target $ e.mem_target.2 hb, e.proj_symm_apply' hb⟩ lemma apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.to_local_equiv.symm x) = x := e.to_local_equiv.right_inv hx lemma apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : e (e.to_local_equiv.symm (b, x)) = (b, x) := e.apply_symm_apply (e.mem_target.2 hx) @[simp, mfld_simps] lemma symm_apply_mk_proj {x : Z} (ex : x ∈ e.source) : e.to_local_equiv.symm (proj x, (e x).2) = x := by rw [← e.coe_fst ex, prod.mk.eta, ← e.coe_coe, e.to_local_equiv.left_inv ex] @[simp, mfld_simps] lemma preimage_symm_proj_base_set : (e.to_local_equiv.symm ⁻¹' (proj ⁻¹' e.base_set)) ∩ e.target = e.target := begin refine inter_eq_right_iff_subset.mpr (λ x hx, _), simp only [mem_preimage, local_equiv.inv_fun_as_coe, e.proj_symm_apply hx], exact e.mem_target.mp hx, end @[simp, mfld_simps] lemma preimage_symm_proj_inter (s : set B) : (e.to_local_equiv.symm ⁻¹' (proj ⁻¹' s)) ∩ e.base_set ×ˢ (univ : set F) = (s ∩ e.base_set) ×ˢ (univ : set F) := begin ext ⟨x, y⟩, suffices : x ∈ e.base_set → (proj (e.to_local_equiv.symm (x, y)) ∈ s ↔ x ∈ s), by simpa only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ, and.congr_left_iff], intro h, rw [e.proj_symm_apply' h] end lemma symm_trans_symm (e e' : pretrivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).symm = e'.to_local_equiv.symm.trans e.to_local_equiv := by rw [local_equiv.trans_symm_eq_symm_trans_symm,local_equiv.symm_symm] lemma symm_trans_source_eq (e e' : pretrivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).source = (e.base_set ∩ e'.base_set) ×ˢ (univ : set F) := by rw [local_equiv.trans_source, e'.source_eq, local_equiv.symm_source, e.target_eq, inter_comm, e.preimage_symm_proj_inter, inter_comm] lemma symm_trans_target_eq (e e' : pretrivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).target = (e.base_set ∩ e'.base_set) ×ˢ (univ : set F) := by rw [← local_equiv.symm_source, symm_trans_symm, symm_trans_source_eq, inter_comm] end topological_fiber_bundle.pretrivialization variable [topological_space Z] /-- A structure extending local homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a local homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' base_set` and `base_set × F`, acting trivially on the first coordinate. -/ @[nolint has_inhabited_instance] structure topological_fiber_bundle.trivialization (proj : Z → B) extends local_homeomorph Z (B × F) := (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = base_set ×ˢ (univ : set F)) (proj_to_fun : ∀ p ∈ source, (to_local_homeomorph p).1 = proj p) open topological_fiber_bundle namespace topological_fiber_bundle.trivialization variables {F} (e : trivialization F proj) {x : Z} /-- Natural identification as a `pretrivialization`. -/ def to_pretrivialization : topological_fiber_bundle.pretrivialization F proj := { ..e } instance : has_coe_to_fun (trivialization F proj) (λ _, Z → B × F) := ⟨λ e, e.to_fun⟩ instance : has_coe (trivialization F proj) (pretrivialization F proj) := ⟨to_pretrivialization⟩ @[simp, mfld_simps] lemma coe_coe : ⇑e.to_local_homeomorph = e := rfl @[simp, mfld_simps] lemma coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_to_fun x ex protected lemma eq_on : eq_on (prod.fst ∘ e) proj e.source := λ x hx, e.coe_fst hx lemma mem_source : x ∈ e.source ↔ proj x ∈ e.base_set := by rw [e.source_eq, mem_preimage] lemma coe_fst' (ex : proj x ∈ e.base_set) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) lemma mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst ex).symm rfl lemma mk_proj_snd' (ex : proj x ∈ e.base_set) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst' ex).symm rfl lemma source_inter_preimage_target_inter (s : set (B × F)) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := e.to_local_homeomorph.source_inter_preimage_target_inter s @[simp, mfld_simps] lemma coe_mk (e : local_homeomorph Z (B × F)) (i j k l m) (x : Z) : (trivialization.mk e i j k l m : trivialization F proj) x = e x := rfl lemma mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.base_set := e.to_pretrivialization.mem_target lemma map_target {x : B × F} (hx : x ∈ e.target) : e.to_local_homeomorph.symm x ∈ e.source := e.to_local_homeomorph.map_target hx lemma proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.to_local_homeomorph.symm x) = x.1 := e.to_pretrivialization.proj_symm_apply hx lemma proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : proj (e.to_local_homeomorph.symm (b, x)) = b := e.to_pretrivialization.proj_symm_apply' hx lemma proj_surj_on_base_set [nonempty F] : set.surj_on proj e.source e.base_set := e.to_pretrivialization.proj_surj_on_base_set lemma apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.to_local_homeomorph.symm x) = x := e.to_local_homeomorph.right_inv hx lemma apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : e (e.to_local_homeomorph.symm (b, x)) = (b, x) := e.to_pretrivialization.apply_symm_apply' hx @[simp, mfld_simps] lemma symm_apply_mk_proj (ex : x ∈ e.source) : e.to_local_homeomorph.symm (proj x, (e x).2) = x := e.to_pretrivialization.symm_apply_mk_proj ex lemma symm_trans_source_eq (e e' : trivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).source = (e.base_set ∩ e'.base_set) ×ˢ (univ : set F) := pretrivialization.symm_trans_source_eq e.to_pretrivialization e' lemma symm_trans_target_eq (e e' : trivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).target = (e.base_set ∩ e'.base_set) ×ˢ (univ : set F) := pretrivialization.symm_trans_target_eq e.to_pretrivialization e' lemma coe_fst_eventually_eq_proj (ex : x ∈ e.source) : prod.fst ∘ e =ᶠ[𝓝 x] proj := mem_nhds_iff.2 ⟨e.source, λ y hy, e.coe_fst hy, e.open_source, ex⟩ lemma coe_fst_eventually_eq_proj' (ex : proj x ∈ e.base_set) : prod.fst ∘ e =ᶠ[𝓝 x] proj := e.coe_fst_eventually_eq_proj (e.mem_source.2 ex) lemma map_proj_nhds (ex : x ∈ e.source) : map proj (𝓝 x) = 𝓝 (proj x) := by rw [← e.coe_fst ex, ← map_congr (e.coe_fst_eventually_eq_proj ex), ← map_map, ← e.coe_coe, e.to_local_homeomorph.map_nhds_eq ex, map_fst_nhds] /-- In the domain of a bundle trivialization, the projection is continuous-/ lemma continuous_at_proj (ex : x ∈ e.source) : continuous_at proj x := (e.map_proj_nhds ex).le /-- Composition of a `trivialization` and a `homeomorph`. -/ def comp_homeomorph {Z' : Type*} [topological_space Z'] (h : Z' ≃ₜ Z) : trivialization F (proj ∘ h) := { to_local_homeomorph := h.to_local_homeomorph.trans e.to_local_homeomorph, base_set := e.base_set, open_base_set := e.open_base_set, source_eq := by simp [e.source_eq, preimage_preimage], target_eq := by simp [e.target_eq], proj_to_fun := λ p hp, have hp : h p ∈ e.source, by simpa using hp, by simp [hp] } end topological_fiber_bundle.trivialization /-- A topological fiber bundle with fiber `F` over a base `B` is a space projecting on `B` for which the fibers are all homeomorphic to `F`, such that the local situation around each point is a direct product. -/ def is_topological_fiber_bundle (proj : Z → B) : Prop := ∀ x : B, ∃e : trivialization F proj, x ∈ e.base_set /-- A trivial topological fiber bundle with fiber `F` over a base `B` is a space `Z` projecting on `B` for which there exists a homeomorphism to `B × F` that sends `proj` to `prod.fst`. -/ def is_trivial_topological_fiber_bundle (proj : Z → B) : Prop := ∃ e : Z ≃ₜ (B × F), ∀ x, (e x).1 = proj x variables {F} lemma is_trivial_topological_fiber_bundle.is_topological_fiber_bundle (h : is_trivial_topological_fiber_bundle F proj) : is_topological_fiber_bundle F proj := let ⟨e, he⟩ := h in λ x, ⟨⟨e.to_local_homeomorph, univ, is_open_univ, rfl, univ_prod_univ.symm, λ x _, he x⟩, mem_univ x⟩ lemma is_topological_fiber_bundle.map_proj_nhds (h : is_topological_fiber_bundle F proj) (x : Z) : map proj (𝓝 x) = 𝓝 (proj x) := let ⟨e, ex⟩ := h (proj x) in e.map_proj_nhds $ e.mem_source.2 ex /-- The projection from a topological fiber bundle to its base is continuous. -/ lemma is_topological_fiber_bundle.continuous_proj (h : is_topological_fiber_bundle F proj) : continuous proj := continuous_iff_continuous_at.2 $ λ x, (h.map_proj_nhds _).le /-- The projection from a topological fiber bundle to its base is an open map. -/ lemma is_topological_fiber_bundle.is_open_map_proj (h : is_topological_fiber_bundle F proj) : is_open_map proj := is_open_map.of_nhds_le $ λ x, (h.map_proj_nhds x).ge /-- The projection from a topological fiber bundle with a nonempty fiber to its base is a surjective map. -/ lemma is_topological_fiber_bundle.surjective_proj [nonempty F] (h : is_topological_fiber_bundle F proj) : function.surjective proj := λ b, let ⟨e, eb⟩ := h b, ⟨x, _, hx⟩ := e.proj_surj_on_base_set eb in ⟨x, hx⟩ /-- The projection from a topological fiber bundle with a nonempty fiber to its base is a quotient map. -/ lemma is_topological_fiber_bundle.quotient_map_proj [nonempty F] (h : is_topological_fiber_bundle F proj) : quotient_map proj := h.is_open_map_proj.to_quotient_map h.continuous_proj h.surjective_proj /-- The first projection in a product is a trivial topological fiber bundle. -/ lemma is_trivial_topological_fiber_bundle_fst : is_trivial_topological_fiber_bundle F (prod.fst : B × F → B) := ⟨homeomorph.refl _, λ x, rfl⟩ /-- The first projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_fst : is_topological_fiber_bundle F (prod.fst : B × F → B) := is_trivial_topological_fiber_bundle_fst.is_topological_fiber_bundle /-- The second projection in a product is a trivial topological fiber bundle. -/ lemma is_trivial_topological_fiber_bundle_snd : is_trivial_topological_fiber_bundle F (prod.snd : F × B → B) := ⟨homeomorph.prod_comm _ _, λ x, rfl⟩ /-- The second projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_snd : is_topological_fiber_bundle F (prod.snd : F × B → B) := is_trivial_topological_fiber_bundle_snd.is_topological_fiber_bundle lemma is_topological_fiber_bundle.comp_homeomorph {Z' : Type*} [topological_space Z'] (e : is_topological_fiber_bundle F proj) (h : Z' ≃ₜ Z) : is_topological_fiber_bundle F (proj ∘ h) := λ x, let ⟨e, he⟩ := e x in ⟨e.comp_homeomorph h, by simpa [topological_fiber_bundle.trivialization.comp_homeomorph] using he⟩ namespace topological_fiber_bundle.trivialization /-- If `e` is a `trivialization` of `proj : Z → B` with fiber `F` and `h` is a homeomorphism `F ≃ₜ F'`, then `e.trans_fiber_homeomorph h` is the trivialization of `proj` with the fiber `F'` that sends `p : Z` to `((e p).1, h (e p).2)`. -/ def trans_fiber_homeomorph {F' : Type*} [topological_space F'] (e : trivialization F proj) (h : F ≃ₜ F') : trivialization F' proj := { to_local_homeomorph := e.to_local_homeomorph.trans ((homeomorph.refl _).prod_congr h).to_local_homeomorph, base_set := e.base_set, open_base_set := e.open_base_set, source_eq := by simp [e.source_eq], target_eq := by { ext, simp [e.target_eq] }, proj_to_fun := λ p hp, have p ∈ e.source, by simpa using hp, by simp [this] } @[simp] lemma trans_fiber_homeomorph_apply {F' : Type*} [topological_space F'] (e : trivialization F proj) (h : F ≃ₜ F') (x : Z) : e.trans_fiber_homeomorph h x = ((e x).1, h (e x).2) := rfl /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations. See also `trivialization.coord_change_homeomorph` for a version bundled as `F ≃ₜ F`. -/ def coord_change (e₁ e₂ : trivialization F proj) (b : B) (x : F) : F := (e₂ $ e₁.to_local_homeomorph.symm (b, x)).2 lemma mk_coord_change (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) (x : F) : (b, e₁.coord_change e₂ b x) = e₂ (e₁.to_local_homeomorph.symm (b, x)) := begin refine prod.ext _ rfl, rw [e₂.coe_fst', ← e₁.coe_fst', e₁.apply_symm_apply' h₁], { rwa [e₁.proj_symm_apply' h₁] }, { rwa [e₁.proj_symm_apply' h₁] } end lemma coord_change_apply_snd (e₁ e₂ : trivialization F proj) {p : Z} (h : proj p ∈ e₁.base_set) : e₁.coord_change e₂ (proj p) (e₁ p).snd = (e₂ p).snd := by rw [coord_change, e₁.symm_apply_mk_proj (e₁.mem_source.2 h)] lemma coord_change_same_apply (e : trivialization F proj) {b : B} (h : b ∈ e.base_set) (x : F) : e.coord_change e b x = x := by rw [coord_change, e.apply_symm_apply' h] lemma coord_change_same (e : trivialization F proj) {b : B} (h : b ∈ e.base_set) : e.coord_change e b = id := funext $ e.coord_change_same_apply h lemma coord_change_coord_change (e₁ e₂ e₃ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) (x : F) : e₂.coord_change e₃ b (e₁.coord_change e₂ b x) = e₁.coord_change e₃ b x := begin rw [coord_change, e₁.mk_coord_change _ h₁ h₂, ← e₂.coe_coe, e₂.to_local_homeomorph.left_inv, coord_change], rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] end lemma continuous_coord_change (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : continuous (e₁.coord_change e₂ b) := begin refine continuous_snd.comp (e₂.to_local_homeomorph.continuous_on.comp_continuous (e₁.to_local_homeomorph.continuous_on_symm.comp_continuous _ _) _), { exact continuous_const.prod_mk continuous_id }, { exact λ x, e₁.mem_target.2 h₁ }, { intro x, rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] } end /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations, as a homeomorphism. -/ def coord_change_homeomorph (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : F ≃ₜ F := { to_fun := e₁.coord_change e₂ b, inv_fun := e₂.coord_change e₁ b, left_inv := λ x, by simp only [*, coord_change_coord_change, coord_change_same_apply], right_inv := λ x, by simp only [*, coord_change_coord_change, coord_change_same_apply], continuous_to_fun := e₁.continuous_coord_change e₂ h₁ h₂, continuous_inv_fun := e₂.continuous_coord_change e₁ h₂ h₁ } @[simp] lemma coord_change_homeomorph_coe (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : ⇑(e₁.coord_change_homeomorph e₂ h₁ h₂) = e₁.coord_change e₂ b := rfl end topological_fiber_bundle.trivialization section comap open_locale classical variables {B' : Type*} [topological_space B'] /-- Given a bundle trivialization of `proj : Z → B` and a continuous map `f : B' → B`, construct a bundle trivialization of `φ : {p : B' × Z | f p.1 = proj p.2} → B'` given by `φ x = (x : B' × Z).1`. -/ noncomputable def topological_fiber_bundle.trivialization.comap (e : trivialization F proj) (f : B' → B) (hf : continuous f) (b' : B') (hb' : f b' ∈ e.base_set) : trivialization F (λ x : {p : B' × Z | f p.1 = proj p.2}, (x : B' × Z).1) := { to_fun := λ p, ((p : B' × Z).1, (e (p : B' × Z).2).2), inv_fun := λ p, if h : f p.1 ∈ e.base_set then ⟨⟨p.1, e.to_local_homeomorph.symm (f p.1, p.2)⟩, by simp [e.proj_symm_apply' h]⟩ else ⟨⟨b', e.to_local_homeomorph.symm (f b', p.2)⟩, by simp [e.proj_symm_apply' hb']⟩, source := {p | f (p : B' × Z).1 ∈ e.base_set}, target := {p | f p.1 ∈ e.base_set}, map_source' := λ p hp, hp, map_target' := λ p (hp : f p.1 ∈ e.base_set), by simp [hp], left_inv' := begin rintro ⟨⟨b, x⟩, hbx⟩ hb, dsimp at *, have hx : x ∈ e.source, from e.mem_source.2 (hbx ▸ hb), ext; simp * end, right_inv' := λ p (hp : f p.1 ∈ e.base_set), by simp [*, e.apply_symm_apply'], open_source := e.open_base_set.preimage (hf.comp $ continuous_fst.comp continuous_subtype_coe), open_target := e.open_base_set.preimage (hf.comp continuous_fst), continuous_to_fun := ((continuous_fst.comp continuous_subtype_coe).continuous_on).prod $ continuous_snd.comp_continuous_on $ e.continuous_to_fun.comp (continuous_snd.comp continuous_subtype_coe).continuous_on $ by { rintro ⟨⟨b, x⟩, (hbx : f b = proj x)⟩ (hb : f b ∈ e.base_set), rw hbx at hb, exact e.mem_source.2 hb }, continuous_inv_fun := begin rw [embedding_subtype_coe.continuous_on_iff], suffices : continuous_on (λ p : B' × F, (p.1, e.to_local_homeomorph.symm (f p.1, p.2))) {p : B' × F | f p.1 ∈ e.base_set}, { refine this.congr (λ p (hp : f p.1 ∈ e.base_set), _), simp [hp] }, { refine continuous_on_fst.prod (e.to_local_homeomorph.symm.continuous_on.comp _ _), { exact ((hf.comp continuous_fst).prod_mk continuous_snd).continuous_on }, { exact λ p hp, e.mem_target.2 hp } } end, base_set := f ⁻¹' e.base_set, source_eq := rfl, target_eq := by { ext, simp }, open_base_set := e.open_base_set.preimage hf, proj_to_fun := λ _ _, rfl } /-- If `proj : Z → B` is a topological fiber bundle with fiber `F` and `f : B' → B` is a continuous map, then the pullback bundle (a.k.a. induced bundle) is the topological bundle with the total space `{(x, y) : B' × Z | f x = proj y}` given by `λ ⟨(x, y), h⟩, x`. -/ lemma is_topological_fiber_bundle.comap (h : is_topological_fiber_bundle F proj) {f : B' → B} (hf : continuous f) : is_topological_fiber_bundle F (λ x : {p : B' × Z | f p.1 = proj p.2}, (x : B' × Z).1) := λ x, let ⟨e, he⟩ := h (f x) in ⟨e.comap f hf x he, he⟩ end comap namespace topological_fiber_bundle.trivialization lemma is_image_preimage_prod (e : trivialization F proj) (s : set B) : e.to_local_homeomorph.is_image (proj ⁻¹' s) (s ×ˢ (univ : set F)) := λ x hx, by simp [e.coe_fst', hx] /-- Restrict a `trivialization` to an open set in the base. `-/ def restr_open (e : trivialization F proj) (s : set B) (hs : is_open s) : trivialization F proj := { to_local_homeomorph := ((e.is_image_preimage_prod s).symm.restr (is_open.inter e.open_target (hs.prod is_open_univ))).symm, base_set := e.base_set ∩ s, open_base_set := is_open.inter e.open_base_set hs, source_eq := by simp [e.source_eq], target_eq := by simp [e.target_eq, prod_univ], proj_to_fun := λ p hp, e.proj_to_fun p hp.1 } section piecewise lemma frontier_preimage (e : trivialization F proj) (s : set B) : e.source ∩ frontier (proj ⁻¹' s) = proj ⁻¹' (e.base_set ∩ frontier s) := by rw [← (e.is_image_preimage_prod s).frontier.preimage_eq, frontier_prod_univ_eq, (e.is_image_preimage_prod _).preimage_eq, e.source_eq, preimage_inter] /-- Given two bundle trivializations `e`, `e'` of `proj : Z → B` and a set `s : set B` such that the base sets of `e` and `e'` intersect `frontier s` on the same set and `e p = e' p` whenever `proj p ∈ e.base_set ∩ frontier s`, `e.piecewise e' s Hs Heq` is the bundle trivialization over `set.ite s e.base_set e'.base_set` that is equal to `e` on `proj ⁻¹ s` and is equal to `e'` otherwise. -/ noncomputable def piecewise (e e' : trivialization F proj) (s : set B) (Hs : e.base_set ∩ frontier s = e'.base_set ∩ frontier s) (Heq : eq_on e e' $ proj ⁻¹' (e.base_set ∩ frontier s)) : trivialization F proj := { to_local_homeomorph := e.to_local_homeomorph.piecewise e'.to_local_homeomorph (proj ⁻¹' s) (s ×ˢ (univ : set F)) (e.is_image_preimage_prod s) (e'.is_image_preimage_prod s) (by rw [e.frontier_preimage, e'.frontier_preimage, Hs]) (by rwa e.frontier_preimage), base_set := s.ite e.base_set e'.base_set, open_base_set := e.open_base_set.ite e'.open_base_set Hs, source_eq := by simp [e.source_eq, e'.source_eq], target_eq := by simp [e.target_eq, e'.target_eq, prod_univ], proj_to_fun := by rintro p (⟨he, hs⟩|⟨he, hs⟩); simp * } /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.base_set ∩ e'.base_set` such that `e` equals `e'` on `proj ⁻¹' {a}`, `e.piecewise_le_of_eq e' a He He' Heq` is the bundle trivialization over `set.ite (Iic a) e.base_set e'.base_set` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `e'` otherwise. -/ noncomputable def piecewise_le_of_eq [linear_order B] [order_topology B] (e e' : trivialization F proj) (a : B) (He : a ∈ e.base_set) (He' : a ∈ e'.base_set) (Heq : ∀ p, proj p = a → e p = e' p) : trivialization F proj := e.piecewise e' (Iic a) (set.ext $ λ x, and.congr_left_iff.2 $ λ hx, by simp [He, He', mem_singleton_iff.1 (frontier_Iic_subset _ hx)]) (λ p hp, Heq p $ frontier_Iic_subset _ hp.2) /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.base_set ∩ e'.base_set`, `e.piecewise_le e' a He He'` is the bundle trivialization over `set.ite (Iic a) e.base_set e'.base_set` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `((e' p).1, h (e' p).2)` otherwise, where `h = `e'.coord_change_homeomorph e _ _` is the homeomorphism of the fiber such that `h (e' p).2 = (e p).2` whenever `e p = a`. -/ noncomputable def piecewise_le [linear_order B] [order_topology B] (e e' : trivialization F proj) (a : B) (He : a ∈ e.base_set) (He' : a ∈ e'.base_set) : trivialization F proj := e.piecewise_le_of_eq (e'.trans_fiber_homeomorph (e'.coord_change_homeomorph e He' He)) a He He' $ by { unfreezingI {rintro p rfl }, ext1, { simp [e.coe_fst', e'.coe_fst', *] }, { simp [e'.coord_change_apply_snd, *] } } /-- Given two bundle trivializations `e`, `e'` over disjoint sets, `e.disjoint_union e' H` is the bundle trivialization over the union of the base sets that agrees with `e` and `e'` over their base sets. -/ noncomputable def disjoint_union (e e' : trivialization F proj) (H : disjoint e.base_set e'.base_set) : trivialization F proj := { to_local_homeomorph := e.to_local_homeomorph.disjoint_union e'.to_local_homeomorph (λ x hx, by { rw [e.source_eq, e'.source_eq] at hx, exact H hx }) (λ x hx, by { rw [e.target_eq, e'.target_eq] at hx, exact H ⟨hx.1.1, hx.2.1⟩ }), base_set := e.base_set ∪ e'.base_set, open_base_set := is_open.union e.open_base_set e'.open_base_set, source_eq := congr_arg2 (∪) e.source_eq e'.source_eq, target_eq := (congr_arg2 (∪) e.target_eq e'.target_eq).trans union_prod.symm, proj_to_fun := begin rintro p (hp|hp'), { show (e.source.piecewise e e' p).1 = proj p, rw [piecewise_eq_of_mem, e.coe_fst]; exact hp }, { show (e.source.piecewise e e' p).1 = proj p, rw [piecewise_eq_of_not_mem, e'.coe_fst hp'], simp only [e.source_eq, e'.source_eq] at hp' ⊢, exact λ h, H ⟨h, hp'⟩ } end } /-- If `h` is a topological fiber bundle over a conditionally complete linear order, then it is trivial over any closed interval. -/ lemma _root_.is_topological_fiber_bundle.exists_trivialization_Icc_subset [conditionally_complete_linear_order B] [order_topology B] (h : is_topological_fiber_bundle F proj) (a b : B) : ∃ e : trivialization F proj, Icc a b ⊆ e.base_set := begin classical, obtain ⟨ea, hea⟩ : ∃ ea : trivialization F proj, a ∈ ea.base_set := h a, -- If `a < b`, then `[a, b] = ∅`, and the statement is trivial cases le_or_lt a b with hab hab; [skip, exact ⟨ea, by simp *⟩], /- Let `s` be the set of points `x ∈ [a, b]` such that `proj` is trivializable over `[a, x]`. We need to show that `b ∈ s`. Let `c = Sup s`. We will show that `c ∈ s` and `c = b`. -/ set s : set B := {x ∈ Icc a b | ∃ e : trivialization F proj, Icc a x ⊆ e.base_set}, have ha : a ∈ s, from ⟨left_mem_Icc.2 hab, ea, by simp [hea]⟩, have sne : s.nonempty := ⟨a, ha⟩, have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2, have sbd : bdd_above s := ⟨b, hsb⟩, set c := Sup s, have hsc : is_lub s c, from is_lub_cSup sne sbd, have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩, obtain ⟨-, ec : trivialization F proj, hec : Icc a c ⊆ ec.base_set⟩ : c ∈ s, { cases hc.1.eq_or_lt with heq hlt, { rwa ← heq }, refine ⟨hc, _⟩, /- In order to show that `c ∈ s`, consider a trivialization `ec` of `proj` over a neighborhood of `c`. Its base set includes `(c', c]` for some `c' ∈ [a, c)`. -/ rcases h c with ⟨ec, hc⟩, obtain ⟨c', hc', hc'e⟩ : ∃ c' ∈ Ico a c, Ioc c' c ⊆ ec.base_set := (mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset hlt).1 (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds ec.open_base_set hc), /- Since `c' < c = Sup s`, there exists `d ∈ s ∩ (c', c]`. Let `ead` be a trivialization of `proj` over `[a, d]`. Then we can glue `ead` and `ec` into a trivialization over `[a, c]`. -/ obtain ⟨d, ⟨hdab, ead, had⟩, hd⟩ : ∃ d ∈ s, d ∈ Ioc c' c := hsc.exists_between hc'.2, refine ⟨ead.piecewise_le ec d (had ⟨hdab.1, le_rfl⟩) (hc'e hd), subset_ite.2 _⟩, refine ⟨λ x hx, had ⟨hx.1.1, hx.2⟩, λ x hx, hc'e ⟨hd.1.trans (not_le.1 hx.2), hx.1.2⟩⟩ }, /- So, `c ∈ s`. Let `ec` be a trivialization of `proj` over `[a, c]`. If `c = b`, then we are done. Otherwise we show that `proj` can be trivialized over a larger interval `[a, d]`, `d ∈ (c, b]`, hence `c` is not an upper bound of `s`. -/ cases hc.2.eq_or_lt with heq hlt, { exact ⟨ec, heq ▸ hec⟩ }, suffices : ∃ (d ∈ Ioc c b) (e : trivialization F proj), Icc a d ⊆ e.base_set, { rcases this with ⟨d, hdcb, hd⟩, exact ((hsc.1 ⟨⟨hc.1.trans hdcb.1.le, hdcb.2⟩, hd⟩).not_lt hdcb.1).elim }, /- Since the base set of `ec` is open, it includes `[c, d)` (hence, `[a, d)`) for some `d ∈ (c, b]`. -/ obtain ⟨d, hdcb, hd⟩ : ∃ d ∈ Ioc c b, Ico c d ⊆ ec.base_set := (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds ec.open_base_set (hec ⟨hc.1, le_rfl⟩)), have had : Ico a d ⊆ ec.base_set, from subset.trans Ico_subset_Icc_union_Ico (union_subset hec hd), by_cases he : disjoint (Iio d) (Ioi c), { /- If `(c, d) = ∅`, then let `ed` be a trivialization of `proj` over a neighborhood of `d`. Then the disjoint union of `ec` restricted to `(-∞, d)` and `ed` restricted to `(c, ∞)` is a trivialization over `[a, d]`. -/ rcases h d with ⟨ed, hed⟩, refine ⟨d, hdcb, (ec.restr_open (Iio d) is_open_Iio).disjoint_union (ed.restr_open (Ioi c) is_open_Ioi) (he.mono (inter_subset_right _ _) (inter_subset_right _ _)), λ x hx, _⟩, rcases hx.2.eq_or_lt with rfl|hxd, exacts [or.inr ⟨hed, hdcb.1⟩, or.inl ⟨had ⟨hx.1, hxd⟩, hxd⟩] }, { /- If `(c, d)` is nonempty, then take `d' ∈ (c, d)`. Since the base set of `ec` includes `[a, d)`, it includes `[a, d'] ⊆ [a, d)` as well. -/ rw [disjoint_left] at he, push_neg at he, rcases he with ⟨d', hdd' : d' < d, hd'c⟩, exact ⟨d', ⟨hd'c, hdd'.le.trans hdcb.2⟩, ec, subset.trans (Icc_subset_Ico_right hdd') had⟩ } end end piecewise end topological_fiber_bundle.trivialization end topological_fiber_bundle /-! ### Constructing topological fiber bundles -/ namespace bundle variable (E : B → Type*) attribute [mfld_simps] proj total_space_mk coe_fst coe_snd_map_apply coe_snd_map_smul instance [I : topological_space F] : ∀ x : B, topological_space (trivial B F x) := λ x, I instance [t₁ : topological_space B] [t₂ : topological_space F] : topological_space (total_space (trivial B F)) := topological_space.induced (proj (trivial B F)) t₁ ⊓ topological_space.induced (trivial.proj_snd B F) t₂ end bundle /-- Core data defining a locally trivial topological bundle with fiber `F` over a topological space `B`. Note that "bundle" is used in its mathematical sense. This is the (computer science) bundled version, i.e., all the relevant data is contained in the following structure. A family of local trivializations is indexed by a type `ι`, on open subsets `base_set i` for each `i : ι`. Trivialization changes from `i` to `j` are given by continuous maps `coord_change i j` from `base_set i ∩ base_set j` to the set of homeomorphisms of `F`, but we express them as maps `B → F → F` and require continuity on `(base_set i ∩ base_set j) × F` to avoid the topology on the space of continuous maps on `F`. -/ @[nolint has_inhabited_instance] structure topological_fiber_bundle_core (ι : Type*) (B : Type*) [topological_space B] (F : Type*) [topological_space F] := (base_set : ι → set B) (is_open_base_set : ∀ i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀ x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → F → F) (coord_change_self : ∀ i, ∀ x ∈ base_set i, ∀ v, coord_change i i x v = v) (coord_change_continuous : ∀ i j, continuous_on (λp : B × F, coord_change i j p.1 p.2) (((base_set i) ∩ (base_set j)) ×ˢ (univ : set F))) (coord_change_comp : ∀ i j k, ∀ x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀ v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) namespace topological_fiber_bundle_core variables [topological_space B] [topological_space F] (Z : topological_fiber_bundle_core ι B F) include Z /-- The index set of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments has_inhabited_instance] def index := ι /-- The base space of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments, reducible] def base := B /-- The fiber of a topological fiber bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments has_inhabited_instance] def fiber (x : B) := F section fiber_instances local attribute [reducible] fiber instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by apply_instance end fiber_instances /-- The total space of the topological fiber bundle, as a convenience function for dot notation. It is by definition equal to `bundle.total_space Z.fiber`, a.k.a. `Σ x, Z.fiber x` but with a different name for typeclass inference. -/ @[nolint unused_arguments, reducible] def total_space := bundle.total_space Z.fiber /-- The projection from the total space of a topological fiber bundle core, on its base. -/ @[reducible, simp, mfld_simps] def proj : Z.total_space → B := bundle.proj Z.fiber /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := { source := (Z.base_set i ∩ Z.base_set j) ×ˢ (univ : set F), target := (Z.base_set i ∩ Z.base_set j) ×ˢ (univ : set F), to_fun := λp, ⟨p.1, Z.coord_change i j p.1 p.2⟩, inv_fun := λp, ⟨p.1, Z.coord_change j i p.1 p.2⟩, map_source' := λp hp, by simpa using hp, map_target' := λp hp, by simpa using hp, left_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.1 }, { simp [hx] } end, right_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.2 }, { simp [hx] }, end, open_source := (is_open.inter (Z.is_open_base_set i) (Z.is_open_base_set j)).prod is_open_univ, open_target := (is_open.inter (Z.is_open_base_set i) (Z.is_open_base_set j)).prod is_open_univ, continuous_to_fun := continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous i j), continuous_inv_fun := by simpa [inter_comm] using continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous j i) } @[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := by { erw [mem_prod], simp } /-- Associate to a trivialization index `i : ι` the corresponding trivialization, i.e., a bijection between `proj ⁻¹ (base_set i)` and `base_set i × F`. As the fiber above `x` is `F` but read in the chart with index `index_at x`, the trivialization in the fiber above x is by definition the coordinate change from i to `index_at x`, so it depends on `x`. The local trivialization will ultimately be a local homeomorphism. For now, we only introduce the local equiv version, denoted with a prime. In further developments, avoid this auxiliary version, and use `Z.local_triv` instead. -/ def local_triv_as_local_equiv (i : ι) : local_equiv Z.total_space (B × F) := { source := Z.proj ⁻¹' (Z.base_set i), target := Z.base_set i ×ˢ (univ : set F), inv_fun := λp, ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩, to_fun := λp, ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩, map_source' := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.prod_mk_mem_set_prod_eq] using hp, map_target' := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.mem_prod] using hp, left_inv' := begin rintros ⟨x, v⟩ hx, change x ∈ Z.base_set i at hx, dsimp only, rw [Z.coord_change_comp, Z.coord_change_self], { exact Z.mem_base_set_at _ }, { simp only [hx, mem_inter_eq, and_self, mem_base_set_at] } end, right_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx }, { simp only [hx, mem_inter_eq, and_self, mem_base_set_at] } end } variable (i : ι) lemma mem_local_triv_as_local_equiv_source (p : Z.total_space) : p ∈ (Z.local_triv_as_local_equiv i).source ↔ p.1 ∈ Z.base_set i := iff.rfl lemma mem_local_triv_as_local_equiv_target (p : B × F) : p ∈ (Z.local_triv_as_local_equiv i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp only [and_true, mem_univ] } lemma local_triv_as_local_equiv_apply (p : Z.total_space) : (Z.local_triv_as_local_equiv i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv_as_local_equiv_trans (i j : ι) : (Z.local_triv_as_local_equiv i).symm.trans (Z.local_triv_as_local_equiv j) ≈ (Z.triv_change i j).to_local_equiv := begin split, { ext x, simp only [mem_local_triv_as_local_equiv_target] with mfld_simps, refl, }, { rintros ⟨x, v⟩ hx, simp only [triv_change, local_triv_as_local_equiv, local_equiv.symm, true_and, prod.mk.inj_iff, prod_mk_mem_set_prod_eq, local_equiv.trans_source, mem_inter_eq, and_true, mem_preimage, proj, mem_univ, local_equiv.coe_mk, eq_self_iff_true, local_equiv.coe_trans, bundle.proj] at hx ⊢, simp only [Z.coord_change_comp, hx, mem_inter_eq, and_self, mem_base_set_at], } end variable (ι) /-- Topological structure on the total space of a topological bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space (bundle.total_space Z.fiber) := topological_space.generate_from $ ⋃ (i : ι) (s : set (B × F)) (s_open : is_open s), {(Z.local_triv_as_local_equiv i).source ∩ (Z.local_triv_as_local_equiv i) ⁻¹' s} variable {ι} lemma open_source' (i : ι) : is_open (Z.local_triv_as_local_equiv i).source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨i, Z.base_set i ×ˢ (univ : set F), (Z.is_open_base_set i).prod is_open_univ, _⟩, ext p, simp only [local_triv_as_local_equiv_apply, prod_mk_mem_set_prod_eq, mem_inter_eq, and_self, mem_local_triv_as_local_equiv_source, and_true, mem_univ, mem_preimage], end open topological_fiber_bundle /-- Extended version of the local trivialization of a fiber bundle constructed from core, registering additionally in its type that it is a local bundle trivialization. -/ def local_triv (i : ι) : trivialization F Z.proj := { base_set := Z.base_set i, open_base_set := Z.is_open_base_set i, source_eq := rfl, target_eq := rfl, proj_to_fun := λ p hp, by { simp only with mfld_simps, refl }, open_source := Z.open_source' i, open_target := (Z.is_open_base_set i).prod is_open_univ, continuous_to_fun := begin rw continuous_on_open_iff (Z.open_source' i), assume s s_open, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨i, s, s_open, rfl⟩ end, continuous_inv_fun := begin apply continuous_on_open_of_generate_from ((Z.is_open_base_set i).prod is_open_univ), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, obtain ⟨j, s, s_open, ts⟩ : ∃ j s, is_open s ∧ t = (local_triv_as_local_equiv Z j).source ∩ (local_triv_as_local_equiv Z j) ⁻¹' s := ht, rw ts, simp only [local_equiv.right_inv, preimage_inter, local_equiv.left_inv], let e := Z.local_triv_as_local_equiv i, let e' := Z.local_triv_as_local_equiv j, let f := e.symm.trans e', have : is_open (f.source ∩ f ⁻¹' s), { rw [(Z.local_triv_as_local_equiv_trans i j).source_inter_preimage_eq], exact (continuous_on_open_iff (Z.triv_change i j).open_source).1 ((Z.triv_change i j).continuous_on) _ s_open }, convert this using 1, dsimp [local_equiv.trans_source], rw [← preimage_comp, inter_assoc], refl, end, to_local_equiv := Z.local_triv_as_local_equiv i } /-- A topological fiber bundle constructed from core is indeed a topological fiber bundle. -/ protected theorem is_topological_fiber_bundle : is_topological_fiber_bundle F Z.proj := λx, ⟨Z.local_triv (Z.index_at x), Z.mem_base_set_at x⟩ /-- The projection on the base of a topological bundle created from core is continuous -/ lemma continuous_proj : continuous Z.proj := Z.is_topological_fiber_bundle.continuous_proj /-- The projection on the base of a topological bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := Z.is_topological_fiber_bundle.is_open_map_proj /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at (b : B) : trivialization F Z.proj := Z.local_triv (Z.index_at b) @[simp, mfld_simps] lemma local_triv_at_def (b : B) : Z.local_triv (Z.index_at b) = Z.local_triv_at b := rfl /-- If an element of `F` is invariant under all coordinate changes, then one can define a corresponding section of the fiber bundle, which is continuous. This applies in particular to the zero section of a vector bundle. Another example (not yet defined) would be the identity section of the endomorphism bundle of a vector bundle. -/ lemma continuous_const_section (v : F) (h : ∀ i j, ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j), Z.coord_change i j x v = v) : continuous (show B → Z.total_space, from λ x, ⟨x, v⟩) := begin apply continuous_iff_continuous_at.2 (λ x, _), have A : Z.base_set (Z.index_at x) ∈ 𝓝 x := is_open.mem_nhds (Z.is_open_base_set (Z.index_at x)) (Z.mem_base_set_at x), apply ((Z.local_triv_at x).to_local_homeomorph.continuous_at_iff_continuous_at_comp_left _).2, { simp only [(∘)] with mfld_simps, apply continuous_at_id.prod, have : continuous_on (λ (y : B), v) (Z.base_set (Z.index_at x)) := continuous_on_const, apply (this.congr _).continuous_at A, assume y hy, simp only [h, hy, mem_base_set_at] with mfld_simps }, { exact A } end @[simp, mfld_simps] lemma local_triv_as_local_equiv_coe : ⇑(Z.local_triv_as_local_equiv i) = Z.local_triv i := rfl @[simp, mfld_simps] lemma local_triv_as_local_equiv_source : (Z.local_triv_as_local_equiv i).source = (Z.local_triv i).source := rfl @[simp, mfld_simps] lemma local_triv_as_local_equiv_target : (Z.local_triv_as_local_equiv i).target = (Z.local_triv i).target := rfl @[simp, mfld_simps] lemma local_triv_as_local_equiv_symm : (Z.local_triv_as_local_equiv i).symm = (Z.local_triv i).to_local_equiv.symm := rfl @[simp, mfld_simps] lemma base_set_at : Z.base_set i = (Z.local_triv i).base_set := rfl @[simp, mfld_simps] lemma local_triv_apply (p : Z.total_space) : (Z.local_triv i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma mem_local_triv_source (p : Z.total_space) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ (Z.local_triv i).base_set := iff.rfl @[simp, mfld_simps] lemma mem_local_triv_target (p : B × F) : p ∈ (Z.local_triv i).target ↔ p.1 ∈ (Z.local_triv i).base_set := trivialization.mem_target _ @[simp, mfld_simps] lemma local_triv_symm_fst (p : B × F) : (Z.local_triv i).to_local_homeomorph.symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma local_triv_at_apply (b : B) (a : F) : ((Z.local_triv_at b) ⟨b, a⟩) = ⟨b, a⟩ := by { rw [local_triv_at, local_triv_apply, coord_change_self], exact Z.mem_base_set_at b } @[simp, mfld_simps] lemma mem_local_triv_at_base_set (b : B) : b ∈ (Z.local_triv_at b).base_set := by { rw [local_triv_at, ←base_set_at], exact Z.mem_base_set_at b, } open bundle /-- The inclusion of a fiber into the total space is a continuous map. -/ @[continuity] lemma continuous_total_space_mk (b : B) : continuous (λ a, total_space_mk Z.fiber b a) := begin rw [continuous_iff_le_induced, topological_fiber_bundle_core.to_topological_space], apply le_induced_generate_from, simp only [total_space_mk, mem_Union, mem_singleton_iff, local_triv_as_local_equiv_source, local_triv_as_local_equiv_coe], rintros s ⟨i, t, ht, rfl⟩, rw [←((Z.local_triv i).source_inter_preimage_target_inter t), preimage_inter, ←preimage_comp, trivialization.source_eq], apply is_open.inter, { simp only [bundle.proj, proj, ←preimage_comp], by_cases (b ∈ (Z.local_triv i).base_set), { rw preimage_const_of_mem h, exact is_open_univ, }, { rw preimage_const_of_not_mem h, exact is_open_empty, }}, { simp only [function.comp, local_triv_apply], rw [preimage_inter, preimage_comp], by_cases (b ∈ Z.base_set i), { have hc : continuous (λ (x : Z.fiber b), (Z.coord_change (Z.index_at b) i b) x), from (Z.coord_change_continuous (Z.index_at b) i).comp_continuous (continuous_const.prod_mk continuous_id) (λ x, ⟨⟨Z.mem_base_set_at b, h⟩, mem_univ x⟩), exact (((Z.local_triv i).open_target.inter ht).preimage (continuous.prod.mk b)).preimage hc }, { rw [(Z.local_triv i).target_eq, ←base_set_at, mk_preimage_prod_right_eq_empty h, preimage_empty, empty_inter], exact is_open_empty, }} end end topological_fiber_bundle_core variables (F) {Z : Type*} [topological_space B] [topological_space F] {proj : Z → B} open topological_fiber_bundle /-- This structure permits to define a fiber bundle when trivializations are given as local equivalences but there is not yet a topology on the total space. The total space is hence given a topology in such a way that there is a fiber bundle structure for which the local equivalences are also local homeomorphism and hence local trivializations. -/ @[nolint has_inhabited_instance] structure topological_fiber_prebundle (proj : Z → B) := (pretrivialization_atlas : set (pretrivialization F proj)) (pretrivialization_at : B → pretrivialization F proj) (mem_base_pretrivialization_at : ∀ x : B, x ∈ (pretrivialization_at x).base_set) (pretrivialization_mem_atlas : ∀ x : B, pretrivialization_at x ∈ pretrivialization_atlas) (continuous_triv_change : ∀ e e' ∈ pretrivialization_atlas, continuous_on (e ∘ e'.to_local_equiv.symm) (e'.target ∩ (e'.to_local_equiv.symm ⁻¹' e.source))) namespace topological_fiber_prebundle variables {F} (a : topological_fiber_prebundle F proj) {e : pretrivialization F proj} /-- Topology on the total space that will make the prebundle into a bundle. -/ def total_space_topology (a : topological_fiber_prebundle F proj) : topological_space Z := ⨆ (e : pretrivialization F proj) (he : e ∈ a.pretrivialization_atlas), coinduced e.set_symm (subtype.topological_space) lemma continuous_symm_of_mem_pretrivialization_atlas (he : e ∈ a.pretrivialization_atlas) : @continuous_on _ _ _ a.total_space_topology e.to_local_equiv.symm e.target := begin refine id (λ z H, id (λ U h, preimage_nhds_within_coinduced' H e.open_target (le_def.1 (nhds_mono _) U h))), exact le_supr₂ e he, end lemma is_open_source (e : pretrivialization F proj) : @is_open _ a.total_space_topology e.source := begin letI := a.total_space_topology, refine is_open_supr_iff.mpr (λ e', _), refine is_open_supr_iff.mpr (λ he', _), refine is_open_coinduced.mpr (is_open_induced_iff.mpr ⟨e.target, e.open_target, _⟩), rw [pretrivialization.set_symm, restrict, e.target_eq, e.source_eq, preimage_comp, subtype.preimage_coe_eq_preimage_coe_iff, e'.target_eq, prod_inter_prod, inter_univ, pretrivialization.preimage_symm_proj_inter], end lemma is_open_target_of_mem_pretrivialization_atlas_inter (e e' : pretrivialization F proj) (he' : e' ∈ a.pretrivialization_atlas) : is_open (e'.to_local_equiv.target ∩ e'.to_local_equiv.symm ⁻¹' e.source) := begin letI := a.total_space_topology, obtain ⟨u, hu1, hu2⟩ := continuous_on_iff'.mp (a.continuous_symm_of_mem_pretrivialization_atlas he') e.source (a.is_open_source e), rw [inter_comm, hu2], exact hu1.inter e'.open_target, end /-- Promotion from a `pretrivialization` to a `trivialization`. -/ def trivialization_of_mem_pretrivialization_atlas (he : e ∈ a.pretrivialization_atlas) : @trivialization B F Z _ _ a.total_space_topology proj := { open_source := a.is_open_source e, continuous_to_fun := begin letI := a.total_space_topology, refine continuous_on_iff'.mpr (λ s hs, ⟨e ⁻¹' s ∩ e.source, (is_open_supr_iff.mpr (λ e', _)), by { rw [inter_assoc, inter_self], refl }⟩), refine (is_open_supr_iff.mpr (λ he', _)), rw [is_open_coinduced, is_open_induced_iff], obtain ⟨u, hu1, hu2⟩ := continuous_on_iff'.mp (a.continuous_triv_change _ he _ he') s hs, have hu3 := congr_arg (λ s, (λ x : e'.target, (x : B × F)) ⁻¹' s) hu2, simp only [subtype.coe_preimage_self, preimage_inter, univ_inter] at hu3, refine ⟨u ∩ e'.to_local_equiv.target ∩ (e'.to_local_equiv.symm ⁻¹' e.source), _, by { simp only [preimage_inter, inter_univ, subtype.coe_preimage_self, hu3.symm], refl }⟩, rw inter_assoc, exact hu1.inter (a.is_open_target_of_mem_pretrivialization_atlas_inter e e' he'), end, continuous_inv_fun := a.continuous_symm_of_mem_pretrivialization_atlas he, .. e } lemma is_topological_fiber_bundle : @is_topological_fiber_bundle B F Z _ _ a.total_space_topology proj := λ x, ⟨a.trivialization_of_mem_pretrivialization_atlas (a.pretrivialization_mem_atlas x), a.mem_base_pretrivialization_at x ⟩ lemma continuous_proj : @continuous _ _ a.total_space_topology _ proj := by { letI := a.total_space_topology, exact a.is_topological_fiber_bundle.continuous_proj, } end topological_fiber_prebundle
c76a50d056a6b63698918751758d1b783f8daafd
ec62863c729b7eedee77b86d974f2c529fa79d25
/5/a.lean
6187889c3d445282d737b6e3b41d47563f161be1
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
382
lean
def value (s : String) : Nat := let cval (c : Char) : Nat := if c == 'B' || c == 'R' then 1 else 0 let rec v : List Char → Nat | [] => 0 | (c :: cs) => 2 * v cs + cval c v s.toList.reverse def solve (input : List String) : Nat := (input.map value).foldl Nat.max 0 def main : IO Unit := do let input ← IO.FS.lines "a.in" IO.print s!"{solve input.toList}\n"
72129b9a9b8ac3370ac1c69ecb74596ea76019ab
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/real/cau_seq_completion_auto.lean
5c67f945bd5f3b7fc24fd8a570dad5d65a04441c
[]
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
12,400
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis Generalizes the Cauchy completion of (ℚ, abs) to the completion of a commutative ring with absolute value. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.real.cau_seq import Mathlib.PostPort universes u_1 u_2 l namespace Mathlib namespace cau_seq.completion def Cauchy {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] := quotient cau_seq.equiv def mk {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : cau_seq β abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (f : cau_seq β abv) : quotient.mk f = mk f := rfl theorem mk_eq {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] {f : cau_seq β abv} {g : cau_seq β abv} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (x : β) : Cauchy := mk (const abv x) protected instance Cauchy.has_zero {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : HasZero Cauchy := { zero := of_rat 0 } protected instance Cauchy.has_one {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : HasOne Cauchy := { one := of_rat 1 } protected instance Cauchy.inhabited {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : Inhabited Cauchy := { default := 0 } theorem of_rat_zero {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : of_rat 0 = 0 := rfl theorem of_rat_one {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] {f : cau_seq β abv} : mk f = 0 ↔ lim_zero f := eq.mp (Eq._oldrec (Eq.refl (mk f = 0 ↔ lim_zero (f - 0))) (sub_zero f)) quotient.eq protected instance Cauchy.has_add {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : Add Cauchy := { add := fun (x y : Cauchy) => quotient.lift_on₂ x y (fun (f g : cau_seq β abv) => mk (f + g)) sorry } @[simp] theorem mk_add {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (f : cau_seq β abv) (g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl protected instance Cauchy.has_neg {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : Neg Cauchy := { neg := fun (x : Cauchy) => quotient.lift_on x (fun (f : cau_seq β abv) => mk (-f)) sorry } @[simp] theorem mk_neg {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (f : cau_seq β abv) : -mk f = mk (-f) := rfl protected instance Cauchy.has_mul {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : Mul Cauchy := { mul := fun (x y : Cauchy) => quotient.lift_on₂ x y (fun (f g : cau_seq β abv) => mk (f * g)) sorry } @[simp] theorem mk_mul {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (f : cau_seq β abv) (g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl protected instance Cauchy.has_sub {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : Sub Cauchy := { sub := fun (x y : Cauchy) => quotient.lift_on₂ x y (fun (f g : cau_seq β abv) => mk (f - g)) sorry } @[simp] theorem mk_sub {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (f : cau_seq β abv) (g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl theorem of_rat_add {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (x : β) (y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add x y) theorem of_rat_neg {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg x) theorem of_rat_mul {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (x : β) (y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul x y) protected instance Cauchy.comm_ring {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring Cauchy := comm_ring.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry theorem of_rat_sub {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [comm_ring β] {abv : β → α} [is_absolute_value abv] (x : β) (y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub x y) protected instance Cauchy.has_inv {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] : has_inv Cauchy := has_inv.mk fun (x : Cauchy) => quotient.lift_on x (fun (f : cau_seq β abv) => mk (dite (lim_zero f) (fun (h : lim_zero f) => 0) fun (h : ¬lim_zero f) => inv f h)) sorry @[simp] theorem inv_zero {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] : 0⁻¹ = 0 := sorry @[simp] theorem inv_mk {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] {f : cau_seq β abv} (hf : ¬lim_zero f) : mk f⁻¹ = mk (inv f hf) := sorry theorem cau_seq_zero_ne_one {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] : ¬0 ≈ 1 := sorry theorem zero_ne_one {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] : 0 ≠ 1 := fun (h : 0 = 1) => cau_seq_zero_ne_one (iff.mp mk_eq h) protected theorem inv_mul_cancel {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := sorry def field {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] : field Cauchy := field.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry has_inv.inv sorry sorry inv_zero theorem of_rat_inv {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] (x : β) : of_rat (x⁻¹) = (of_rat x⁻¹) := sorry theorem of_rat_div {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (y : β) : of_rat (x / y) = of_rat x / of_rat y := sorry end cau_seq.completion namespace cau_seq class is_complete {α : Type u_1} [linear_ordered_field α] (β : Type u_2) [ring β] (abv : β → α) [is_absolute_value abv] where is_complete : ∀ (s : cau_seq β abv), ∃ (b : β), s ≈ const abv b theorem complete {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (s : cau_seq β abv) : ∃ (b : β), s ≈ const abv b := is_complete.is_complete def lim {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (s : cau_seq β abv) : β := classical.some (complete s) theorem equiv_lim {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) theorem eq_lim_of_const_equiv {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] {f : cau_seq β abv} {x : β} (h : const abv x ≈ f) : x = lim f := iff.mp const_equiv (setoid.trans h (equiv_lim f)) theorem lim_eq_of_equiv_const {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] {f : cau_seq β abv} {x : β} (h : f ≈ const abv x) : lim f = x := Eq.symm (eq_lim_of_const_equiv (setoid.symm h)) theorem lim_eq_lim_of_equiv {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] {f : cau_seq β abv} {g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const (setoid.trans h (equiv_lim g)) @[simp] theorem lim_const {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const (setoid.refl (const abv x)) theorem lim_add {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (f : cau_seq β abv) (g : cau_seq β abv) : lim f + lim g = lim (f + g) := sorry theorem lim_mul_lim {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (f : cau_seq β abv) (g : cau_seq β abv) : lim f * lim g = lim (f * g) := sorry theorem lim_mul {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := eq.mpr (id (Eq._oldrec (Eq.refl (lim f * x = lim (f * const abv x))) (Eq.symm (lim_mul_lim f (const abv x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (lim f * x = lim f * lim (const abv x))) (lim_const x))) (Eq.refl (lim f * x))) theorem lim_neg {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (f : cau_seq β abv) : lim (-f) = -lim f := sorry theorem lim_eq_zero_iff {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [ring β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := sorry theorem lim_inv {α : Type u_1} [linear_ordered_field α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] {f : cau_seq β abv} (hf : ¬lim_zero f) : lim (inv f hf) = (lim f⁻¹) := sorry theorem lim_le {α : Type u_1} [linear_ordered_field α] [is_complete α abs] {f : cau_seq α abs} {x : α} (h : f ≤ const abs x) : lim f ≤ x := iff.mp const_le (le_of_eq_of_le (setoid.symm (equiv_lim f)) h) theorem le_lim {α : Type u_1} [linear_ordered_field α] [is_complete α abs] {f : cau_seq α abs} {x : α} (h : const abs x ≤ f) : x ≤ lim f := iff.mp const_le (le_of_le_of_eq h (equiv_lim f)) theorem lt_lim {α : Type u_1} [linear_ordered_field α] [is_complete α abs] {f : cau_seq α abs} {x : α} (h : const abs x < f) : x < lim f := iff.mp const_lt (lt_of_lt_of_eq h (equiv_lim f)) theorem lim_lt {α : Type u_1} [linear_ordered_field α] [is_complete α abs] {f : cau_seq α abs} {x : α} (h : f < const abs x) : lim f < x := iff.mp const_lt (lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h) end Mathlib
3c66c0906da28cc28e3127125647b057a9a1a0bc
32a2d1642d7519c99693bc1d3b24069e4853dd1f
/analysis/topology/topological_space.lean
2f648393623df97e349f81a4273fe48908685351
[ "Apache-2.0" ]
permissive
Cedric0099/mathlib
7edb81d5d68e280b4d21f6c0377dad1f9b8c0d71
a97101d2df5d186848075a2d0452f6a04d8a13eb
refs/heads/master
1,584,201,847,599
1,524,979,632,000
1,524,979,632,000
131,690,350
0
0
null
1,525,162,341,000
1,525,162,341,000
null
UTF-8
Lean
false
false
52,169
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of topological spaces. Parts of the formalization is based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.set.countable tactic open set filter lattice classical local attribute [instance] prop_decidable universes u v w structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} 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 variables [topological_space α] lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := have (⋃₀ {s₁, s₂}) = (s₁ ∪ s₂), by simp [union_comm], this ▸ is_open_sUnion $ show ∀(t : set α), t ∈ ({s₁, s₂} : set (set α)) → is_open t, by finish lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i @[simp] lemma is_open_empty : is_open (∅ : set α) := have is_open (⋃₀ ∅ : set α), from is_open_sUnion (assume a, false.elim), by simp at this; assumption lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (by simp) $ λ a s has hs ih h, begin suffices : is_open (a ∩ ⋂₀ s), { simpa }, exact is_open_inter (h _ $ mem_insert _ _) (ih $ assume t ht, h _ $ mem_insert_of_mem _ ht) end lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp [*]; exact is_open_univ end) (assume : ¬ p, begin simp [*]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set α) : Prop := is_open (-s) @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by simp [is_closed] @[simp] lemma is_closed_univ : is_closed (univ : set α) := by simp [is_closed] lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := by simp [is_closed]; exact is_open_inter lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simp [is_closed, compl_sInter]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i @[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s - t) := is_open_inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂ lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (by simp) (by simp [or_imp_distrib, is_closed_union, forall_and_distrib] {contextual := tt}) lemma is_closed_imp [topological_space α] {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ by finish, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp [interior, and_comm, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := interior_eq_of_open is_open_empty @[simp] lemma interior_univ : interior (univ : set α) = univ := interior_eq_of_open is_open_univ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := interior_eq_of_open is_open_interior @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ by simp [is_open_inter]) 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 simp [subset_interior_iff_subset_of_open, this, is_open_diff hu₁ h₁], have u - s ⊆ ∅, by rw [h₂] at this; assumption, 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 [subset_def, mem_interior] /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩ lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := closure_eq_of_is_closed is_closed_empty @[simp] lemma closure_univ : closure (univ : set α) = univ := closure_eq_of_is_closed is_closed_univ @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := closure_eq_of_is_closed is_closed_closure @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ by simp [is_closed_union]) (union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _)) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) := begin simp [interior, closure], rw [compl_sUnion, compl_image_set_of], simp [compl_subset_compl_iff_subset] end @[simp] lemma interior_compl_eq {s : set α} : interior (- s) = - closure s := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl_eq {s : set α} : closure (- s) = - interior s := by simp [closure_eq_compl_interior_compl] lemma closure_compl {s : set α} : closure (-s) = - interior s := subset.antisymm (by simp [closure_subset_iff_subset_of_is_closed, compl_subset_compl_iff_subset, subset.refl]) begin rw [←compl_subset_compl_iff_subset, compl_compl, subset_interior_iff_subset_of_open, ←compl_subset_compl_iff_subset, compl_compl], exact subset_closure, exact is_open_compl_iff.mpr is_closed_closure end lemma interior_compl {s : set α} : interior (-s) = - closure s := calc interior (- s) = - - interior (- s) : by simp ... = - closure (- (- s)) : by rw [closure_compl] ... = - closure s : by simp theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ := ⟨λ h o oo ao os, have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩ /-- 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, sdiff_eq] /-- neighbourhood filter -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s) lemma tendsto_nhds {m : β → α} {f : filter β} (h : ∀s, a ∈ s → is_open s → m ⁻¹' s ∈ f.sets) : tendsto m f (nhds a) := show map m f ≤ (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s), from le_infi $ assume s, le_infi $ assume ⟨ha, hs⟩, le_principal_iff.mpr $ h s ha hs lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) := tendsto_nhds $ assume s ha hs, univ_mem_sets' $ assume _, ha lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} := calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp⟩) ⟨univ, by simp⟩ ... = {s | ∃t⊆s, is_open t ∧ a ∈ t} : le_antisymm (supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩) (assume t ⟨i, hi₁, hi₂, hi₃⟩, by simp; exact ⟨i, ⟨hi₃, hi₂⟩, hi₁⟩) lemma map_nhds {a : α} {f : α → β} : map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) := calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) : map_binfi_eq (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp⟩) ⟨univ, by simp⟩ ... = _ : by simp lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t := by simp [nhds_sets] lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s := by simp [mem_nhds_sets_iff]; exact assume t ht _ hs, ht hs lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ (nhds a).sets := by simp [nhds_sets]; exact ⟨s, subset.refl _, hs, ha⟩ lemma return_le_nhds : return ≤ (nhds : α → filter α) := assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $ by simp [h₁] @[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ := assume : nhds a = ⊥, have return a = (⊥ : filter α), from lattice.bot_unique $ this ▸ return_le_nhds a, pure_neq_bot this lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} := set.ext $ by simp [mem_interior, nhds_sets] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ (nhds a).sets := by simp [interior_eq_nhds] lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s := calc is_open s ↔ interior s = s : by rw [interior_eq_iff_open] ... ↔ s ⊆ interior s : ⟨assume h, by simp [*, subset.refl], subset.antisymm interior_subset⟩ ... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ (nhds a).sets := by simpa using @is_open_iff_nhds α _ _ lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} := calc closure s = - interior (- s) : closure_eq_compl_interior_compl ... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl ... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr (inf_eq_bot_iff_le_compl (show principal s ⊔ principal (-s) = ⊤, by simp [principal_univ]) (by simp)).symm theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ (nhds a).sets, t ∩ s ≠ ∅ := mem_closure_iff.trans ⟨λ H t ht, subset_ne_empty (inter_subset_inter_right _ interior_subset) (H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)), λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩ lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s := calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed] ... ↔ closure s ⊆ s : ⟨assume h, by simp [*, subset.refl], assume h, subset.antisymm h subset_closure⟩ ... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ (nhds a).sets, from mem_nhds_sets h hs, have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by simp [this], have nhds a ⊓ principal (s ∩ t) ≠ ⊥, from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by simp ... = nhds a ⊓ principal t : by rw [←inf_assoc, this] ... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption, by rw [closure_eq_nhds]; assumption lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) := calc closure s \ closure t = (- closure t) ∩ closure s : by simp [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 [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b.sets) : a ∈ s := have b.map f ≤ nhds a ⊓ principal s, from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)), is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this lemma mem_closure_of_tendsto {f : β → α} {x : filter β} {a : α} {s : set α} (hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s := is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $ le_inf (le_trans (map_mono $ inf_le_left) hf) $ le_trans (map_mono $ inf_le_right_of_le $ by simp; exact subset.refl _) (@map_vmap_le _ _ _ f) /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t∈(nhds x).sets, finite {i | f i ∩ t ≠ ∅ } lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite_subset h $ by simp⟩ lemma locally_finite_subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, finite_subset ht₂ $ assume i hi, neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ -f i, from assume i hi, by simp at h; exact h i hi, have ∀i, - f i ∈ (nhds a).sets, by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets, apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin, exact assume i h, this i end ... ≤ principal (- ⋃i, f i) : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter_eq, mem_set_of_eq, mem_Union_eq, and_imp, not_exists, not_eq_empty_iff_exists, exists_imp_distrib, (≠)], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite /- compact sets -/ section compact /-- A set `s` is compact if every filter that contains `s` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥ lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := assume f hnf hsf, let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hsf $ by simp [h]) in have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t, by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a, have a ∈ t, from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf hsf (le_refl _), ⟨a, this, ha⟩ lemma compact_adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f.sets := classical.by_cases mem_sets_of_neq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have nhds a ⊓ principal (-t) ≠ ⊥, from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.mpr this, have false, from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (by simp), by contradiction lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ nhds a ≠ ⊥, by simp [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩ lemma compact_elim_finite_subcover {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' := classical.by_contradiction $ assume h, have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c', from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩, let f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩, principal_mono.mpr $ diff_right_antimono $ sUnion_mono $ subset_union_left _ _, principal_mono.mpr $ diff_right_antimono $ sUnion_mono $ subset_union_right _ _⟩) (assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp [diff_neq_empty]; exact h hc'₁ hc'₂), have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $ show principal (s \ ⋃₀∅) ≤ principal s, by simp; exact subset.refl s, let ⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha in have f ≤ principal (-t), from infi_le_of_le ⟨{t}, by simp [ht₁], finite_insert _ finite_empty⟩ $ principal_mono.mpr $ show s - ⋃₀{t} ⊆ - t, begin simp; exact assume x ⟨_, hnt⟩, hnt end, have is_closed (- t), from is_open_compl_iff.mp $ by simp; exact hc₁ t ht₁, have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›), this ‹a ∈ t› lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := if h : b = ∅ then ⟨∅, by simp, by simp, h ▸ hc₂⟩ else let ⟨i, hi⟩ := exists_mem_of_ne_empty h in have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj, have hc'₂ : s ⊆ ⋃₀ (c '' b), by simpa, let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx, let ⟨f', hf⟩ := axiom_of_choice this, f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i), from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid, by simpa [f, hid, (hf ⟨_, hid⟩).2] using hxi⟩, ⟨f '' d, assume i ⟨j, hj, h⟩, h ▸ by simpa [f, hj] using (hf ⟨_, hj⟩).1, finite_image f hd₂, subset.trans hd₃ $ by simpa [subset_def]⟩ lemma compact_of_finite_subcover {s : set α} (h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥), have hf : ∀x∈s, nhds x ⊓ f = ⊥, by simpa [not_and, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ (nhds x ⊓ f).sets, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ (nhds x ⊓ principal t₂).sets, from (nhds x ⊓ principal t₂).upwards_sets (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have nhds x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa [_root_.not_forall], let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c (assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa [subset_def]) in let ⟨b, hb⟩ := axiom_of_choice $ show ∀s:c', ∃t, t ∈ f.sets ∧ - closure t = s, from assume ⟨x, hx⟩, hcc' hx in have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets, from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left, have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets, from inter_mem_sets (by simp at hfs; assumption) this, have ∅ ∈ f.sets, from f.upwards_sets this $ assume x ⟨hxs, hxi⟩, let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, by simpa using hsc' hxs) in have -closure (b ⟨t, htc'⟩) = t, from (hb _).right, have x ∈ - t, from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by simp at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h ... ⊆ closure (b ⟨t, htc'⟩) : subset_closure ... ⊆ - - closure (b ⟨t, htc'⟩) : by simp; exact subset.refl _), show false, from this hxt, hfn $ by rwa [empty_in_sets_eq_bot] at this lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') := ⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩ lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ by simpa [empty_in_sets_eq_bot] using hsf lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume c hc₁ hc₂, let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, by simpa using hc₂) in ⟨{i}, by simp [hic], finite_singleton _, by simp [hai]⟩ lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) : (∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) := assume hf, compact_of_finite_subcover $ assume c c_open c_cover, have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃₀ c : c_cover), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in let c' := ⋃i, finite_subcovers i in have c' ⊆ c, from Union_subset (λi, (h i).fst), have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1), have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2 ... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _), ⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩ lemma compact_of_finite {s : set α} (hs : finite s) : compact s := let s' : set α := ⋃i ∈ s, {i} in have e : s' = s, from ext $ λi, by simp, have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton), e ▸ this end compact /- separation axioms -/ section separation /-- A T₁ space, also known as a Fréchet space, is a topological space where for every pair `x ≠ y`, there is an open set containing `x` and not `y`. Equivalently, every singleton set is closed. -/ class t1_space (α : Type u) [topological_space α] := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets := mem_nhds_sets is_closed_singleton $ by simp; exact h @[simp] lemma closure_singleton [topological_space α] [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h instance t2_space.t1_space [topological_space α] [t2_space α] : t1_space α := ⟨assume x, have ∀y, y ≠ x ↔ ∃ (i : set α), (x ∉ i ∧ is_open i) ∧ y ∈ i, from assume y, ⟨assume h', let ⟨u, v, hu, hv, hy, hx, h⟩ := t2_separation h' in have x ∉ u, from assume : x ∈ u, have x ∈ u ∩ v, from ⟨this, hx⟩, by rwa [h] at this, ⟨u, ⟨this, hu⟩, hy⟩, assume ⟨s, ⟨hx, hs⟩, hy⟩ h, hx $ h ▸ hy⟩, have (-{x} : set α) = (⋃s∈{s : set α | x ∉ s ∧ is_open s}, s), by apply set.ext; simpa, show is_open (- {x}), by rw [this]; exact (is_open_Union $ assume s, is_open_Union $ assume ⟨_, hs⟩, hs)⟩ lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ (nhds x ⊓ nhds y).sets, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by simp [h], assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by simp [inf_of_le_left h], assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t2_space α := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ (nhds a).sets) : ∃t∈(nhds a).sets, t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_neq_bot $ by simp; exact ht₃, subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ end regularity /- generating sets -/ end topological_space namespace topological_space variables {α : Type u} /-- The least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ g, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) := le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s, begin intros s hs, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat) ... = _ : by simp }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat ... ≤ _ : begin simp; exact subset_sUnion_of_mem htk end } end, this s hs as) end topological_space /- constructions using the complete lattice structure -/ section constructions variables {α : Type u} {β : Type v} instance : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } instance : has_Inf (topological_space α) := ⟨λ tt, { is_open := λs, ∀t∈tt, topological_space.is_open t s, is_open_univ := assume t h, t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂ t ht, t.is_open_inter s₁ s₂ (h₁ t ht) (h₂ t ht), is_open_sUnion := assume s h t ht, t.is_open_sUnion _ $ assume s' hss', h _ hss' _ ht }⟩ private lemma Inf_le {tt : set (topological_space α)} {t : topological_space α} (h : t ∈ tt) : Inf tt ≤ t := assume s hs, hs t h private lemma le_Inf {tt : set (topological_space α)} {t : topological_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := assume s hs t' ht', h t' ht' s hs /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ s = f ⁻¹' s', is_open_univ := ⟨univ, by simp; exact t.is_open_univ⟩, is_open_inter := assume s₁ s₂ ⟨s'₁, hs₁, eq₁⟩ ⟨s'₂, hs₂, eq₂⟩, ⟨s'₁ ∩ s'₂, by simp [eq₁, eq₂]; exact t.is_open_inter _ _ hs₁ hs₂⟩, is_open_sUnion := assume s h, begin simp [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp [sUnion_eq_Union, (λx h, (hf x h).right.symm)], exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨-t, by simp; assumption, by simp [preimage_compl, heq.symm]⟩, assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by simp; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by simp; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } instance : has_inf (topological_space α) := ⟨λ t₁ t₂, { is_open := λs, t₁.is_open s ∧ t₂.is_open s, is_open_univ := ⟨t₁.is_open_univ, t₂.is_open_univ⟩, is_open_inter := assume s₁ s₂ ⟨h₁₁, h₁₂⟩ ⟨h₂₁, h₂₂⟩, ⟨t₁.is_open_inter s₁ s₂ h₁₁ h₂₁, t₂.is_open_inter s₁ s₂ h₁₂ h₂₂⟩, is_open_sUnion := assume s h, ⟨t₁.is_open_sUnion _ $ assume t ht, (h t ht).left, t₂.is_open_sUnion _ $ assume t ht, (h t ht).right⟩ }⟩ instance : has_top (topological_space α) := ⟨{is_open := λs, true, is_open_univ := trivial, is_open_inter := assume a b ha hb, trivial, is_open_sUnion := assume s h, trivial }⟩ instance {α : Type u} : complete_lattice (topological_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := assume a b, le_Inf $ assume x, assume h : a ≤ x ∧ b ≤ x, h.left, le_sup_right := assume a b, le_Inf $ assume x, assume h : a ≤ x ∧ b ≤ x, h.right, sup_le := assume a b c h₁ h₂, Inf_le $ show c ∈ {x | a ≤ x ∧ b ≤ x}, from ⟨h₁, h₂⟩, inf := (⊓), le_inf := assume a b h h₁ h₂ s hs, ⟨h₁ s hs, h₂ s hs⟩, inf_le_left := assume a b s ⟨h₁, h₂⟩, h₁, inf_le_right := assume a b s ⟨h₁, h₂⟩, h₂, top := ⊤, le_top := assume a t ht, trivial, bot := Inf univ, bot_le := assume a, Inf_le $ mem_univ a, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := assume s f h, le_Inf $ assume t ht, ht _ h, Sup_le := assume s f h, Inf_le $ assume t ht, h _ ht, Inf := Inf, le_Inf := assume s a, le_Inf, Inf_le := assume s a, Inf_le, ..topological_space.partial_order } instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ lemma t2_space_top : @t2_space α ⊤ := { t2 := assume x y hxy, ⟨{x}, {y}, trivial, trivial, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; simp at hz; cc⟩ } lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) : t₁ ≤ t₂ := assume s, show @is_open α t₁ s → @is_open α t₂ s, begin simp [is_open_iff_nhds]; exact assume hs a ha, h _ $ hs _ ha end lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma induced_le_iff_le_coinduced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tβ.induced f ≤ tα ↔ tβ ≤ tα.coinduced f := iff.intro (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) (assume h s ⟨t, ht, hst⟩, hst.symm ▸ h _ ht) instance : topological_space empty := ⊤ instance : topological_space unit := ⊤ instance : topological_space bool := ⊤ instance : topological_space ℕ := ⊤ instance : topological_space ℤ := ⊤ instance sierpinski_space : topological_space Prop := topological_space.generate_from {{true}} instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := topological_space.induced subtype.val t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := topological_space.induced prod.fst t₁ ⊔ topological_space.induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := topological_space.coinduced sum.inl t₁ ⊓ topological_space.coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨅a, topological_space.coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨆a, topological_space.induced (λf, f a) (t₂ a) section open topological_space lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : generate_from g ≤ t := assume s (hs : generate_open g s), generate_open.rec_on hs h is_open_univ (assume s t _ _ hs ht, is_open_inter hs ht) (assume k _ hk, is_open_sUnion hk) lemma supr_eq_generate_from {ι : Sort w} { g : ι → topological_space α } : supr g = generate_from (⋃i, {s | (g i).is_open s}) := le_antisymm (supr_le $ assume i s is_open_s, generate_open.basic _ $ by simp; exact ⟨i, is_open_s⟩) (generate_from_le $ assume s, begin simp, exact assume i is_open_s, have g i ≤ supr g, from le_supr _ _, this s is_open_s end) lemma sup_eq_generate_from { g₁ g₂ : topological_space α } : g₁ ⊔ g₂ = generate_from {s | g₁.is_open s ∨ g₂.is_open s} := le_antisymm (sup_le (assume s, generate_open.basic _ ∘ or.inl) (assume s, generate_open.basic _ ∘ or.inr)) (generate_from_le $ assume s hs, have h₁ : g₁ ≤ g₁ ⊔ g₂, from le_sup_left, have h₂ : g₂ ≤ g₁ ⊔ g₂, from le_sup_right, or.rec_on hs (h₁ s) (h₂ s)) lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₂ a ≤ @nhds α t₁ a := infi_le_infi $ assume s, infi_le_infi2 $ assume ⟨ha, hs⟩, ⟨⟨ha, h _ hs⟩, le_refl _⟩ lemma nhds_supr {ι : Sort w} {t : ι → topological_space α} {a : α} : @nhds α (supr t) a = (⨅i, @nhds α (t i) a) := le_antisymm (le_infi $ assume i, nhds_mono $ le_supr _ _) begin rw [supr_eq_generate_from, nhds_generate_from], exact (le_infi $ assume s, le_infi $ assume ⟨hs, hi⟩, begin simp at hi, cases hi with i hi, exact (infi_le_of_le i $ le_principal_iff.mpr $ @mem_nhds_sets α (t i) _ _ hi hs) end) end lemma nhds_sup {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊔ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := calc @nhds α (t₁ ⊔ t₂) a = @nhds α (⨆b:bool, cond b t₁ t₂) a : by rw [supr_bool_eq] ... = (⨅b, @nhds α (cond b t₁ t₂) a) : begin rw [nhds_supr] end ... = @nhds α t₁ a ⊓ @nhds α t₂ a : by rw [infi_bool_eq] end end constructions namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, by simpa [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, by simp; exact (@empty_ne_univ _ ⟨a⟩).symm⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (generate_from_le $ assume s hs, by_cases (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s ≠ ∅, generate_open.basic _ ⟨{s}, by simp [this, hs]⟩)) (generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ by simp [hvu])) (generate_from_le h_open)⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin rw [hb.2.2, nhds_generate_from, infi_sets_eq'], { simpa [and_comm, and.left_comm] }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, by simpa using hu₃⟩ }, { suffices : a ∈ (⋃₀ b), { simpa [and_comm] }, { rw [hb.2.1], trivial } } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} (u : set α) (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t)) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in ⟨b', countable_image $ countable_subset (by simp {contextual:=tt}) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp, is_topological_basis_of_subbasis hb₂⟩ instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from]; simp [infi_subtype], have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs, have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (by simp [countable_Union_Prop]), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa [closure_eq_nhds, nhds_eq, infi_inf w], infi_neq_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets], simp at hs, split; apply inter_subset_inter_right; simp [hs] end⟩) (assume ⟨s, has, hs⟩, have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅, from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ (mem_Union_eq _ _).mpr ⟨hs, by simp⟩⟩, by simp [this]) ⟩⟩ end topological_space section limit variables {α : Type u} [inhabited α] [topological_space α] open classical /-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/ noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h variables [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a := lim_eq nhds_neq_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (nhds a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end limit
19272053951879d5bc00c008f16d0042e5af0b15
e9dbaaae490bc072444e3021634bf73664003760
/src/Test/TestCRing.lean
567ec21c8f46275e5b3cedb58d0b4af18d8b52ad
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,353
lean
import Geo.Arith.CRing import Geo.Background.Real namespace Arith namespace CRing namespace Test open HExpr (horner hornerAux int) open CRExpr abbrev x := atom 0 abbrev y := atom 1 abbrev z := atom 2 def check0 (cr : CRExpr) : IO Unit := if (cr.toHExpr == 0) then IO.println "PASS" else throw $ IO.userError (toString cr.toHExpr ++ " ≠ 0") #eval check0 0 #eval check0 $ 0 + 0 #eval check0 $ 0 + 0 + 0 #eval check0 $ 1 - 1 #eval check0 $ 1 - 1 + 2 - 2 #eval check0 $ x^2 - x*x #eval check0 $ x^3 - x*x*x #eval check0 $ x^4 - x*x*x*x #eval check0 $ x^2 * x^3 - x^5 #eval check0 $ x^2 * (x^3 + 1) - x^5 - x^2 #eval check0 $ (x + y) * x^2 * (x^3 + 1) - (x^6 + x^3 + y * x^5 + y * x^2) #eval check0 $ (x + y)^2 - x^2 - y^2 - 2 * x * y #eval check0 $ (x + y + z)^2 - x^2 - y^2 - z^2 - 2 * x * y - 2 * y * z - 2 * x * z #eval check0 $ x - x #eval check0 $ x^2 - x*x #eval check0 $ - (x + x) + 2 * x #eval check0 $ - (x + x - 2 * x) #eval check0 $ - ((x + y)^2) + (x^2 + 2*x*y + y^2) #eval check0 $ - ((x + y)^2) + (x^2 + 2*x*y + y^2) #eval check0 $ - ((x + y)^2) - - (x^2 + 2*x*y + y^2) #eval check0 $ - (- ((x + y + z)^2) - - - - (x^2 + y^2 + z^2 + 2 * x * y + 2 * y * z + 2 * x * z)) #eval check0 $ ((x + 1) * y) - (x * y + 1 * y) #eval check0 $ x^2 * (x + 1) * y - (x^3 * y + 1 * y * x^2) #eval check0 $ x - - y - x - y end Test end CRing end Arith
bb8390717aa69adc544aa913968543f84bba407c
bd30ef9a38da5172e55165b5cf19d92706763afa
/src/rubiks_cube.lean
9dbee2f9a948b23e125d81d34df561ba237b76e2
[]
no_license
kendfrey/rubiks-cube-group
8838ce34704d8d150e5feba6f1e536b3d228dd37
3baebd73972384294931c75d584a491eb0fbc15c
refs/heads/master
1,671,557,772,358
1,601,554,362,000
1,601,554,362,000
285,715,961
21
0
null
null
null
null
UTF-8
Lean
false
false
20,402
lean
import group_theory.perm.sign import group_theory.subgroup import data.list.perm import fin_group import array_perm_group open equiv open equiv.perm /-- The group of all possible ways to assemble a Rubik's cube. Not all positions are solvable. -/ @[derive group] def rubiks_cube_overgroup := array_perm 8 (fin' 3) × array_perm 12 (fin' 2) section widget inductive colour : Type | white | green | red | blue | orange | yellow open colour instance : has_to_string colour := ⟨ λ c, match c with | white := "#ffffff" | green := "#00ff00" | red := "#ff0000" | blue := "#0000ff" | orange := "#ff7f00" | yellow := "#ffff00" end ⟩ open vector def list.vec {α : Sort*} : Π a : list α, vector α (a.length) | [] := nil | (x :: xs) := cons x (xs.vec) def corner_map : vector (vector colour 3) 8 := [ [white, orange, blue].vec, [white, blue, red].vec, [white, red, green].vec, [white, green, orange].vec, [yellow, orange, green].vec, [yellow, green, red].vec, [yellow, red, blue].vec, [yellow, blue, orange].vec ].vec def edge_map : vector (vector colour 2) 12 := [ [white, blue].vec, [white, red].vec, [white, green].vec, [white, orange].vec, [yellow, green].vec, [yellow, red].vec, [yellow, blue].vec, [yellow, orange].vec, [blue, orange].vec, [blue, red].vec, [green, red].vec, [green, orange].vec ].vec variables (cube : rubiks_cube_overgroup) (i : fin 8) def corner_sticker (i : fin 8) (o : fin 3) (cube : rubiks_cube_overgroup) : colour := nth (nth corner_map (cube.fst.snd.inv_fun i)) (((cube.fst.fst.read i)⁻¹ : fin' 3) + o) def edge_sticker (i : fin 12) (o : fin 2) (cube : rubiks_cube_overgroup) : colour := nth (nth edge_map (cube.snd.snd.inv_fun i)) (((cube.snd.fst.read i)⁻¹ : fin' 2) + o) open widget meta def sticker (x y : ℕ) (colour : colour) : html empty := h "div" [attr.style [("grid-column", to_string x), ("grid-row", to_string y), ("background-color", to_string colour)]] [] meta def rubiks_cube_overgroup.to_html (cube : rubiks_cube_overgroup) : html empty := h "div" [ attr.style [ ("display", "grid"), ("grid-template-columns", "repeat(12, 20px)"), ("grid-template-rows", "repeat(9, 20px)"), ("row-gap", "2px"), ("column-gap", "2px"), ("margin", "10px") ] ] [ sticker 4 1 ∘ corner_sticker 0 0 $ cube, sticker 5 1 ∘ edge_sticker 0 0 $ cube, sticker 6 1 ∘ corner_sticker 1 0 $ cube, sticker 4 2 ∘ edge_sticker 3 0 $ cube, sticker 5 2 white, sticker 6 2 ∘ edge_sticker 1 0 $ cube, sticker 4 3 ∘ corner_sticker 3 0 $ cube, sticker 5 3 ∘ edge_sticker 2 0 $ cube, sticker 6 3 ∘ corner_sticker 2 0 $ cube, sticker 1 4 ∘ corner_sticker 0 1 $ cube, sticker 2 4 ∘ edge_sticker 3 1 $ cube, sticker 3 4 ∘ corner_sticker 3 2 $ cube, sticker 1 5 ∘ edge_sticker 8 1 $ cube, sticker 2 5 orange, sticker 3 5 ∘ edge_sticker 11 1 $ cube, sticker 1 6 ∘ corner_sticker 7 2 $ cube, sticker 2 6 ∘ edge_sticker 7 1 $ cube, sticker 3 6 ∘ corner_sticker 4 1 $ cube, sticker 4 4 ∘ corner_sticker 3 1 $ cube, sticker 5 4 ∘ edge_sticker 2 1 $ cube, sticker 6 4 ∘ corner_sticker 2 2 $ cube, sticker 4 5 ∘ edge_sticker 11 0 $ cube, sticker 5 5 green, sticker 6 5 ∘ edge_sticker 10 0 $ cube, sticker 4 6 ∘ corner_sticker 4 2 $ cube, sticker 5 6 ∘ edge_sticker 4 1 $ cube, sticker 6 6 ∘ corner_sticker 5 1 $ cube, sticker 7 4 ∘ corner_sticker 2 1 $ cube, sticker 8 4 ∘ edge_sticker 1 1 $ cube, sticker 9 4 ∘ corner_sticker 1 2 $ cube, sticker 7 5 ∘ edge_sticker 10 1 $ cube, sticker 8 5 red, sticker 9 5 ∘ edge_sticker 9 1 $ cube, sticker 7 6 ∘ corner_sticker 5 2 $ cube, sticker 8 6 ∘ edge_sticker 5 1 $ cube, sticker 9 6 ∘ corner_sticker 6 1 $ cube, sticker 10 4 ∘ corner_sticker 1 1 $ cube, sticker 11 4 ∘ edge_sticker 0 1 $ cube, sticker 12 4 ∘ corner_sticker 0 2 $ cube, sticker 10 5 ∘ edge_sticker 9 0 $ cube, sticker 11 5 blue, sticker 12 5 ∘ edge_sticker 8 0 $ cube, sticker 10 6 ∘ corner_sticker 6 2 $ cube, sticker 11 6 ∘ edge_sticker 6 1 $ cube, sticker 12 6 ∘ corner_sticker 7 1 $ cube, sticker 4 7 ∘ corner_sticker 4 0 $ cube, sticker 5 7 ∘ edge_sticker 4 0 $ cube, sticker 6 7 ∘ corner_sticker 5 0 $ cube, sticker 4 8 ∘ edge_sticker 7 0 $ cube, sticker 5 8 yellow, sticker 6 8 ∘ edge_sticker 5 0 $ cube, sticker 4 9 ∘ corner_sticker 7 0 $ cube, sticker 5 9 ∘ edge_sticker 6 0 $ cube, sticker 6 9 ∘ corner_sticker 6 0 $ cube ] end widget section face_turns private def cycle_impl {α : Type*} [decidable_eq α] : α → list α → perm α | _ [] := 1 | a (x :: xs) := swap a x * cycle_impl x xs private def cycle {α : Type*} [decidable_eq α] : list α → perm α | [] := 1 | (x :: xs) := cycle_impl x xs open array def wr {n m : ℕ} (i : fin n) (x : fin m) (a : array n (fin' m)) := write a i x def U : rubiks_cube_overgroup := ⟨⟨1, cycle [0, 1, 2, 3]⟩, ⟨1, cycle [0, 1, 2, 3]⟩⟩ def D : rubiks_cube_overgroup := ⟨⟨1, cycle [4, 5, 6, 7]⟩, ⟨1, cycle [4, 5, 6, 7]⟩⟩ def R : rubiks_cube_overgroup := ⟨⟨wr 1 1 ∘ wr 6 2 ∘ wr 5 1 ∘ wr 2 2 $ 1, cycle [1, 6, 5, 2]⟩, ⟨1, cycle [1, 9, 5, 10]⟩⟩ def L : rubiks_cube_overgroup := ⟨⟨wr 0 2 ∘ wr 3 1 ∘ wr 4 2 ∘ wr 7 1 $ 1, cycle [0, 3, 4, 7]⟩, ⟨1, cycle [3, 11, 7, 8]⟩⟩ def F : rubiks_cube_overgroup := ⟨⟨wr 2 1 ∘ wr 5 2 ∘ wr 4 1 ∘ wr 3 2 $ 1, cycle [2, 5, 4, 3]⟩, ⟨wr 2 1 ∘ wr 10 1 ∘ wr 4 1 ∘ wr 11 1 $ 1, cycle [2, 10, 4, 11]⟩⟩ def B : rubiks_cube_overgroup := ⟨⟨wr 0 1 ∘ wr 7 2 ∘ wr 6 1 ∘ wr 1 2 $ 1, cycle [0, 7, 6, 1]⟩, ⟨wr 0 1 ∘ wr 8 1 ∘ wr 6 1 ∘ wr 9 1 $ 1, cycle [0, 8, 6, 9]⟩⟩ def U2 := U^2 def D2 := D^2 def R2 := R^2 def L2 := L^2 def F2 := F^2 def B2 := B^2 def U' := U⁻¹ def D' := D⁻¹ def R' := R⁻¹ def L' := L⁻¹ def F' := F⁻¹ def B' := B⁻¹ instance : has_coe_to_fun rubiks_cube_overgroup := ⟨(λ a, rubiks_cube_overgroup → rubiks_cube_overgroup), λ x y, x * y⟩ end face_turns /-- The set of all solvable Rubik's cubes. -/ def rubiks_cube : set rubiks_cube_overgroup := {c | c.fst.snd.sign = c.snd.snd.sign ∧ multiset.prod ⟦c.fst.fst.to_list⟧ = 1 ∧ multiset.prod ⟦c.snd.fst.to_list⟧ = 1} namespace rubiks_cube section perm_to_list variables {α β : Type*} open list private lemma list_swap_lt {n m : ℕ} : 0 < n → n < m.succ → n - 1 < m := begin intros h₁ h₂, cases n, { exfalso, apply nat.not_lt_zero, apply h₁, }, rw [nat.sub_one, nat.pred_succ], apply nat.lt_of_succ_lt_succ, apply h₂, end @[simp] def list.swap : Π (l : list α) (i j : ℕ), i < j → j < l.length → list α | [] _ _ _ h := false.elim (nat.not_lt_zero _ h) | (x :: xs) _ 0 h _ := false.elim (nat.not_lt_zero _ h) | (x :: xs) 0 (j' + 1) h₁ h₂ := xs.nth_le j' (list_swap_lt h₁ h₂) :: xs.take j' ++ x :: xs.drop (j' + 1) | (x :: xs) (i' + 1) (j' + 1) h₁ h₂ := x :: xs.swap i' j' (nat.lt_of_succ_lt_succ h₁) (nat.lt_of_succ_lt_succ h₂) lemma list_perm_swap {l : list α} {i j h₁ h₂} : list.swap l i j h₁ h₂ ~ l := begin revert i j, induction l, { intros i j _ h, exfalso, apply nat.not_lt_zero, apply h, }, intros i j h₁ h₂, cases i, swap, { cases j, { exfalso, apply nat.not_lt_zero, apply h₁, }, apply perm.cons, apply l_ih, }, cases j, { exfalso, apply nat.not_lt_zero, apply h₁, }, dsimp, rw [← cons_append, ← singleton_append, ← @singleton_append _ l_hd], apply perm_append_comm.trans, rw [singleton_append, cons_append], apply perm.cons, rw ← append_assoc, apply perm_append_comm.trans, apply (perm.append_left _ perm_append_comm).trans, apply eq.rec (perm.refl _), dsimp, rw ← drop_eq_nth_le_cons, apply take_append_drop, end @[simp] lemma list_swap_length {l : list α} {i j h₁ h₂} : (list.swap l i j h₁ h₂).length = l.length := begin apply perm.length_eq, apply list_perm_swap, end private lemma swap_cases [de : decidable_eq α] {x y z : α} (p : α → Prop) : p x → p y → p z → p (swap x y z) := begin intros h_x h_y h_z, cases de z x with z_ne_x z_eq_x, swap, { simp *, }, cases de z y with z_ne_y z_eq_y, swap, { simp *, }, rw swap_apply_of_ne_of_ne; assumption, end private lemma swap_map [de : decidable_eq α] [decidable_eq β] {x y z : α} {f : α → β} (inj : function.injective f) : swap (f x) (f y) (f z) = f (swap x y z) := begin cases de z x, swap, { simp *, }, cases de z y, swap, { simp *, }, rw swap_apply_of_ne_of_ne, rotate, { simp *, }, { simp *, }, rw swap_apply_of_ne_of_ne; assumption, end lemma list_swap_nth_le {l : list α} {i j k h₁ h₂ h₃ h₄} : (list.swap l i j h₁ h₂).nth_le k h₃ = l.nth_le (swap i j k) h₄ := begin revert i j k, induction l, { intros, exfalso, apply nat.not_lt_zero, apply h₂, }, intros, cases j, { exfalso, apply nat.not_lt_zero, apply h₁, }, cases i, { dsimp, cases k, { simp_rw swap_apply_left, refl, }, cases nat.decidable_eq k j with k_ne_j k_eq_j, { have k_pos : k.succ ≠ 0, { intros, contradiction, }, have k_ne_j' : k.succ ≠ j.succ, { intros h, apply k_ne_j, apply nat.succ.inj, apply h, }, simp_rw swap_apply_of_ne_of_ne k_pos k_ne_j', dsimp, cases (lt_or_gt_of_ne k_ne_j) with k_lt_j k_gt_j, { rw nth_le_append, swap, { rw length_take, apply lt_min, { apply k_lt_j, }, { apply lt_trans k_lt_j, apply nat.lt_of_succ_lt_succ, apply h₂, }, }, suffices : ∀ {l : list α} {n i h₁ h₂}, (take n l).nth_le i h₁ = l.nth_le i h₂, { rw this, }, intros l, induction l with l_hd l l_ih, { intros n i h₁ h₂, exfalso, apply nat.not_lt_zero, apply h₂, }, intros n i h₁ h₂, cases n, { exfalso, apply nat.not_lt_zero, apply h₁, }, cases i, { refl, }, apply l_ih, }, { have take_length : (take j l_tl).length = j, { rw length_take, apply min_eq_left, apply le_of_lt, apply nat.lt_of_succ_lt_succ, apply h₂, }, rw nth_le_append_right, swap, { rw take_length, apply le_of_lt, apply k_gt_j, }, simp_rw take_length, cases k, { exfalso, apply nat.not_lt_zero, apply k_gt_j, }, have k_ge_j : k ≥ j, { apply nat.le_of_lt_succ, apply k_gt_j, }, simp_rw @nat.succ_sub k j k_ge_j, dsimp, rw nth_le_drop', congr, rw nat.succ_add, rw nat.add_sub_cancel', apply k_ge_j, }, }, { subst k, simp_rw swap_apply_right, dsimp, have : ∀ {l₁ l₂ : list α} {x : α} {i : ℕ} {h}, l₁.length = i → (l₁ ++ x :: l₂).nth_le i h = x, { intros l₁, induction l₁, { intros, subst i, refl, }, intros l₂ x i h₁ h₂, cases i, { contradiction, }, dsimp, rw l₁_ih, apply nat.succ.inj, apply h₂, }, apply this, rw length_take, apply min_eq_left, apply nat.le_of_succ_le_succ, apply le_of_lt, apply h₂, }, }, { intros, dsimp, cases k, { dsimp, have i_pos : 0 ≠ i.succ, { intros h, contradiction, }, have j_pos : 0 ≠ j.succ, { intros h, contradiction, }, simp_rw swap_apply_of_ne_of_ne i_pos j_pos, simp, }, dsimp, conv_rhs { congr, skip, rw swap_map nat.succ_injective, }, dsimp, apply l_ih, }, end lemma perm_array_swap_eq_to_list_swap {n : ℕ} {a : array n α} {i j h₁ h₂} : (perm_array a (swap i j)).to_list = list.swap a.to_list i j h₁ h₂ := begin apply ext_le, { simp, }, intros k h₃ h₄, rw array.to_list_nth_le, swap, { rwa array.to_list_length at h₃, }, simp_rw perm_array_def, dsimp, have : equiv.symm (swap i j) = swap i j := rfl, rw this, clear this, rw array.to_list_length at *, rw list_swap_nth_le, swap, { rw array.to_list_length, apply swap_cases (< n), { apply lt.trans h₁, apply h₂, }, { apply h₂, }, { apply h₃, }, }, rw array.to_list_nth_le, swap, { apply swap_cases (< n), { apply lt.trans h₁, apply h₂, }, { apply h₂, }, { apply h₃, }, }, congr, apply fin.eq_of_veq, rw swap_apply_def, dsimp, rw swap_apply_def, cases fin.decidable_eq _ ⟨k, _⟩ i with k_ne_i k_eq_i, { rw if_neg, swap, { apply k_ne_i, }, rw @if_neg (k = ↑i), swap, { intros h, apply k_ne_i, apply fin.eq_of_veq, apply h, }, cases fin.decidable_eq _ ⟨k, _⟩ j with k_ne_j k_eq_j, { rw if_neg, swap, { apply k_ne_j, }, rw if_neg, swap, { intros h, apply k_ne_j, apply fin.eq_of_veq, apply h, }, refl, }, rw if_pos, swap, { apply k_eq_j, }, rw if_pos, swap, { rw ← k_eq_j, refl, }, }, rw if_pos, swap, { apply k_eq_i, }, rw if_pos, swap, { rw ← k_eq_i, refl, }, end theorem perm_to_list {n : ℕ} {a : array n α} {p : perm (fin n)} : (perm_array a p).to_list ~ a.to_list := begin apply swap_induction_on p, { rw perm_array_perm_one, }, clear p, intros p i j i_ne_j ih, apply perm.trans _ ih, clear ih, rw ← perm_array_comp, generalize : perm_array a p = l, clear a, wlog i_lt_j : i < j using i j, { apply lt_or_gt_of_ne, apply i_ne_j, }, swap, { rw swap_comm, apply this, symmetry, apply i_ne_j, }, rw perm_array_swap_eq_to_list_swap, rotate, { apply i_lt_j, }, { rw array.to_list_length, apply fin.is_lt, }, apply list_perm_swap, end end perm_to_list private lemma list.map₂_nth_le {α β γ : Type*} {a b} {f : α → β → γ} {i : ℕ} {h h₁ h₂} : (list.map₂ f a b).nth_le i h = f (a.nth_le i h₁) (b.nth_le i h₂) := begin revert b i, induction a, { intros b i h h₁ h₂, exfalso, apply nat.not_lt_zero, apply h₁, }, intros b, cases b, { intros i h h₁ h₂, exfalso, apply nat.not_lt_zero, apply h₂, }, intros i h h₁ h₂, dsimp, cases i, { refl, }, dsimp, apply a_ih, end lemma mul_to_list {α : Type*} [group α] {n : ℕ} {a b : array n α} : (a * b).to_list = list.map₂ (*) a.to_list b.to_list := begin apply list.ext_le, { simp, }, intros i h_i h_i₂, rw array.to_list_length at *, rw list.map₂_nth_le; try { rwa array.to_list_length }, simp only [array.to_list_nth_le _ h_i, array.read_mul], end lemma inv_to_list {α : Type*} [group α] {n : ℕ} {a : array n α} : a⁻¹.to_list = list.map (has_inv.inv) a.to_list := begin apply list.ext_le, { simp, }, intros i h_i h_i₂, rw array.to_list_length at *, rw list.nth_le_map; try { rwa array.to_list_length }, simp only [array.to_list_nth_le _ h_i], refl, end lemma mul_prod {α : Type*} [comm_group α] {a b : list α} : a.length = b.length → (list.map₂ (*) a b).prod = a.prod * b.prod := begin revert b, induction a, { intros b h, rw list.eq_nil_of_length_eq_zero h.symm, simp, }, intros b h, cases b, { contradiction, }, dsimp, simp only [list.prod_cons], rw a_ih; injection h, apply mul_mul_mul_comm, end lemma inv_prod {α : Type*} [comm_group α] {a : list α} : (list.map (has_inv.inv) a).prod = a.prod⁻¹ := begin induction a, { simp, }, simp [list.prod_cons, mul_comm, *], end lemma perm_prod {α : Type*} [comm_group α] {n : ℕ} {a : array n α} {p : perm (fin n)} : (perm_array a p).to_list.prod = a.to_list.prod := begin apply list.perm.prod_eq, apply perm_to_list, end lemma one_mem : (1 : rubiks_cube_overgroup) ∈ rubiks_cube := begin split; try { split }; refl, end lemma mul_mem {a b : rubiks_cube_overgroup} : a ∈ rubiks_cube → b ∈ rubiks_cube → a * b ∈ rubiks_cube := begin intros h_a h_b, split, { simp [h_a.left, h_b.left], }, split; { dsimp, rw [mul_to_list, multiset.coe_prod, mul_prod], swap, { refl, }, have : (perm_array a.fst.fst b.fst.snd).to_list.prod = a.fst.fst.to_list.prod, { apply list.perm.prod_eq, apply perm_to_list, }, rw perm_prod, rcases h_a with ⟨_, h_a₁, h_a₂⟩, rcases h_b with ⟨_, h_b₁, h_b₂⟩, simp [multiset.coe_prod, *] at *, }, end lemma inv_mem {x : rubiks_cube_overgroup} : x ∈ rubiks_cube → x⁻¹ ∈ rubiks_cube := begin intros h, split, { simp [sign_inv, h.left], }, split; { dsimp, rw [multiset.coe_prod, perm_prod, inv_to_list, inv_prod, one_inv.symm], apply inv_inj.mpr, rcases h with ⟨_, h₁, h₂⟩, simp [multiset.coe_prod, *] at *, }, end protected def group : subgroup rubiks_cube_overgroup := { carrier := rubiks_cube, one_mem' := one_mem, mul_mem' := @mul_mem, inv_mem' := @inv_mem, } end rubiks_cube
61ec81e325a5942973485d12295292ffdd999dc7
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/option.lean
193c90356109a5f30c9bacef8d2472f5d00e6586
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,435
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 logic.eq logic.inhabited logic.decidable open eq.ops decidable inductive option (A : Type) : Type := none {} : option A, some : A → option A namespace option definition is_none {A : Type} (o : option A) : Prop := rec true (λ a, false) o theorem is_none_none {A : Type} : is_none (@none A) := trivial theorem not_is_none_some {A : Type} (a : A) : ¬ is_none (some a) := not_false_trivial theorem none_ne_some {A : Type} (a : A) : none ≠ some a := assume H, no_confusion H theorem some.inj {A : Type} {a₁ a₂ : A} (H : some a₁ = some a₂) : a₁ = a₂ := no_confusion H (λe, e) protected definition is_inhabited [instance] (A : Type) : inhabited (option A) := inhabited.mk none protected definition has_decidable_eq [instance] {A : Type} (H : decidable_eq A) : decidable_eq (option A) := take o₁ o₂ : option A, rec_on o₁ (rec_on o₂ (inl rfl) (take a₂, (inr (none_ne_some a₂)))) (take a₁ : A, rec_on o₂ (inr (ne.symm (none_ne_some a₁))) (take a₂ : A, decidable.rec_on (H a₁ a₂) (assume Heq : a₁ = a₂, inl (Heq ▸ rfl)) (assume Hne : a₁ ≠ a₂, inr (assume Hn : some a₁ = some a₂, absurd (some.inj Hn) Hne)))) end option
d2f2104277f8abf6a7397f21fb7c0c5cb1076a4b
6de8ea38e7f58ace8fbf74ba3ad0bf3b3d1d7ab5
/homework2/Problem3/solutions.lean
201d208bb3e42ec78c7eab14a450826b07dff7e4
[]
no_license
KinanBab/CS591K1-Labs
72f4e2c7d230d4e4f548a343a47bf815272b1f58
d4569bf99d20c22cd56721024688cda247d1447f
refs/heads/master
1,587,016,758,873
1,558,148,366,000
1,558,148,366,000
165,329,114
5
2
null
1,550,689,848,000
1,547,252,664,000
TeX
UTF-8
Lean
false
false
3,056
lean
@[simp] def mylength : (list nat) -> nat | list.nil := 0 | (list.cons h l') := 1 + mylength l' -- Problem 3: reversing a list (35 points for full credit, total with all bonuses is 60 points) -- Part A: implement a reverse functionality (5 points) -- One of the common ways to reverse an array is to rely -- on append #check list.append #eval [1, 2, 3] ++ [6, 7] -- shortcut notation for list.append @[simp] def myrev : (list nat) -> (list nat) -- your implementation goes here | l := list.nil -- Part B: simple reverse properties (5 points) -- Helpful lemma: show how myrev and append compose lemma myrev_append (l1 l2: list nat) : myrev (l1 ++ l2) = (myrev l2) ++ (myrev l1) := begin --proof goes here end -- applying reverse twice should land us in the same array theorem myrev_myrev (l: list nat) : myrev (myrev l) = l := begin -- proof goes here end -- Part B: reverse and length (5 points) -- show how length and append compose lemma mylength_append (l1 l2: list nat): mylength (l1 ++ l2) = mylength l1 + mylength l2 := begin -- proof goes here end -- reverse preserves length theorem myrev_length (l: list nat): mylength l = mylength (myrev l) := begin -- proof goes here end -- Part C: (10 points) -- Are these 2 theorems (without the lemmas) enough to conclude -- that myrev is `correct` according to our intuitive definition of correctness? -- Can you think of a counter example implementation? -- one that satisifies both properties but is incorrect? -- HINT: you can come up with one without using append @[simp] def incorrect_myrev : (list nat) -> (list nat) -- implementation goes here | l := list.nil theorem incorrect_myrev_ok1 (l: list nat) : incorrect_myrev (incorrect_myrev l) = l := begin -- proof goes here end theorem incorrect_myrev_ok2 (l: list nat) : mylength l = mylength (incorrect_myrev l) := begin -- proof goes here end -- Part D: BONUS (10 points) -- What if we include myrev_append lemma? how about only [myrev_append] lemma and [myrev_length]? -- Would your counter example still work? -- If yes, prove it! can you give another counter example? -- if not, how can you be sure that no other example exists? -- Write a theorem statement that formally encodes whether the -- properties are enough or not, you do not have to prove it (but can do so for an extra 15 points) -- HINT: one possible way of encoding this is to say, if myrev satisifies both theorems, then -- it must satisify some very tedious and verbose encoding of what `correctness` means. -- Answer goes here -- Part E: summing the elment of the list (10 points) @[simp] def mysum : (list nat) -> nat -- your implementation goes here | l := 0 -- It may help you to prove some lemma about mysum and append -- in particular that the sum of two appended list, is the -- sum of each separatly added together -- you can use such a lemma in the theorem below to simplify the proof. -- prove that reverse preserves sum theorem myrev_mysum (l1: list nat) : mysum (myrev l1) = mysum l1 := begin -- proof goes here end
29672c5d6372e8980ccf46de4e59292456ff9a0d
9cba98daa30c0804090f963f9024147a50292fa0
/old/src/classical_time.lean
8e5c21170b64263c383d0cf680a427d9b8998c60
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
7,143
lean
import .....math.affine.affine_coordinate_framed_space_lib import .....math.affine.affine_coordinate_transform import ..metrology.dimensions import ..metrology.measurement import data.real.basic noncomputable theory --open real_lib open measurementSystem open aff_fr open aff_lib open aff_trans structure classicalTime : Type := mk :: (sp : aff_lib.affine_coord_space.standard_space ℝ 1) (id : ℕ) -- id serves as unique ID for a given geometric space attribute [reducible] def classicalTime.build (id : ℕ) : classicalTime := ⟨aff_lib.affine_coord_space.mk_with_standard ℝ 1, id⟩ noncomputable def classicalTime.algebra : classicalTime → aff_lib.affine_coord_space.standard_space ℝ 1 | (classicalTime.mk sp n) := sp structure classicalTimeScalar := mk :: (sp : classicalTime) (val : ℝ) attribute [reducible] def classicalTimeScalar.build (sp : classicalTime) (val : vector ℝ 1) := classicalTimeScalar.mk sp (val.nth 1) attribute [reducible] def classicalTimeScalar.algebra (s : classicalTimeScalar) := s.val structure classicalTimeVector := mk :: (sp : classicalTime) (coords : vector ℝ 1) attribute [reducible] def classicalTimeVector.build (sp : classicalTime) (coords : vector ℝ 1) := classicalTimeVector.mk sp --⟨[coord], by refl⟩ coords attribute [reducible] def classicalTimeVector.algebra (v : classicalTimeVector) := (aff_lib.affine_coord_space.mk_coord_vec (classicalTime.algebra v.sp) v.coords) structure classicalTimePoint := mk :: (sp : classicalTime) (coords : vector ℝ 1) attribute [reducible] def classicalTimePoint.build (sp : classicalTime) (coords : vector ℝ 1) := classicalTimePoint.mk sp --⟨[coord], by refl⟩ coords attribute [reducible] def classicalTimePoint.algebra (v : classicalTimePoint) := (aff_lib.affine_coord_space.mk_coord_point (classicalTime.algebra v.sp) v.coords) abbreviation classicalTimeBasis := (fin 1) → classicalTimeVector inductive classicalTimeFrame : Type | std (sp : classicalTime) : classicalTimeFrame | derived (sp : classicalTime) --ALERT : WEAK TYPING (fr : classicalTimeFrame) --ALERT : WEAK TYPING (origin : classicalTimePoint) (basis : classicalTimeBasis) (m : MeasurementSystem) : classicalTimeFrame | interpret (fr : classicalTimeFrame) (m : MeasurementSystem) attribute [reducible] def classicalTimeFrame.space : classicalTimeFrame → classicalTime | (classicalTimeFrame.std sp) := sp | (classicalTimeFrame.derived s f o b m) := s | (classicalTimeFrame.interpret f m) := classicalTimeFrame.space f attribute [reducible] def classicalTimeFrame.build_derived : classicalTimeFrame → classicalTimePoint → classicalTimeBasis → MeasurementSystem → classicalTimeFrame | (classicalTimeFrame.std sp) p v m := classicalTimeFrame.derived sp (classicalTimeFrame.std sp) p v m | (classicalTimeFrame.derived s f o b m) p v ms := classicalTimeFrame.derived s (classicalTimeFrame.derived s f o b m) p v ms | (classicalTimeFrame.interpret f m) p v ms := classicalTimeFrame.derived (classicalTimeFrame.space f) (classicalTimeFrame.interpret f m) p v ms attribute [reducible] noncomputable def classicalTimeFrame.algebra : classicalTimeFrame → aff_fr.affine_coord_frame ℝ 1 | (classicalTimeFrame.std sp) := aff_lib.affine_coord_space.frame (classicalTime.algebra sp) | (classicalTimeFrame.derived s f o b m) := let base_fr := (classicalTimeFrame.algebra f) in let base_sp := aff_lib.affine_coord_space.mk_from_frame base_fr in aff_lib.affine_coord_space.mk_frame base_sp (aff_lib.affine_coord_space.mk_coord_point base_sp o.coords) (aff_lib.affine_coord_space.mk_basis base_sp ⟨[aff_lib.affine_coord_space.mk_coord_vec base_sp (b 1).coords], by refl⟩) base_fr | (classicalTimeFrame.interpret f m) := classicalTimeFrame.algebra f attribute [reducible] def classicalTime.stdFrame (sp : classicalTime) := classicalTimeFrame.std sp structure classicalTimeCoordinateVector extends classicalTimeVector := mk :: (frame : classicalTimeFrame) attribute [reducible] def classicalTimeCoordinateVector.build (sp : classicalTime) (fr : classicalTimeFrame) (coords : vector ℝ 1) : classicalTimeCoordinateVector := { frame := fr, ..(classicalTimeVector.build sp coords) } attribute [reducible] def classicalTimeCoordinateVector.fromalgebra {f : affine_coord_frame ℝ 1} (sp : classicalTime) (fr : classicalTimeFrame) (vec : aff_coord_vec ℝ 1 f) --(vec : aff_coord_vec ℝ 1 (classicalTimeFrame.algebra fr)) : classicalTimeCoordinateVector := classicalTimeCoordinateVector.build sp fr (affine_coord_vec.get_coords vec) attribute [reducible] def classicalTimeCoordinateVector.algebra (v : classicalTimeCoordinateVector) := let base_fr := (classicalTimeFrame.algebra v.frame) in let base_sp := aff_lib.affine_coord_space.mk_from_frame base_fr in aff_lib.affine_coord_space.mk_coord_vec base_sp v.coords structure classicalTimeCoordinatePoint extends classicalTimePoint := mk :: (frame : classicalTimeFrame) attribute [reducible] def classicalTimeCoordinatePoint.build (sp : classicalTime) (fr : classicalTimeFrame) (coords : vector ℝ 1) : classicalTimeCoordinatePoint := { frame := fr, ..(classicalTimePoint.build sp coords) } attribute [reducible] def classicalTimeCoordinatePoint.fromalgebra {f : affine_coord_frame ℝ 1} (sp : classicalTime) (fr : classicalTimeFrame) (pt : aff_coord_pt ℝ 1 f) : classicalTimeCoordinatePoint := classicalTimeCoordinatePoint.build sp fr (affine_coord_pt.get_coords pt) attribute [reducible] def classicalTimeCoordinatePoint.algebra (v : classicalTimeCoordinatePoint) := let base_fr := (classicalTimeFrame.algebra v.frame) in let base_sp := aff_lib.affine_coord_space.mk_from_frame base_fr in aff_lib.affine_coord_space.mk_coord_point base_sp v.coords --attribute [reducible] structure classicalTimeTransform := (sp : classicalTime) (from_ : classicalTimeFrame) (to_ : classicalTimeFrame) def classicalTimeTransform.build (sp : classicalTime) (from_ : classicalTimeFrame) (to_ : classicalTimeFrame) := classicalTimeTransform.mk sp from_ to_ attribute [reducible] def classicalTimeTransform.algebra (tr : classicalTimeTransform) := affine_coord_space.build_transform ℝ 1 ((classicalTimeFrame.algebra tr.from_)) ((classicalTimeFrame.algebra tr.to_)) (⟨⟨⟩⟩ : affine_coord_space ℝ 1 _) (⟨⟨⟩⟩ : affine_coord_space ℝ 1 _)
fdd46c6e4da7904601d8c3a9164cec9beb2917ec
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/list/alist.lean
3b2b912169beac7812a4475c9c9c5d5ab10d9336
[ "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
12,225
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro -/ import data.list.sigma /-! # Association Lists This file defines association lists. An association list is a list where every element consists of a key and a value, and no two entries have the same key. The type of the value is allowed to be dependent on the type of the key. This type dependence is implemented using `sigma`: The elements of the list are of type `sigma β`, for some type index `β`. ## Main definitions Association lists are represented by the `alist` structure. This file defines this structure and provides ways to access, modify, and combine `alist`s. * `alist.keys` returns a list of keys of the alist. * `alist.has_mem` returns membership in the set of keys. * `alist.erase` removes a certain key. * `alist.insert` adds a key-value mapping to the list. * `alist.union` combines two association lists. ## References * <https://en.wikipedia.org/wiki/Association_list> -/ universes u v w open list variables {α : Type u} {β : α → Type v} /-- `alist β` is a key-value map stored as a `list` (i.e. a linked list). It is a wrapper around certain `list` functions with the added constraint that the list have unique keys. -/ structure alist (β : α → Type v) : Type (max u v) := (entries : list (sigma β)) (nodupkeys : entries.nodupkeys) /-- Given `l : list (sigma β)`, create a term of type `alist β` by removing entries with duplicate keys. -/ def list.to_alist [decidable_eq α] {β : α → Type v} (l : list (sigma β)) : alist β := { entries := _, nodupkeys := nodupkeys_dedupkeys l } namespace alist @[ext] theorem ext : ∀ {s t : alist β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' lemma ext_iff {s t : alist β} : s = t ↔ s.entries = t.entries := ⟨congr_arg _, ext⟩ instance [decidable_eq α] [∀ a, decidable_eq (β a)] : decidable_eq (alist β) := λ xs ys, by rw ext_iff; apply_instance /-! ### keys -/ /-- The list of keys of an association list. -/ def keys (s : alist β) : list α := s.entries.keys theorem keys_nodup (s : alist β) : s.keys.nodup := s.nodupkeys /-! ### mem -/ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (alist β) := ⟨λ a s, a ∈ s.keys⟩ theorem mem_keys {a : α} {s : alist β} : a ∈ s ↔ a ∈ s.keys := iff.rfl theorem mem_of_perm {a : α} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : a ∈ s₁ ↔ a ∈ s₂ := (p.map sigma.fst).mem_iff /-! ### empty -/ /-- The empty association list. -/ instance : has_emptyc (alist β) := ⟨⟨[], nodupkeys_nil⟩⟩ instance : inhabited (alist β) := ⟨∅⟩ @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : alist β) := not_mem_nil a @[simp] theorem empty_entries : (∅ : alist β).entries = [] := rfl @[simp] theorem keys_empty : (∅ : alist β).keys = [] := rfl /-! ### singleton -/ /-- The singleton association list. -/ def singleton (a : α) (b : β a) : alist β := ⟨[⟨a, b⟩], nodupkeys_singleton _⟩ @[simp] theorem singleton_entries (a : α) (b : β a) : (singleton a b).entries = [sigma.mk a b] := rfl @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = [a] := rfl /-! ### lookup -/ section variables [decidable_eq α] /-- Look up the value associated to a key in an association list. -/ def lookup (a : α) (s : alist β) : option (β a) := s.entries.lookup a @[simp] theorem lookup_empty (a) : lookup a (∅ : alist β) = none := rfl theorem lookup_is_some {a : α} {s : alist β} : (s.lookup a).is_some ↔ a ∈ s := lookup_is_some theorem lookup_eq_none {a : α} {s : alist β} : lookup a s = none ↔ a ∉ s := lookup_eq_none theorem mem_lookup_iff {a : α} {b : β a} {s : alist β} : b ∈ lookup a s ↔ sigma.mk a b ∈ s.entries := mem_lookup_iff s.nodupkeys theorem perm_lookup {a : α} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : s₁.lookup a = s₂.lookup a := perm_lookup _ s₁.nodupkeys s₂.nodupkeys p instance (a : α) (s : alist β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /-! ### replace -/ /-- Replace a key with a given value in an association list. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : alist β) : alist β := ⟨kreplace a b s.entries, (kreplace_nodupkeys a b).2 s.nodupkeys⟩ @[simp] theorem keys_replace (a : α) (b : β a) (s : alist β) : (replace a b s).keys = s.keys := keys_kreplace _ _ _ @[simp] theorem mem_replace {a a' : α} {b : β a} {s : alist β} : a' ∈ replace a b s ↔ a' ∈ s := by rw [mem_keys, keys_replace, ←mem_keys] theorem perm_replace {a : α} {b : β a} {s₁ s₂ : alist β} : s₁.entries ~ s₂.entries → (replace a b s₁).entries ~ (replace a b s₂).entries := perm.kreplace s₁.nodupkeys end /-- Fold a function over the key-value pairs in the map. -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (d : δ) (m : alist β) : δ := m.entries.foldl (λ r a, f r a.1 a.2) d /-! ### erase -/ section variables [decidable_eq α] /-- Erase a key from the map. If the key is not present, do nothing. -/ def erase (a : α) (s : alist β) : alist β := ⟨s.entries.kerase a, s.nodupkeys.kerase a⟩ @[simp] lemma keys_erase (a : α) (s : alist β) : (erase a s).keys = s.keys.erase a := keys_kerase @[simp] theorem mem_erase {a a' : α} {s : alist β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := by rw [mem_keys, keys_erase, s.keys_nodup.mem_erase_iff, ←mem_keys] theorem perm_erase {a : α} {s₁ s₂ : alist β} : s₁.entries ~ s₂.entries → (erase a s₁).entries ~ (erase a s₂).entries := perm.kerase s₁.nodupkeys @[simp] theorem lookup_erase (a) (s : alist β) : lookup a (erase a s) = none := lookup_kerase a s.nodupkeys @[simp] theorem lookup_erase_ne {a a'} {s : alist β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := lookup_kerase_ne h theorem erase_erase (a a' : α) (s : alist β) : (s.erase a).erase a' = (s.erase a').erase a := ext $ kerase_kerase /-! ### insert -/ /-- Insert a key-value pair into an association list and erase any existing pair with the same key. -/ def insert (a : α) (b : β a) (s : alist β) : alist β := ⟨kinsert a b s.entries, kinsert_nodupkeys a b s.nodupkeys⟩ @[simp] theorem insert_entries {a} {b : β a} {s : alist β} : (insert a b s).entries = sigma.mk a b :: kerase a s.entries := rfl theorem insert_entries_of_neg {a} {b : β a} {s : alist β} (h : a ∉ s) : (insert a b s).entries = ⟨a, b⟩ :: s.entries := by rw [insert_entries, kerase_of_not_mem_keys h] @[simp] theorem insert_empty (a) (b : β a) : insert a b ∅ = singleton a b := rfl @[simp] theorem mem_insert {a a'} {b' : β a'} (s : alist β) : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := mem_keys_kinsert @[simp] theorem keys_insert {a} {b : β a} (s : alist β) : (insert a b s).keys = a :: s.keys.erase a := by simp [insert, keys, keys_kerase] theorem perm_insert {a} {b : β a} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : (insert a b s₁).entries ~ (insert a b s₂).entries := by simp only [insert_entries]; exact p.kinsert s₁.nodupkeys @[simp] theorem lookup_insert {a} {b : β a} (s : alist β) : lookup a (insert a b s) = some b := by simp only [lookup, insert, lookup_kinsert] @[simp] theorem lookup_insert_ne {a a'} {b' : β a'} {s : alist β} (h : a ≠ a') : lookup a (insert a' b' s) = lookup a s := lookup_kinsert_ne h @[simp] theorem lookup_to_alist {a} (s : list (sigma β)) : lookup a s.to_alist = s.lookup a := by rw [list.to_alist,lookup,lookup_dedupkeys] @[simp] theorem insert_insert {a} {b b' : β a} (s : alist β) : (s.insert a b).insert a b' = s.insert a b' := by ext : 1; simp only [alist.insert_entries, list.kerase_cons_eq]; constructor_matching* [_ ∧ _]; refl theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : alist β) (h : a ≠ a') : ((s.insert a b).insert a' b').entries ~ ((s.insert a' b').insert a b).entries := by simp only [insert_entries]; rw [kerase_cons_ne,kerase_cons_ne,kerase_comm]; [apply perm.swap, exact h, exact h.symm] @[simp] lemma insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b := ext $ by simp only [alist.insert_entries, list.kerase_cons_eq, and_self, alist.singleton_entries, heq_iff_eq, eq_self_iff_true] @[simp] theorem entries_to_alist (xs : list (sigma β)) : (list.to_alist xs).entries = dedupkeys xs := rfl theorem to_alist_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_alist (⟨a,b⟩ :: xs) = insert a b xs.to_alist := rfl /-! ### extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : alist β) : option (β a) × alist β := have (kextract a s.entries).2.nodupkeys, by rw [kextract_eq_lookup_kerase]; exact s.nodupkeys.kerase _, match kextract a s.entries, this with | (b, l), h := (b, ⟨l, h⟩) end @[simp] theorem extract_eq_lookup_erase (a : α) (s : alist β) : extract a s = (lookup a s, erase a s) := by simp [extract]; split; refl /-! ### union -/ /-- `s₁ ∪ s₂` is the key-based union of two association lists. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union (s₁ s₂ : alist β) : alist β := ⟨s₁.entries.kunion s₂.entries, s₁.nodupkeys.kunion s₂.nodupkeys⟩ instance : has_union (alist β) := ⟨union⟩ @[simp] theorem union_entries {s₁ s₂ : alist β} : (s₁ ∪ s₂).entries = kunion s₁.entries s₂.entries := rfl @[simp] theorem empty_union {s : alist β} : (∅ : alist β) ∪ s = s := ext rfl @[simp] theorem union_empty {s : alist β} : s ∪ (∅ : alist β) = s := ext $ by simp @[simp] theorem mem_union {a} {s₁ s₂ : alist β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_keys_kunion theorem perm_union {s₁ s₂ s₃ s₄ : alist β} (p₁₂ : s₁.entries ~ s₂.entries) (p₃₄ : s₃.entries ~ s₄.entries) : (s₁ ∪ s₃).entries ~ (s₂ ∪ s₄).entries := by simp [p₁₂.kunion s₃.nodupkeys p₃₄] theorem union_erase (a : α) (s₁ s₂ : alist β) : erase a (s₁ ∪ s₂) = erase a s₁ ∪ erase a s₂ := ext kunion_kerase.symm @[simp] theorem lookup_union_left {a} {s₁ s₂ : alist β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := lookup_kunion_left @[simp] theorem lookup_union_right {a} {s₁ s₂ : alist β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := lookup_kunion_right @[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : alist β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ := mem_lookup_kunion theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : alist β} : b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := mem_lookup_kunion_middle theorem insert_union {a} {b : β a} {s₁ s₂ : alist β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := by ext; simp theorem union_assoc {s₁ s₂ s₃ : alist β} : ((s₁ ∪ s₂) ∪ s₃).entries ~ (s₁ ∪ (s₂ ∪ s₃)).entries := lookup_ext (alist.nodupkeys _) (alist.nodupkeys _) (by simp [decidable.not_or_iff_and_not,or_assoc,and_or_distrib_left,and_assoc]) end /-! ### disjoint -/ /-- Two associative lists are disjoint if they have no common keys. -/ def disjoint (s₁ s₂ : alist β) : Prop := ∀ k ∈ s₁.keys, ¬ k ∈ s₂.keys variables [decidable_eq α] theorem union_comm_of_disjoint {s₁ s₂ : alist β} (h : disjoint s₁ s₂) : (s₁ ∪ s₂).entries ~ (s₂ ∪ s₁).entries := lookup_ext (alist.nodupkeys _) (alist.nodupkeys _) (begin intros, simp, split; intro h', cases h', { right, refine ⟨_,h'⟩, apply h, rw [keys,← list.lookup_is_some,h'], exact rfl }, { left, rw h'.2 }, cases h', { right, refine ⟨_,h'⟩, intro h'', apply h _ h'', rw [keys,← list.lookup_is_some,h'], exact rfl }, { left, rw h'.2 }, end) end alist
a0a9cc2c3add9ae5227b5641b305c82ee4b5ecda
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/instances/rat.lean
a1b57c42926f58dc8da35b625b9a9a9698d363bd
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
4,091
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.order.archimedean import topology.instances.int import topology.instances.nat import topology.instances.real /-! # Topology on the ratonal numbers The structure of a metric space on `ℚ` is introduced in this file, induced from `ℝ`. -/ noncomputable theory open metric set filter namespace rat instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem dist_eq (x y : ℚ) : dist x y = |x - y| := rfl @[norm_cast, simp] lemma dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl theorem uniform_continuous_coe_real : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_coe_real : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_coe_real : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_coe_real.dense_embedding rat.dense_range_cast theorem embedding_coe_real : embedding (coe : ℚ → ℝ) := dense_embedding_coe_real.to_embedding theorem continuous_coe_real : continuous (coe : ℚ → ℝ) := uniform_continuous_coe_real.continuous end rat @[norm_cast, simp] theorem nat.dist_cast_rat (x y : ℕ) : dist (x : ℚ) y = dist x y := by rw [← nat.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast lemma nat.uniform_embedding_coe_rat : uniform_embedding (coe : ℕ → ℚ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using nat.pairwise_one_le_dist lemma nat.closed_embedding_coe_rat : closed_embedding (coe : ℕ → ℚ) := closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using nat.pairwise_one_le_dist @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast lemma int.uniform_embedding_coe_rat : uniform_embedding (coe : ℤ → ℚ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using int.pairwise_one_le_dist lemma int.closed_embedding_coe_rat : closed_embedding (coe : ℤ → ℚ) := closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using int.pairwise_one_le_dist instance : noncompact_space ℚ := int.closed_embedding_coe_rat.noncompact_space -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := rat.uniform_embedding_coe_real.to_uniform_inducing.uniform_continuous_iff.2 $ by simp only [(∘), rat.cast_add]; exact real.uniform_continuous_add.comp (rat.uniform_continuous_coe_real.prod_map rat.uniform_continuous_coe_real) theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := rat.embedding_coe_real.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((rat.continuous_coe_real.prod_map rat.continuous_coe_real)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage rat.uniform_embedding_coe_real (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end
bbeeeb4fb13fb14bb16a7a1696efce63da70cbdc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/projective.lean
d24b4877fcff4176429136675513014cce52becb
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,276
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison, Jakob von Raumer -/ import algebra.homology.quasi_iso import category_theory.preadditive.projective_resolution import category_theory.preadditive.yoneda.limits import category_theory.preadditive.yoneda.projective /-! # Abelian categories with enough projectives have projective resolutions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. When `C` is abelian `projective.d f` and `f` are exact. Hence, starting from an epimorphism `P ⟶ X`, where `P` is projective, we can apply `projective.d` repeatedly to obtain a projective resolution of `X`. -/ noncomputable theory open category_theory open category_theory.limits open opposite universes v u v' u' namespace category_theory open category_theory.projective variables {C : Type u} [category.{v} C] [abelian C] /-- When `C` is abelian, `projective.d f` and `f` are exact. -/ lemma exact_d_f [enough_projectives C] {X Y : C} (f : X ⟶ Y) : exact (d f) f := (abelian.exact_iff _ _).2 $ ⟨by simp, zero_of_epi_comp (π _) $ by rw [←category.assoc, cokernel.condition]⟩ /-- The preadditive Co-Yoneda functor on `P` preserves colimits if `P` is projective. -/ def preserves_finite_colimits_preadditive_coyoneda_obj_of_projective (P : C) [hP : projective P] : preserves_finite_colimits (preadditive_coyoneda_obj (op P)) := begin letI := (projective_iff_preserves_epimorphisms_preadditive_coyoneda_obj' P).mp hP, apply functor.preserves_finite_colimits_of_preserves_epis_and_kernels, end /-- An object is projective if its preadditive Co-Yoneda functor preserves finite colimits. -/ lemma projective_of_preserves_finite_colimits_preadditive_coyoneda_obj (P : C) [hP : preserves_finite_colimits (preadditive_coyoneda_obj (op P))] : projective P := begin rw projective_iff_preserves_epimorphisms_preadditive_coyoneda_obj', apply_instance end namespace ProjectiveResolution /-! Our goal is to define `ProjectiveResolution.of Z : ProjectiveResolution Z`. The `0`-th object in this resolution will just be `projective.over Z`, i.e. an arbitrarily chosen projective object with a map to `Z`. After that, we build the `n+1`-st object as `projective.syzygies` applied to the previously constructed morphism, and the map to the `n`-th object as `projective.d`. -/ variables [enough_projectives C] /-- Auxiliary definition for `ProjectiveResolution.of`. -/ @[simps] def of_complex (Z : C) : chain_complex C ℕ := chain_complex.mk' (projective.over Z) (projective.syzygies (projective.π Z)) (projective.d (projective.π Z)) (λ ⟨X, Y, f⟩, ⟨projective.syzygies f, projective.d f, (exact_d_f f).w⟩) /-- In any abelian category with enough projectives, `ProjectiveResolution.of Z` constructs a projective resolution of the object `Z`. -/ @[irreducible] def of (Z : C) : ProjectiveResolution Z := { complex := of_complex Z, π := chain_complex.mk_hom _ _ (projective.π Z) 0 (by { simp, exact (exact_d_f (projective.π Z)).w.symm, }) (λ n _, ⟨0, by ext⟩), projective := by { rintros (_|_|_|n); apply projective.projective_over, }, exact₀ := by simpa using exact_d_f (projective.π Z), exact := by { rintros (_|n); { simp, apply exact_d_f, }, }, epi := projective.π_epi Z, } @[priority 100] instance (Z : C) : has_projective_resolution Z := { out := ⟨of Z⟩ } @[priority 100] instance : has_projective_resolutions C := { out := λ Z, by apply_instance } end ProjectiveResolution end category_theory namespace homological_complex.hom variables {C : Type u} [category.{v} C] [abelian C] /-- If `X` is a chain complex of projective objects and we have a quasi-isomorphism `f : X ⟶ Y[0]`, then `X` is a projective resolution of `Y.` -/ def to_single₀_ProjectiveResolution {X : chain_complex C ℕ} {Y : C} (f : X ⟶ (chain_complex.single₀ C).obj Y) [quasi_iso f] (H : ∀ n, projective (X.X n)) : ProjectiveResolution Y := { complex := X, π := f, projective := H, exact₀ := f.to_single₀_exact_d_f_at_zero, exact := f.to_single₀_exact_at_succ, epi := f.to_single₀_epi_at_zero } end homological_complex.hom
4f92b0ec7790070a58a02771038180b48f23df05
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/diff_cont_on_cl.lean
7c9c611b29ebfdb5296bafdcdce7a8b6bd5e9ddf
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,947
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.calculus.deriv.inv /-! # Functions differentiable on a domain and continuous on its closure > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Many theorems in complex analysis assume that a function is complex differentiable on a domain and is continuous on its closure. In this file we define a predicate `diff_cont_on_cl` that expresses this property and prove basic facts about this predicate. -/ open set filter metric open_locale topology variables (𝕜 : Type*) {E F G : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_add_comm_group F] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_add_comm_group G] [normed_space 𝕜 G] {f g : E → F} {s t : set E} {x : E} /-- A predicate saying that a function is differentiable on a set and is continuous on its closure. This is a common assumption in complex analysis. -/ @[protect_proj] structure diff_cont_on_cl (f : E → F) (s : set E) : Prop := (differentiable_on : differentiable_on 𝕜 f s) (continuous_on : continuous_on f (closure s)) variable {𝕜} lemma differentiable_on.diff_cont_on_cl (h : differentiable_on 𝕜 f (closure s)) : diff_cont_on_cl 𝕜 f s := ⟨h.mono subset_closure, h.continuous_on⟩ lemma differentiable.diff_cont_on_cl (h : differentiable 𝕜 f) : diff_cont_on_cl 𝕜 f s := ⟨h.differentiable_on, h.continuous.continuous_on⟩ lemma is_closed.diff_cont_on_cl_iff (hs : is_closed s) : diff_cont_on_cl 𝕜 f s ↔ differentiable_on 𝕜 f s := ⟨λ h, h.differentiable_on, λ h, ⟨h, hs.closure_eq.symm ▸ h.continuous_on⟩⟩ lemma diff_cont_on_cl_univ : diff_cont_on_cl 𝕜 f univ ↔ differentiable 𝕜 f := is_closed_univ.diff_cont_on_cl_iff.trans differentiable_on_univ lemma diff_cont_on_cl_const {c : F} : diff_cont_on_cl 𝕜 (λ x : E, c) s := ⟨differentiable_on_const c, continuous_on_const⟩ namespace diff_cont_on_cl lemma comp {g : G → E} {t : set G} (hf : diff_cont_on_cl 𝕜 f s) (hg : diff_cont_on_cl 𝕜 g t) (h : maps_to g t s) : diff_cont_on_cl 𝕜 (f ∘ g) t := ⟨hf.1.comp hg.1 h, hf.2.comp hg.2 $ h.closure_of_continuous_on hg.2⟩ lemma continuous_on_ball [normed_space ℝ E] {x : E} {r : ℝ} (h : diff_cont_on_cl 𝕜 f (ball x r)) : continuous_on f (closed_ball x r) := begin rcases eq_or_ne r 0 with rfl|hr, { rw closed_ball_zero, exact continuous_on_singleton f x }, { rw ← closure_ball x hr, exact h.continuous_on } end lemma mk_ball {x : E} {r : ℝ} (hd : differentiable_on 𝕜 f (ball x r)) (hc : continuous_on f (closed_ball x r)) : diff_cont_on_cl 𝕜 f (ball x r) := ⟨hd, hc.mono $ closure_ball_subset_closed_ball⟩ protected lemma differentiable_at (h : diff_cont_on_cl 𝕜 f s) (hs : is_open s) (hx : x ∈ s) : differentiable_at 𝕜 f x := h.differentiable_on.differentiable_at $ hs.mem_nhds hx lemma differentiable_at' (h : diff_cont_on_cl 𝕜 f s) (hx : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.differentiable_on.differentiable_at hx protected lemma mono (h : diff_cont_on_cl 𝕜 f s) (ht : t ⊆ s) : diff_cont_on_cl 𝕜 f t := ⟨h.differentiable_on.mono ht, h.continuous_on.mono (closure_mono ht)⟩ lemma add (hf : diff_cont_on_cl 𝕜 f s) (hg : diff_cont_on_cl 𝕜 g s) : diff_cont_on_cl 𝕜 (f + g) s := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ lemma add_const (hf : diff_cont_on_cl 𝕜 f s) (c : F) : diff_cont_on_cl 𝕜 (λ x, f x + c) s := hf.add diff_cont_on_cl_const lemma const_add (hf : diff_cont_on_cl 𝕜 f s) (c : F) : diff_cont_on_cl 𝕜 (λ x, c + f x) s := diff_cont_on_cl_const.add hf lemma neg (hf : diff_cont_on_cl 𝕜 f s) : diff_cont_on_cl 𝕜 (-f) s := ⟨hf.1.neg, hf.2.neg⟩ lemma sub (hf : diff_cont_on_cl 𝕜 f s) (hg : diff_cont_on_cl 𝕜 g s) : diff_cont_on_cl 𝕜 (f - g) s := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ lemma sub_const (hf : diff_cont_on_cl 𝕜 f s) (c : F) : diff_cont_on_cl 𝕜 (λ x, f x - c) s := hf.sub diff_cont_on_cl_const lemma const_sub (hf : diff_cont_on_cl 𝕜 f s) (c : F) : diff_cont_on_cl 𝕜 (λ x, c - f x) s := diff_cont_on_cl_const.sub hf lemma const_smul {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F] [has_continuous_const_smul R F] (hf : diff_cont_on_cl 𝕜 f s) (c : R) : diff_cont_on_cl 𝕜 (c • f) s := ⟨hf.1.const_smul c, hf.2.const_smul c⟩ lemma smul {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : E → 𝕜'} {f : E → F} {s : set E} (hc : diff_cont_on_cl 𝕜 c s) (hf : diff_cont_on_cl 𝕜 f s) : diff_cont_on_cl 𝕜 (λ x, c x • f x) s := ⟨hc.1.smul hf.1, hc.2.smul hf.2⟩ lemma smul_const {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : E → 𝕜'} {s : set E} (hc : diff_cont_on_cl 𝕜 c s) (y : F) : diff_cont_on_cl 𝕜 (λ x, c x • y) s := hc.smul diff_cont_on_cl_const lemma inv {f : E → 𝕜} (hf : diff_cont_on_cl 𝕜 f s) (h₀ : ∀ x ∈ closure s, f x ≠ 0) : diff_cont_on_cl 𝕜 f⁻¹ s := ⟨differentiable_on_inv.comp hf.1 $ λ x hx, h₀ _ (subset_closure hx), hf.2.inv₀ h₀⟩ end diff_cont_on_cl lemma differentiable.comp_diff_cont_on_cl {g : G → E} {t : set G} (hf : differentiable 𝕜 f) (hg : diff_cont_on_cl 𝕜 g t) : diff_cont_on_cl 𝕜 (f ∘ g) t := hf.diff_cont_on_cl.comp hg (maps_to_image _ _) lemma differentiable_on.diff_cont_on_cl_ball {U : set E} {c : E} {R : ℝ} (hf : differentiable_on 𝕜 f U) (hc : closed_ball c R ⊆ U) : diff_cont_on_cl 𝕜 f (ball c R) := diff_cont_on_cl.mk_ball (hf.mono (ball_subset_closed_ball.trans hc)) (hf.continuous_on.mono hc)
14e7b73d6adaec9cc396cf00dd46c945831a6b23
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/impbug4.lean
a5c09866e337108384070c2cb2f36165d389333b
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
610
lean
prelude -- category definition Prop := Type.{0} constant eq {A : Type} : A → A → Prop infix `=`:50 := eq constant ob : Type.{1} constant mor : ob → ob → Type.{1} inductive category : Type := mk : Π (id : Π (A : ob), mor A A), (Π (A B : ob) (f : mor A A), id A = f) → category definition id (Cat : category) := category.rec (λ id idl, id) Cat constant Cat : category print "-----------------" theorem id_left (A : ob) (f : mor A A) : @eq (mor A A) (id Cat A) f := @category.rec (λ (C : category), Π (A B : ob) (f : mor A A), @eq (mor A A) (id C A) f) (λ id idl, idl) Cat A A f
acdb028f8d25197144b42b454ad70e33aa932280
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/irCompilerBug.lean
50f35432644156337f9f0c55062aa9e3e041e4b8
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
803
lean
new_frontend structure Payload := (key : Nat) (val : Nat) @[noinline] def get? (p : Payload) (k : Nat) : Option Nat := if p.key == k then p.val else none inductive T | a (i : Nat) | b (i : Nat) | c (i : Nat) | d (i : Nat) @[noinline] def foo (p : Payload) : Option T := (do let i ← get? p 1; pure (T.a i)) <|> (do let i ← get? p 2; pure (T.b i)) <|> (do let i ← get? p 3; pure (T.c i)) <|> (do let i ← get? p 4; let i ← get? p 5; pure (T.d i)) def wrongOutput : String := match foo (Payload.mk 1 20) with | some (t : T) => match t with | T.a i => "1: " ++ toString i | T.b i => "2: " ++ toString i | T.c i => "3: " ++ toString i | T.d i => "4: " ++ toString i | none => "5" #eval wrongOutput def main (xs : List String) : IO Unit := IO.println wrongOutput
0264bbca9db5b48c467a959eef4bfbecb47c9248
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/multiset.lean
bbe2210b74a1af9806e7f5236c0f1f5cfc6b22f9
[ "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
135,136
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.equiv.basic data.list.basic data.list.perm data.list.sort data.quot data.string.basic algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} open_locale add_monoid /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul]; cc @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (add_monoid.smul n m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α → β) [is_monoid_hom f] : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left' ih) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- antidiagonal -/ theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem antidiagonal_coe (l : list α) : @antidiagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem antidiagonal_coe' (l : list α) : @antidiagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ x.1 + x.2 = s := quotient.induction_on s $ λ l, begin simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], cases x with x₁ x₂, exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩ end @[simp] theorem antidiagonal_map_fst (s : multiset α) : (antidiagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_map_snd (s : multiset α) : (antidiagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl @[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_antidiagonal (s : multiset α) : card (antidiagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← antidiagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm], cc }, end /- powerset_len -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact perm_app IH (perm_map _ (IHn p)) }, { simp, apply perm_app_right, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = 0::0 := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a::s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h)) /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono h lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (nodup_ext ht (nodup_map (show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy)) (nodup_attach.2 hs))).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _) section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _, λ h, h.symm ▸ erase_dup_zero⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp, priority 980] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp, priority 980] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp, priority 980] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp, priority 980] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_ndinsert_left]; tauto /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp, priority 980] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp, priority 980] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp, priority 980] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter @[simp] theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp, priority 980] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] @[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card := quot.induction_on s $ length_merge_sort _ end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, x::0, bind := @bind, .. multiset.functor } instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by rw [bind_cons, map_cons, bind_zero, add_zero], pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero], bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := congr_arg coe $ list.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := congr_arg coe $ list.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := congr_arg coe $ list.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_le n m l end Ico variable (α) def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } namespace nat /-- The antidiagonal of a natural number `n` is the multiset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) := list.nat.antidiagonal n /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by rw [antidiagonal, coe_card, list.nat.length_antidiagonal] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, list.nat.antidiagonal_zero], refl } /-- The antidiagonal of `n` does not contain duplicate entries. -/ @[simp] lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := coe_nodup.2 $ list.nat.nodup_antidiagonal n end nat end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
996ab99c956c08689fb75e0038f24aefe21aaffe
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Meta/DiscrTree.lean
f8bbaaeee8e64aeb4e09624c950470dd505051d9
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,998
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 -/ prelude import Init.Lean.Meta.Basic import Init.Lean.Meta.FunInfo import Init.Lean.Meta.InferType namespace Lean namespace Meta namespace DiscrTree /- (Imperfect) discrimination trees. We use a hybrid representation. - A `PersistentHashMap` for the root node which usually contains many children. - A sorted array of key/node pairs for inner nodes. The edges are labeled by keys: - Constant names (and arity). Universe levels are ignored. - Free variables (and arity). Thus, an entry in the discrimination tree may reference hypotheses from the local context. - Literals - Star/Wildcard. We use them to represent metavariables and terms we want to ignore. We ignore implicit arguments and proofs. - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc). We reduce terms using `TransparencyMode.reducible`. Thus, all reducible definitions in an expression `e` are unfolded before we insert it into the discrimination tree. Recall that projections from classes are **NOT** reducible. For example, the expressions `HasAdd.add α (ringHasAdd ?α ?s) ?x ?x` and `HasAdd.add Nat Nat.hasAdd a b` generates paths with the following keys respctively ``` ⟨HasAdd.add, 4⟩, *, *, *, * ⟨HasAdd.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩ ``` That is, we don't reduce `HasAdd.add Nat Nat.HasAdd a b` into `Nat.add a b`. We say the `HasAdd.add` applications are the de-facto canonical forms in the metaprogramming framework. Moreover, it is the metaprammer resposability to re-pack applications such as `Nat.add a b` into `HasAdd.add Nat Nat.hasAdd a b`. Remark: we store the arity in the keys 1- To be able to implement the "skip" operation when retrieving "candidate" unifiers. 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`. -/ def Key.ctorIdx : Key → Nat | Key.star => 0 | Key.other => 1 | Key.lit _ => 2 | Key.fvar _ _ => 3 | Key.const _ _ => 4 def Key.lt : Key → Key → Bool | Key.lit v₁, Key.lit v₂ => v₁ < v₂ | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx instance Key.hasLess : HasLess Key := ⟨fun a b => Key.lt a b⟩ def Key.format : Key → Format | Key.star => "*" | Key.other => "◾" | Key.lit (Literal.natVal v) => fmt v | Key.lit (Literal.strVal v) => repr v | Key.const k _ => fmt k | Key.fvar k _ => fmt k instance Key.hasFormat : HasFormat Key := ⟨Key.format⟩ def Key.arity : Key → Nat | Key.const _ a => a | Key.fvar _ a => a | _ => 0 instance Trie.inhabited {α} : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩ def empty {α} : DiscrTree α := { root := {} } /- The discrimination tree ignores implicit arguments and proofs. We use the following auxiliary id as a "mark". -/ private def tmpMVarId : MVarId := `_discr_tree_tmp private def tmpStar := mkMVar tmpMVarId instance {α} : Inhabited (DiscrTree α) := ⟨{}⟩ /-- Return true iff the argument should be treated as a "wildcard" by the discrimination tree. - We ignore proofs because of proof irrelevance. It doesn't make sense to try to index their structure. - We ignore instance implicit arguments (e.g., `[HasAdd α]`) because they are "morally" canonical. Moreover, we may have many definitionally equal terms floating around. Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`. - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them, and may not even understand why some simplification rule is not firing. However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`, where `Nat` is an implicit argument. Thus, we would add the path ``` Decidable -> Eq -> * -> * -> * -> [Nat.decEq] ``` to the discrimination tree IF we ignored the implict `Nat` argument. This would be BAD since **ALL** decidable equality instances would be in the same path. So, we index implicit arguments if they are types. This setting seems sensible for simplification lemmas such as: ``` forall (x y : Unit), (@Eq Unit x y) = true ``` If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate simplification lemma for any equality in our goal. Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation, and `ignoreArg` would return true for any term of the form `noIndexing t`. -/ private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := if h : i < infos.size then let info := infos.get ⟨i, h⟩; if info.instImplicit then pure true else if info.implicit then not <$> isType a else isProof a else isProof a private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr) | i, Expr.app f a _, todo => condM (ignoreArg a i infos) (pushArgsAux (i-1) f (todo.push tmpStar)) (pushArgsAux (i-1) f (todo.push a)) | _, _, todo => pure todo private partial def whnfEta : Expr → MetaM Expr | e => do e ← whnf e; match e.etaExpandedStrict? with | some e => whnfEta e | none => pure e private def pushArgs (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do e ← whnfEta e; let fn := e.getAppFn; let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do { info ← getFunInfoNArgs fn nargs; todo ← pushArgsAux info.paramInfo (nargs-1) e todo; pure (k, todo) }; match fn with | Expr.lit v _ => pure (Key.lit v, todo) | Expr.const c _ _ => let nargs := e.getAppNumArgs; push (Key.const c nargs) nargs | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs; push (Key.fvar fvarId nargs) nargs | Expr.mvar mvarId _ => if mvarId == tmpMVarId then -- We use `tmp to mark implicit arguments and proofs pure (Key.star, todo) else condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId) (pure (Key.other, todo)) (pure (Key.star, todo)) | _ => pure (Key.other, todo) partial def mkPathAux : Array Expr → Array Key → MetaM (Array Key) | todo, keys => if todo.isEmpty then pure keys else do let e := todo.back; let todo := todo.pop; (k, todo) ← pushArgs todo e; mkPathAux todo (keys.push k) private def initCapacity := 8 def mkPath (e : Expr) : MetaM (Array Key) := withTransparency TransparencyMode.reducible $ do let todo : Array Expr := Array.mkEmpty initCapacity; let keys : Array Key := Array.mkEmpty initCapacity; mkPathAux (todo.push e) keys private partial def createNodes {α} (keys : Array Key) (v : α) : Nat → Trie α | i => if h : i < keys.size then let k := keys.get ⟨i, h⟩; let c := createNodes (i+1); Trie.node #[] #[(k, c)] else Trie.node #[v] #[] private def insertVal {α} [HasBeq α] (vs : Array α) (v : α) : Array α := if vs.contains v then vs else vs.push v private partial def insertAux {α} [HasBeq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α | i, Trie.node vs cs => if h : i < keys.size then let k := keys.get ⟨i, h⟩; let c := Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => let c := insertAux (i+1) s; (k, c)) -- merge with existing (fun _ => let c := createNodes keys v (i+1); (k, c)) (k, arbitrary _); Trie.node vs c else Trie.node (insertVal vs v) cs def insertCore {α} [HasBeq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α := if keys.isEmpty then panic! "invalid key sequence" else let k := keys.get! 0; match d.root.find? k with | none => let c := createNodes keys v 1; { root := d.root.insert k c } | some c => let c := insertAux keys v 1 c; { root := d.root.insert k c } def insert {α} [HasBeq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do keys ← mkPath e; pure $ d.insertCore keys v partial def Trie.format {α} [HasFormat α] : Trie α → Format | Trie.node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ Trie.format c)) instance Trie.hasFormat {α} [HasFormat α] : HasFormat (Trie α) := ⟨Trie.format⟩ partial def format {α} [HasFormat α] (d : DiscrTree α) : Format := let (_, r) := d.root.foldl (fun (p : Bool × Format) k c => (false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (fmt k ++ " => " ++ fmt c))) (true, Format.nil); Format.group r instance DiscrTree.hasFormat {α} [HasFormat α] : HasFormat (DiscrTree α) := ⟨format⟩ private def getKeyArgs (e : Expr) (isMatch? : Bool) : MetaM (Key × Array Expr) := do e ← whnfEta e; match e.getAppFn with | Expr.lit v _ => pure (Key.lit v, #[]) | Expr.const c _ _ => let nargs := e.getAppNumArgs; pure (Key.const c nargs, e.getAppRevArgs) | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs; pure (Key.fvar fvarId nargs, e.getAppRevArgs) | Expr.mvar mvarId _ => if isMatch? then pure (Key.other, #[]) else do ctx ← read; if ctx.config.isDefEqStuckEx then /- When the configuration flag `isDefEqStuckEx` is set to true, we want `isDefEq` to throw an exception whenever it tries to assign a read-only metavariable. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`. That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (HasAdd ?m)` where `?m` is a read-only metavariable, and the discrimination tree contains the keys `HadAdd Nat` and `HasAdd Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as a regular metavariable here, otherwise we return the empty set of candidates. This is incorrect because it is equivalent to saying that there is no solution even if the caller assigns `?m` and try again. -/ pure (Key.star, #[]) else condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId) (pure (Key.other, #[])) (pure (Key.star, #[])) | _ => pure (Key.other, #[]) private abbrev getMatchKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e true private abbrev getUnifyKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e false private partial def getMatchAux {α} : Array Expr → Trie α → Array α → MetaM (Array α) | todo, Trie.node vs cs, result => if todo.isEmpty then pure $ result ++ vs else if cs.isEmpty then pure result else do let e := todo.back; let todo := todo.pop; let first := cs.get! 0; /- Recall that `Key.star` is the minimal key -/ (k, args) ← getMatchKeyArgs e; /- We must always visit `Key.star` edges since they are wildcards. Thus, `todo` is not used linearly when there is `Key.star` edge and there is an edge for `k` and `k != Key.star`. -/ let visitStarChild (result : Array α) : MetaM (Array α) := if first.1 == Key.star then getMatchAux todo first.2 result else pure result; match k with | Key.star => visitStarChild result | _ => match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with | none => visitStarChild result | some c => do result ← visitStarChild result; getMatchAux (todo ++ args) c.2 result private def getStarResult {α} (d : DiscrTree α) : Array α := let result : Array α := Array.mkEmpty initCapacity; match d.root.find? Key.star with | none => result | some (Trie.node vs _) => result ++ vs def getMatch {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withTransparency TransparencyMode.reducible $ do let result := getStarResult d; (k, args) ← getMatchKeyArgs e; match k with | Key.star => pure result | _ => match d.root.find? k with | none => pure result | some c => getMatchAux args c result private partial def getUnifyAux {α} : Nat → Array Expr → Trie α → (Array α) → MetaM (Array α) | skip+1, todo, Trie.node vs cs, result => if cs.isEmpty then pure result else cs.foldlM (fun result ⟨k, c⟩ => getUnifyAux (skip + k.arity) todo c result) result | 0, todo, Trie.node vs cs, result => if todo.isEmpty then pure (result ++ vs) else if cs.isEmpty then pure result else do let e := todo.back; let todo := todo.pop; (k, args) ← getUnifyKeyArgs e; match k with | Key.star => cs.foldlM (fun result ⟨k, c⟩ => getUnifyAux k.arity todo c result) result | _ => let first := cs.get! 0; let visitStarChild (result : Array α) : MetaM (Array α) := if first.1 == Key.star then getUnifyAux 0 todo first.2 result else pure result; match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with | none => visitStarChild result | some c => do result ← visitStarChild result; getUnifyAux 0 (todo ++ args) c.2 result def getUnify {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withTransparency TransparencyMode.reducible $ do (k, args) ← getUnifyKeyArgs e; match k with | Key.star => d.root.foldlM (fun result k c => getUnifyAux k.arity #[] c result) #[] | _ => let result := getStarResult d; match d.root.find? k with | none => pure result | some c => getUnifyAux 0 args c result end DiscrTree end Meta end Lean
bd924d6c008eac9611de110d6156f6df4c9566eb
e2fc96178628c7451e998a0db2b73877d0648be5
/src/classes/context_free/closure_properties/union.lean
0a3d9985cef91175f77b9e318d8d764d63ce8819
[ "BSD-2-Clause" ]
permissive
madvorak/grammars
cd324ae19b28f7b8be9c3ad010ef7bf0fabe5df2
1447343a45fcb7821070f1e20b57288d437323a6
refs/heads/main
1,692,383,644,884
1,692,032,429,000
1,692,032,429,000
453,948,141
7
0
null
null
null
null
UTF-8
Lean
false
false
17,777
lean
import classes.context_free.basics.lifting variables {T : Type} private def union_grammar (g₁ g₂ : CF_grammar T) : CF_grammar T := CF_grammar.mk (option (g₁.nt ⊕ g₂.nt)) none ( (none, [symbol.nonterminal (some (sum.inl (g₁.initial)))]) :: (none, [symbol.nonterminal (some (sum.inr (g₂.initial)))]) :: ((list.map rule_of_rule₁ g₁.rules) ++ (list.map rule_of_rule₂ g₂.rules)) ) variables {g₁ g₂ : CF_grammar T} section lifted_grammars private def oN₁_of_N : (union_grammar g₁ g₂).nt → (option g₁.nt) | none := none | (some (sum.inl nonte)) := some nonte | (some (sum.inr _)) := none private def oN₂_of_N : (union_grammar g₁ g₂).nt → (option g₂.nt) | none := none | (some (sum.inl _)) := none | (some (sum.inr nonte)) := some nonte private def g₁g : @lifted_grammar T := lifted_grammar.mk g₁ (union_grammar g₁ g₂) (some ∘ sum.inl) (by { intros x y h, apply sum.inl_injective, apply option.some_injective, exact h, }) (by { intros r h, apply list.mem_cons_of_mem, apply list.mem_cons_of_mem, apply list.mem_append_left, rw list.mem_map, use r, split, { exact h, }, unfold rule_of_rule₁, unfold lift_rule, norm_num, unfold lift_string, unfold lsTN_of_lsTN₁, five_steps, }) oN₁_of_N (by { intros x y ass, cases x, { right, refl, }, cases x, swap, { right, refl, }, cases y, { rw ass, right, refl, }, cases y, swap, { tauto, }, left, simp only [oN₁_of_N] at ass, apply congr_arg, apply congr_arg, exact ass, }) (by { intro r, rintro ⟨r_in, r_ntype⟩, cases r_in, { exfalso, rw r_in at r_ntype, dsimp only at r_ntype, cases r_ntype with n₀ imposs, exact option.no_confusion imposs, }, cases r_in, { exfalso, rw r_in at r_ntype, dsimp only at r_ntype, cases r_ntype with n₀ imposs, exact option.no_confusion imposs, }, change r ∈ (list.map rule_of_rule₁ g₁.rules ++ list.map rule_of_rule₂ g₂.rules) at r_in, rw list.mem_append at r_in, cases r_in, { rw list.mem_map at r_in, rcases r_in with ⟨r₁, r₁_in, r₁_convert_r⟩, use r₁, split, { exact r₁_in, }, rw ←r₁_convert_r, simp only [ lift_rule, rule_of_rule₁, lift_string, lsTN_of_lsTN₁, prod.mk.inj_iff, eq_self_iff_true, true_and ], five_steps, }, { exfalso, rw list.mem_map at r_in, rcases r_in with ⟨r₂, r₂_in, r₂_convert_r⟩, rw ←r₂_convert_r at r_ntype, unfold rule_of_rule₂ at r_ntype, dsimp only at r_ntype, cases r_ntype with n₁ contr, rw option.some_inj at contr, exact sum.no_confusion contr, }, }) (by { intro, refl }) private def g₂g : @lifted_grammar T := lifted_grammar.mk g₂ (union_grammar g₁ g₂) (some ∘ sum.inr) (by { intros x y h, apply sum.inr_injective, apply option.some_injective, exact h, }) (by { intros r h, apply list.mem_cons_of_mem, apply list.mem_cons_of_mem, apply list.mem_append_right, rw list.mem_map, use r, split, { exact h, }, unfold rule_of_rule₂, unfold lift_rule, norm_num, unfold lift_string, unfold lsTN_of_lsTN₂, five_steps, }) oN₂_of_N (by { intros x y ass, cases x, { right, refl, }, cases x, { right, refl, }, cases y, { right, rw ass, refl, }, cases y, { tauto, }, left, simp only [oN₂_of_N] at ass, apply congr_arg, apply congr_arg, exact ass, }) (by { intro r, rintro ⟨r_in, r_ntype⟩, cases list.eq_or_mem_of_mem_cons r_in with r_eq r_in_, { exfalso, rw r_eq at r_ntype, dsimp only at r_ntype, cases r_ntype with n₀ imposs, exact option.no_confusion imposs, }, cases list.eq_or_mem_of_mem_cons r_in_ with r_eq_ r_in__, { exfalso, rw r_eq_ at r_ntype, dsimp only at r_ntype, cases r_ntype with n₀ imposs, exact option.no_confusion imposs, }, clear r_in r_in_, rename r_in__ r_in, rw list.mem_append at r_in, cases r_in, { exfalso, rw list.mem_map at r_in, rcases r_in with ⟨r₁, r₁_in, r₁_convert_r⟩, rw ←r₁_convert_r at r_ntype, unfold rule_of_rule₁ at r_ntype, dsimp only at r_ntype, cases r_ntype with n₂ contr, rw option.some_inj at contr, exact sum.no_confusion contr, }, { rw list.mem_map at r_in, rcases r_in with ⟨r₂, r₂_in, r₂_convert_r⟩, use r₂, split, { exact r₂_in, }, rw ←r₂_convert_r, simp only [ lift_rule, rule_of_rule₂, lift_string, lsTN_of_lsTN₂, prod.mk.inj_iff, eq_self_iff_true, true_and ], five_steps, }, }) (by { intro, refl }) end lifted_grammars section lemmata_subset private lemma deri₁_more (w : list (symbol T g₁.nt)) : CF_derives g₁ [symbol.nonterminal g₁.initial] w → CF_derives (union_grammar g₁ g₂) (lsTN_of_lsTN₁ [symbol.nonterminal g₁.initial]) (lsTN_of_lsTN₁ w) := begin intro ass, let gg₁ := @g₁g T g₁ g₂, change CF_derives gg₁.g (lsTN_of_lsTN₁ [symbol.nonterminal g₁.initial]) (lsTN_of_lsTN₁ w), have techni : lsTN_of_lsTN₁ = lift_string gg₁.lift_nt, { unfold lsTN_of_lsTN₁, unfold lift_string, ext1 w, five_steps, }, rw techni, exact lift_deri ass, end private lemma deri₂_more (w : list (symbol T g₂.nt)) : CF_derives g₂ [symbol.nonterminal g₂.initial] w → CF_derives (union_grammar g₁ g₂) (lsTN_of_lsTN₂ [symbol.nonterminal g₂.initial]) (lsTN_of_lsTN₂ w) := begin intro ass, let gg₂ := @g₂g T g₁ g₂, change CF_derives gg₂.g (lsTN_of_lsTN₂ [symbol.nonterminal g₂.initial]) (lsTN_of_lsTN₂ w), have techni : lsTN_of_lsTN₂ = lift_string gg₂.lift_nt, { unfold lsTN_of_lsTN₂, unfold lift_string, ext1 w, five_steps, }, rw techni, exact lift_deri ass, end private lemma in_union_of_in_first (w : list T) : w ∈ CF_language g₁ → w ∈ CF_language (union_grammar g₁ g₂) := begin intro assum, have deri_start : CF_derives (union_grammar g₁ g₂) [symbol.nonterminal none] [symbol.nonterminal (some (sum.inl g₁.initial))], { apply CF_deri_of_tran, use (none, [symbol.nonterminal (some (sum.inl (g₁.initial)))]), split, { change (none, [symbol.nonterminal (some (sum.inl g₁.initial))]) ∈ ( (none, [symbol.nonterminal (some (sum.inl (g₁.initial)))]) :: (none, [symbol.nonterminal (some (sum.inr (g₂.initial)))]) :: ((list.map rule_of_rule₁ g₁.rules) ++ (list.map rule_of_rule₂ g₂.rules)) ), apply list.mem_cons_self, }, use [[], []], simp, }, have deri_rest : CF_derives (union_grammar g₁ g₂) [symbol.nonterminal (some (sum.inl g₁.initial))] (list.map symbol.terminal w), { have beginning : [symbol.nonterminal (some (sum.inl g₁.initial))] = lsTN_of_lsTN₁ [symbol.nonterminal g₁.initial], { unfold lsTN_of_lsTN₁, change [symbol.nonterminal (some (sum.inl g₁.initial))] = [sTN_of_sTN₁ (symbol.nonterminal g₁.initial)], unfold sTN_of_sTN₁, }, have ending : (list.map symbol.terminal w) = lsTN_of_lsTN₁ (list.map symbol.terminal w), { ext1, unfold lsTN_of_lsTN₁, rw [list.nth_map, list.map_map, list.nth_map], apply congr_arg, refl, }, rw beginning, rw ending, exact deri₁_more (list.map symbol.terminal w) assum, }, unfold CF_language, rw set.mem_set_of_eq, unfold CF_generates, unfold CF_generates_str, unfold CF_derives, apply CF_deri_of_deri_deri deri_start, exact deri_rest, end private lemma in_union_of_in_second (w : list T) : w ∈ CF_language g₂ → w ∈ CF_language (union_grammar g₁ g₂) := begin intro assum, have deri_start : CF_derives (union_grammar g₁ g₂) [symbol.nonterminal none] [symbol.nonterminal (some (sum.inr g₂.initial))], { apply CF_deri_of_tran, use (none, [symbol.nonterminal (some (sum.inr (g₂.initial)))]), split, { change (none, [symbol.nonterminal (some (sum.inr g₂.initial))]) ∈ ( (none, [symbol.nonterminal (some (sum.inl (g₁.initial)))]) :: (none, [symbol.nonterminal (some (sum.inr (g₂.initial)))]) :: ((list.map rule_of_rule₁ g₁.rules) ++ (list.map rule_of_rule₂ g₂.rules)) ), apply list.mem_cons_of_mem, apply list.mem_cons_self, }, use [[], []], simp, }, have deri_rest : CF_derives (union_grammar g₁ g₂) [symbol.nonterminal (some (sum.inr g₂.initial))] (list.map symbol.terminal w), { have beginning : [symbol.nonterminal (some (sum.inr g₂.initial))] = lsTN_of_lsTN₂ [symbol.nonterminal g₂.initial], { unfold lsTN_of_lsTN₂, change [symbol.nonterminal (some (sum.inr g₂.initial))] = [sTN_of_sTN₂ (symbol.nonterminal g₂.initial)], unfold sTN_of_sTN₂, }, have ending : (list.map symbol.terminal w) = lsTN_of_lsTN₂ (list.map symbol.terminal w), { ext1, unfold lsTN_of_lsTN₂, rw [list.nth_map, list.map_map, list.nth_map], apply congr_arg, refl, }, rw beginning, rw ending, exact deri₂_more (list.map symbol.terminal w) assum, }, unfold CF_language, rw set.mem_set_of_eq, unfold CF_generates, unfold CF_generates_str, unfold CF_derives, apply CF_deri_of_deri_deri deri_start, exact deri_rest, end end lemmata_subset section lemmata_supset meta def good_singleton : tactic unit := `[ unfold good_string, intros a in_singleton, rw list.mem_singleton at in_singleton, rw in_singleton, unfold good_letter ] private lemma in_language_left_case_of_union {w : list T} (hypo : CF_derives (union_grammar g₁ g₂) [symbol.nonterminal (some (sum.inl g₁.initial))] (list.map symbol.terminal w)) : w ∈ CF_language g₁ := begin unfold CF_language, rw set.mem_set_of_eq, unfold CF_generates, unfold CF_generates_str, let gg₁ := @g₁g T g₁ g₂, have bar : [symbol.nonterminal g₁.initial] = (sink_string gg₁.sink_nt [symbol.nonterminal (some (sum.inl g₁.initial))]), { unfold sink_string, refl, }, rw bar, have baz : list.map symbol.terminal w = sink_string gg₁.sink_nt (list.map symbol.terminal w), { unfold sink_string, rw list.filter_map_map, change list.map symbol.terminal w = list.filter_map (λ x, (sink_symbol gg₁.sink_nt ∘ symbol.terminal) x) w, convert_to list.map symbol.terminal w = list.filter_map (λ x, option.some (symbol.terminal x)) w, change list.map symbol.terminal w = list.filter_map (option.some ∘ symbol.terminal) w, clear hypo, induction w with d l, { refl, }, rw list.map, convert_to symbol.terminal d :: list.map symbol.terminal l = symbol.terminal d :: list.filter_map (some ∘ symbol.terminal) l, norm_num, exact w_ih, }, rw baz, exact (sink_deri gg₁ [symbol.nonterminal (some (sum.inl g₁.initial))] (list.map symbol.terminal w) hypo (by { good_singleton, use g₁.initial, refl, })).left, end private lemma in_language_right_case_of_union {w : list T} (hypo : CF_derives (union_grammar g₁ g₂) [symbol.nonterminal (some (sum.inr g₂.initial))] (list.map symbol.terminal w)) : w ∈ CF_language g₂ := begin unfold CF_language, rw set.mem_set_of_eq, unfold CF_generates, unfold CF_generates_str, let gg₂ := @g₂g T g₁ g₂, have bar : [symbol.nonterminal g₂.initial] = (sink_string gg₂.sink_nt [symbol.nonterminal (some (sum.inr g₂.initial))]), { unfold sink_string, refl, }, rw bar, have baz : list.map symbol.terminal w = sink_string gg₂.sink_nt (list.map symbol.terminal w), { unfold sink_string, rw list.filter_map_map, change list.map symbol.terminal w = list.filter_map (λ x, (sink_symbol gg₂.sink_nt ∘ symbol.terminal) x) w, convert_to list.map symbol.terminal w = list.filter_map (λ x, option.some (symbol.terminal x)) w, change list.map symbol.terminal w = list.filter_map (option.some ∘ symbol.terminal) w, clear hypo, induction w with d l, { refl, }, rw list.map, convert_to symbol.terminal d :: list.map symbol.terminal l = symbol.terminal d :: list.filter_map (some ∘ symbol.terminal) l, norm_num, exact w_ih, }, rw baz, exact (sink_deri gg₂ [symbol.nonterminal (some (sum.inr g₂.initial))] (list.map symbol.terminal w) hypo (by { good_singleton, use g₂.initial, refl, })).left, end private lemma both_empty (u v: list (symbol T (union_grammar g₁ g₂).nt)) (a : (symbol T (union_grammar g₁ g₂).nt)) (bef: [symbol.nonterminal (union_grammar g₁ g₂).initial] = u ++ [a] ++ v) : u = [] ∧ v = [] := begin have len := congr_arg list.length bef, rw [list.length_singleton, list.length_append, list.length_append, list.length_singleton] at len, split, { by_contradiction, rw ←list.length_eq_zero at h, exact nat.not_succ_le_self 1 (by calc 1 = (u.length + 1) + v.length : len ... = u.length + (1 + v.length) : add_assoc (list.length u) 1 (list.length v) ... ≥ 1 + (1 + v.length) : add_le_add (nat.one_le_iff_ne_zero.mpr h) (le_of_eq rfl) ... = (1 + 1) + v.length : eq.symm (add_assoc 1 1 (list.length v)) ... ≥ 1 + 1 + 0 : le_self_add ... = 2 : rfl), }, { by_contradiction, rw ←list.length_eq_zero at h, exact nat.not_succ_le_self 1 (by calc 1 = (u.length + 1) + v.length : len ... ≥ (u.length + 1) + 1 : add_le_add (le_of_eq rfl) (nat.one_le_iff_ne_zero.mpr h) ... = u.length + (1 + 1) : add_assoc (list.length u) 1 1 ... ≥ 0 + (1 + 1) : le_add_self ... = (0 + 1) + 1 : eq.symm (add_assoc 0 1 1) ... = 2 : rfl), }, end private lemma in_language_impossible_case_of_union (w : list T) (r : (union_grammar g₁ g₂).nt × list (symbol T (union_grammar g₁ g₂).nt)) (u v: list (symbol T (union_grammar g₁ g₂).nt)) (hu : u = []) (hv : v = []) (bef: [symbol.nonterminal (union_grammar g₁ g₂).initial] = u ++ [symbol.nonterminal r.fst] ++ v) (sbi : r ∈ (list.map rule_of_rule₁ g₁.rules ++ list.map rule_of_rule₂ g₂.rules)) : w ∈ CF_language g₁ ∨ w ∈ CF_language g₂ := begin exfalso, rw [hu, hv] at bef, rw [list.nil_append, list.append_nil] at bef, change [symbol.nonterminal none] = [symbol.nonterminal r.fst] at bef, have rule_root : r.fst = none, { have almost := list.head_eq_of_cons_eq bef, exact symbol.nonterminal.inj almost.symm, }, rw list.mem_append at sbi, cases sbi, { rw list.mem_map at sbi, rcases sbi with ⟨r₁, -, imposs⟩, unfold rule_of_rule₁ at imposs, rw ←imposs at rule_root, unfold prod.fst at rule_root, exact option.no_confusion rule_root, }, { rw list.mem_map at sbi, rcases sbi with ⟨r₂, -, imposs⟩, unfold rule_of_rule₂ at imposs, rw ←imposs at rule_root, unfold prod.fst at rule_root, exact option.no_confusion rule_root, }, end private lemma in_language_of_in_union (w : list T) : w ∈ CF_language (union_grammar g₁ g₂) → w ∈ CF_language g₁ ∨ w ∈ CF_language g₂ := begin intro ass, cases CF_tran_or_id_of_deri ass with impossible h, { exfalso, have zeroth := congr_arg (λ p, list.nth p 0) impossible, unfold list.nth at zeroth, rw list.nth_map at zeroth, cases (w.nth 0), { rw option.map_none' at zeroth, exact option.no_confusion zeroth, }, { rw option.map_some' at zeroth, exact symbol.no_confusion (option.some.inj zeroth), }, }, rcases h with ⟨S₁, deri_head, deri_tail⟩, rcases deri_head with ⟨rule, ruleok, u, v, h_bef, h_aft⟩, rw h_aft at deri_tail, cases both_empty u v (symbol.nonterminal rule.fst) h_bef with u_nil v_nil, cases ruleok with g₁S r_rest, { left, rw g₁S at *, rw u_nil at deri_tail, rw v_nil at deri_tail, rw list.nil_append at deri_tail, exact in_language_left_case_of_union deri_tail, }, cases r_rest with g₂S r_imposs, { right, rw g₂S at *, rw u_nil at deri_tail, rw v_nil at deri_tail, rw list.nil_append at deri_tail, exact in_language_right_case_of_union deri_tail, }, exact in_language_impossible_case_of_union w rule u v u_nil v_nil h_bef r_imposs, end end lemmata_supset /-- The class of context-free languages is closed under union. -/ theorem CF_of_CF_u_CF {T : Type} (L₁ : language T) (L₂ : language T) : is_CF L₁ ∧ is_CF L₂ → is_CF (L₁ + L₂) := begin rintro ⟨⟨g₁, eq_L₁⟩, ⟨g₂, eq_L₂⟩⟩, use union_grammar g₁ g₂, apply set.eq_of_subset_of_subset, { -- prove `L₁ + L₂ ⊇ ` intros w hyp, rw language.mem_add, rw ←eq_L₁, rw ←eq_L₂, exact in_language_of_in_union w hyp, }, { -- prove `L₁ + L₂ ⊆ ` intros w hyp, cases hyp with case₁ case₂, { rw ←eq_L₁ at case₁, exact in_union_of_in_first w case₁, }, { rw ←eq_L₂ at case₂, exact in_union_of_in_second w case₂, }, }, end
12915a79cf28e1cae70d99d11f7bc02f52b957c3
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/Check.lean
2dcfba5a2648686706b21b873dde23e71d5c0b8d
[ "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
3,561
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.InferType import Lean.Meta.LevelDefEq /- This is not the Kernel type checker, but an auxiliary method for checking whether terms produced by tactics and `isDefEq` are type correct. -/ namespace Lean.Meta private def ensureType (e : Expr) : MetaM Unit := do getLevel e pure () def throwLetTypeMismatchMessage {α} (fvarId : FVarId) : MetaM α := do let lctx ← getLCtx match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ n t v _) => do let vType ← inferType v throwError! "invalid let declaration, term{indentExpr v}\nhas type{indentExpr vType}\nbut is expected to have type{indentExpr t}" | _ => unreachable! private def checkConstant (constName : Name) (us : List Level) : MetaM Unit := do let cinfo ← getConstInfo constName unless us.length == cinfo.lparams.length do throwIncorrectNumberOfLevels constName us private def getFunctionDomain (f : Expr) : MetaM Expr := do let fType ← inferType f let fType ← whnfD fType match fType with | Expr.forallE _ d _ _ => pure d | _ => throwFunctionExpected f def throwAppTypeMismatch {α} {m} [Monad m] [MonadExceptOf Exception m] [MonadRef m] [AddErrorMessageContext m] [MonadLiftT MetaM m] (f a : Expr) (extraMsg : MessageData := Format.nil) : m α := do let e := mkApp f a let aType ← inferType a let expectedType ← liftM $ getFunctionDomain f throwError! "application type mismatch{indentExpr e}\nargument{indentExpr a}\nhas type{indentExpr aType}\nbut is expected to have type{indentExpr expectedType}{extraMsg}" def checkApp (f a : Expr) : MetaM Unit := do let fType ← inferType f let fType ← whnf fType match fType with | Expr.forallE _ d _ _ => let aType ← inferType a unless (← isDefEq d aType) do throwAppTypeMismatch f a | _ => throwFunctionExpected (mkApp f a) private partial def checkAux : Expr → MetaM Unit | e@(Expr.forallE ..) => checkForall e | e@(Expr.lam ..) => checkLambdaLet e | e@(Expr.letE ..) => checkLambdaLet e | Expr.const c lvls _ => checkConstant c lvls | Expr.app f a _ => do checkAux f; checkAux a; checkApp f a | Expr.mdata _ e _ => checkAux e | Expr.proj _ _ e _ => checkAux e | _ => pure () where checkLambdaLet (e : Expr) : MetaM Unit := lambdaLetTelescope e fun xs b => do xs.forM fun x => do let xDecl ← getFVarLocalDecl x; match xDecl with | LocalDecl.cdecl _ _ _ t _ => ensureType t checkAux t | LocalDecl.ldecl _ _ _ t v _ => ensureType t checkAux t let vType ← inferType v unless (← isDefEq t vType) do throwLetTypeMismatchMessage x.fvarId! checkAux v checkAux b checkForall (e : Expr) : MetaM Unit := forallTelescope e fun xs b => do xs.forM fun x => do let xDecl ← getFVarLocalDecl x ensureType xDecl.type checkAux xDecl.type ensureType b checkAux b def check (e : Expr) : MetaM Unit := traceCtx `Meta.check do withTransparency TransparencyMode.all $ checkAux e def isTypeCorrect (e : Expr) : MetaM Bool := do try check e pure true catch ex => trace[Meta.typeError]! ex.toMessageData pure false builtin_initialize registerTraceClass `Meta.check registerTraceClass `Meta.typeError end Lean.Meta
7e6c624dee53e9bf1aef9f857cd83ae5bae5af92
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/anonymousCtor.lean
1b0f56c9196bc9cac3db897b6d8342e2c06b312f
[ "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
83
lean
inductive S | mk : List S → String → S def f (s : String) : S := ⟨[], s⟩
86ec4c2ee9e9d4d603ee817cfb1bff2afbd040eb
4fa161becb8ce7378a709f5992a594764699e268
/src/order/zorn.lean
65512240d8a4ea6565281863a290cb9afa28a4a3
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
12,895
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 Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import data.set.lattice noncomputable theory universes u open set classical open_locale classical namespace zorn section chain parameters {α : Type u} (r : α → α → Prop) local infix ` ≺ `:50 := r /-- A chain is a subset `c` satisfying `x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/ def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) parameters {r} theorem chain.total_of_refl [is_refl α r] {c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) : x ≺ y ∨ y ≺ x := if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e theorem chain.mono {c c'} : c' ⊆ c → chain c → chain c' := pairwise_on.mono theorem chain.directed_on [is_refl α r] {c} (H : chain c) : directed_on (≺) c := assume x hx y hy, match H.total_of_refl hx hy with | or.inl h := ⟨y, hy, h, refl _⟩ | or.inr h := ⟨x, hx, refl _, h⟩ end theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) /-- `super_chain c₁ c₂` means that `c₂ is a chain that strictly includes `c₁`. -/ def super_chain (c₁ c₂ : set α) : Prop := chain c₂ ∧ c₁ ⊂ c₂ /-- A chain `c` is a maximal chain if there does not exists a chain strictly including `c`. -/ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') /-- Given a set `c`, if there exists a chain `c'` strictly including `c`, then `succ_chain c` is one of these chains. Otherwise it is `c`. -/ def succ_chain (c : set α) : set α := if h : ∃c', chain c ∧ super_chain c c' then some h else c theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂, cases hc₂.neg_resolve_left hc₁ with c' hc', exact succ_spec ⟨c', hc₁, hc'⟩ end theorem succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] /-- Set of sets reachable from `∅` using `succ_chain` and `⋃₀`. -/ inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) theorem chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case succ : c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case union : s hs ih { refine (classical.or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case succ : c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case union : s hs ih { apply or.imp_left (assume h', subset.antisymm h' h), apply classical.by_contradiction, simp [not_or_distrib, sUnion_subset_iff, classical.not_forall], intros c₃ hc₃ h₁ h₂, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₁ $ h' ▸ subset.refl _) }, { exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₁ $ subset.trans succ_increasing h) } } end theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case succ : c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case union : s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ theorem chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case succ : c hc h { exact chain_succ h }, case union : s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end /-- `max_chain` is the union of all sets in the chain closure. -/ def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ chain_closure), have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, H⟩ := this, ⟨h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := ssubset_iff_subset_ne.1 H in have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ theorem exists_maximal_of_chains_bounded (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀c:set α, chain (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @exists_maximal_of_chains_bounded α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α) (ih : ∀ c ⊆ s, chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) : ∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m := let ⟨⟨m, hms, hxm⟩, h⟩ := @zorn_partial_order {m // m ∈ s ∧ x ≤ m} _ (λ c hc, c.eq_empty_or_nonempty.elim (assume hce, hce.symm ▸ ⟨⟨x, hxs, le_refl _⟩, λ _, false.elim⟩) (assume ⟨m, hmc⟩, let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (image_subset_iff.2 $ λ z hzc, z.2.1) (by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq; exact hc p hpc q hqc (mt (by rintro rfl; refl) hpq)) m.1 (mem_image_of_mem _ hmc) in ⟨⟨ub, hubs, le_trans m.2.2 $ hub m.1 $ mem_image_of_mem _ hmc⟩, λ a hac, hub a.1 ⟨a, hac, rfl⟩⟩)) in ⟨m, hms, hxm, λ z hzs hmz, congr_arg subtype.val $ h ⟨z, hzs, le_trans hxm hmz⟩ hmz⟩ theorem zorn_subset {α : Type u} (S : set (set α)) (h : ∀c ⊆ S, chain (⊆) c → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) : ∃ m ∈ S, ∀a ∈ S, m ⊆ a → a = m := begin letI : partial_order S := partial_order.lift subtype.val (λ _ _, subtype.eq'), have : ∀c:set S, @chain S (≤) c → ∃ub, ∀a∈c, a ≤ ub, { intros c hc, rcases h (subtype.val '' c) (image_subset_iff.2 _) _ with ⟨s, sS, hs⟩, { exact ⟨⟨s, sS⟩, λ ⟨x, hx⟩ H, hs _ (mem_image_of_mem _ H)⟩ }, { rintro ⟨x, hx⟩ _, exact hx }, { rintro _ ⟨x, cx, rfl⟩ _ ⟨y, cy, rfl⟩ xy, exact hc x cx y cy (mt (congr_arg _) xy) } }, rcases zorn_partial_order this with ⟨⟨m, mS⟩, hm⟩, exact ⟨m, mS, λ a aS ha, congr_arg subtype.val (hm ⟨a, aS⟩ ha)⟩ end theorem zorn_subset₀ {α : Type u} (S : set (set α)) (H : ∀c ⊆ S, chain (⊆) c → c.nonempty → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) : ∃ m ∈ S, x ⊆ m ∧ ∀a ∈ S, m ⊆ a → a = m := begin let T := {s ∈ S | x ⊆ s}, rcases zorn_subset T _ with ⟨m, ⟨mS, mx⟩, hm⟩, { exact ⟨m, mS, mx, λ a ha ha', hm a ⟨ha, subset.trans mx ha'⟩ ha'⟩ }, { intros c cT hc, cases c.eq_empty_or_nonempty with c0 c0, { rw c0, exact ⟨x, ⟨hx, subset.refl _⟩, λ _, false.elim⟩ }, { rcases H _ (subset.trans cT (sep_subset _ _)) hc c0 with ⟨ub, us, h⟩, refine ⟨ub, ⟨us, _⟩, h⟩, rcases c0 with ⟨s, hs⟩, exact subset.trans (cT hs).2 (h _ hs) } } end theorem chain.total {α : Type u} [preorder α] {c : set α} (H : chain (≤) c) : ∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x := λ x y, H.total_of_refl theorem chain.image {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) (f : α → β) (h : ∀ x y, r x y → s (f x) (f y)) {c : set α} (hrc : chain r c) : chain s (f '' c) := λ x ⟨a, ha₁, ha₂⟩ y ⟨b, hb₁, hb₂⟩, ha₂ ▸ hb₂ ▸ λ hxy, (hrc a ha₁ b hb₁ (mt (congr_arg f) $ hxy)).elim (or.inl ∘ h _ _) (or.inr ∘ h _ _) end zorn theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))
b62d677ea4fc331fc0ae29c5da90d4fb19e5d783
618003631150032a5676f229d13a079ac875ff77
/src/tactic/hint.lean
2fc75c01134feb54ba2198bafb5e1c7ce50d7e72
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,966
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 tactic.solve_by_elim import tactic.interactive namespace tactic namespace hint /-- An attribute marking a `tactic unit` or `tactic string` which should be used by the `hint` tactic. -/ @[user_attribute] meta def hint_tactic_attribute : user_attribute := { name := `hint_tactic, descr := "A tactic that should be tried by `hint`." } add_tactic_doc { name := "hint_tactic", category := doc_category.attr, decl_names := [`tactic.hint.hint_tactic_attribute], tags := ["rewrite", "search"] } open lean lean.parser interactive private meta def add_tactic_hint (n : name) (t : expr) : tactic unit := do add_decl $ declaration.defn n [] `(tactic string) t reducibility_hints.opaque ff, hint_tactic_attribute.set n () tt /-- `add_hint_tactic t` runs the tactic `t` whenever `hint` is invoked. The typical use case is `add_hint_tactic "foo"` for some interactive tactic `foo`. -/ @[user_command] meta def add_hint_tactic (_ : parse (tk "add_hint_tactic")) : parser unit := do n ← parser.pexpr, e ← to_expr n, s ← eval_expr string e, let t := "`[" ++ s ++ "]", (t, _) ← with_input parser.pexpr t, of_tactic $ do let h := s <.> "_hint", t ← to_expr ``(do %%t, pure %%n), add_tactic_hint h t. add_tactic_doc { name := "add_hint_tactic", category := doc_category.cmd, decl_names := [`tactic.hint.add_hint_tactic], tags := ["search"] } add_hint_tactic "refl" add_hint_tactic "exact dec_trivial" add_hint_tactic "assumption" add_hint_tactic "intro" -- tidy does something better here: it suggests the actual "intros X Y f" string; perhaps add a wrapper? add_hint_tactic "apply_auto_param" add_hint_tactic "dsimp at *" add_hint_tactic "simp at *" -- TODO hook up to squeeze_simp? add_hint_tactic "fconstructor" add_hint_tactic "injections_and_clear" add_hint_tactic "solve_by_elim" add_hint_tactic "unfold_coes" add_hint_tactic "unfold_aux" end hint /-- Report a list of tactics that can make progress against the current goal, and for each such tactic, the number of remaining goals afterwards. -/ meta def hint : tactic (list (string × ℕ)) := do names ← attribute.get_instances `hint_tactic, focus1 $ try_all_sorted (names.reverse.map name_to_tactic) namespace interactive /-- Report a list of tactics that can make progress against the current goal. -/ meta def hint : tactic unit := do hints ← tactic.hint, if hints.length = 0 then fail "no hints available" else do t ← hints.nth 0, if t.2 = 0 then do trace "the following tactics solve the goal:\n----", (hints.filter (λ p : string × ℕ, p.2 = 0)).mmap' (λ p, tactic.trace format!"Try this: {p.1}") else do trace "the following tactics make progress:\n----", hints.mmap' (λ p, tactic.trace format!"Try this: {p.1}") /-- `hint` lists possible tactics which will make progress (that is, not fail) against the current goal. ```lean example {P Q : Prop} (p : P) (h : P → Q) : Q := begin hint, /- the following tactics make progress: ---- Try this: solve_by_elim Try this: finish Try this: tauto -/ solve_by_elim, end ``` You can add a tactic to the list that `hint` tries by either using 1. `attribute [hint_tactic] my_tactic`, if `my_tactic` is already of type `tactic string` (`tactic unit` is allowed too, in which case the printed string will be the name of the tactic), or 2. `add_hint_tactic "my_tactic"`, specifying a string which works as an interactive tactic. -/ add_tactic_doc { name := "hint", category := doc_category.tactic, decl_names := [`tactic.interactive.hint], tags := ["search", "Try this"] } end interactive end tactic
fe78d24a033aac48de6c11c3327a2889aa657226
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/WHNF.lean
288d32a59ca44be63d00d20fdc467cb02a61586f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
36,513
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.Structure import Lean.Util.Recognizers import Lean.Meta.GetConst import Lean.Meta.FunInfo import Lean.Meta.Match.MatcherInfo import Lean.Meta.Match.MatchPatternAttr namespace Lean.Meta -- =========================== /-! # Smart unfolding support -/ -- =========================== /-- Forward declaration. It is defined in the module `src/Lean/Elab/PreDefinition/Structural/Eqns.lean`. It is possible to avoid this hack if we move `Structural.EqnInfo` and `Structural.eqnInfoExt` to this module. -/ @[extern "lean_get_structural_rec_arg_pos"] opaque getStructuralRecArgPos? (declName : Name) : CoreM (Option Nat) def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name := Name.mkStr declName smartUnfoldingSuffix def hasSmartUnfoldingDecl (env : Environment) (declName : Name) : Bool := env.contains (mkSmartUnfoldingNameFor declName) register_builtin_option smartUnfolding : Bool := { defValue := true descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } /-- Add auxiliary annotation to indicate the `match`-expression `e` must be reduced when performing smart unfolding. -/ def markSmartUnfoldingMatch (e : Expr) : Expr := mkAnnotation `sunfoldMatch e def smartUnfoldingMatch? (e : Expr) : Option Expr := annotation? `sunfoldMatch e /-- Add auxiliary annotation to indicate expression `e` (a `match` alternative rhs) was successfully reduced by smart unfolding. -/ def markSmartUnfoldingMatchAlt (e : Expr) : Expr := mkAnnotation `sunfoldMatchAlt e def smartUnfoldingMatchAlt? (e : Expr) : Option Expr := annotation? `sunfoldMatchAlt e -- =========================== /-! # Helper methods -/ -- =========================== def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv return isAuxRecursor env constName || isNoConfusion env constName @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls => do let (some cinfo) ← getConst? name | failK () k cinfo lvls | _ => failK () -- =========================== /-! # Helper functions for reducing recursors -/ -- =========================== private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none return some ctor private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do match type.getAppFn with | Expr.const d lvls => let (some ctor) ← getFirstCtor d | pure none return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => return none private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ => recVal.rules.find? fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM Expr := do let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then return major else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then return major else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure major let newType ← inferType newCtorApp /- TODO: check whether changing reducibility to default hurts performance here. We do that to make sure auxiliary `Eq.rec` introduced by the `match`-compiler are reduced even when `TransparencyMode.reducible` (like in `simp`). We use `withNewMCtxDepth` to make sure metavariables at `majorType` are not assigned. For example, given `major : Eq ?x y`, we don't want to apply K by assigning `?x := y`. -/ if (← withAtLeastTransparency TransparencyMode.default <| withNewMCtxDepth <| isDefEq majorType newType) then return newCtorApp else return major /-- Create the `i`th projection `major`. It tries to use the auto-generated projection functions if available. Otherwise falls back to `Expr.proj`. -/ def mkProjFn (ctorVal : ConstructorVal) (us : List Level) (params : Array Expr) (i : Nat) (major : Expr) : CoreM Expr := do match getStructureInfo? (← getEnv) ctorVal.induct with | none => return mkProj ctorVal.induct i major | some info => match info.getProjFn? i with | none => return mkProj ctorVal.induct i major | some projFn => return mkApp (mkAppN (mkConst projFn us) params) major /-- If `major` is not a constructor application, and its type is a structure `C ...`, then return `C.mk major.1 ... major.n` \pre `inductName` is `C`. If `Meta.Config.etaStruct` is `false` or the condition above does not hold, this method just returns `major`. -/ private def toCtorWhenStructure (inductName : Name) (major : Expr) : MetaM Expr := do unless (← useEtaStruct inductName) do return major let env ← getEnv if !isStructureLike env inductName then return major else if let some _ := major.isConstructorApp? env then return major else let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf inductName then return major match majorType.getAppFn with | Expr.const d us => if (← whnfD (← inferType majorType)) == mkSort levelZero then return major -- We do not perform eta for propositions, see implementation in the kernel else let some ctorName ← getFirstCtor d | pure major let ctorInfo ← getConstInfoCtor ctorName let params := majorType.getAppArgs.shrink ctorInfo.numParams let mut result := mkAppN (mkConst ctorName us) params for i in [:ctorInfo.numFields] do result := mkApp result (← mkProjFn ctorInfo us params i major) return result | _ => return major /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← whnf major if recVal.k then major ← toCtorWhenK recVal major major := major.toCtorIfLit major ← toCtorWhenStructure recVal.getInduct major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.levelParams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () -- =========================== /-! # Helper functions for reducing Quot.lift and Quot.ind -/ -- =========================== /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _) _) _) majorArg => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK () let f := recArgs[argPos]! let r := mkApp f majorArg let recArity := majorPos + 1 successK <| mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () -- =========================== /-! # Helper function for extracting "stuck term" -/ -- =========================== mutual private partial def isRecStuck? (recVal : RecursorVal) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case return none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else return none private partial def isQuotRecStuck? (recVal : QuotVal) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else return none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => return none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? (e : Expr) : MetaM (Option MVarId) := do match e with | .mdata _ e => getStuckMVar? e | .proj _ _ e => getStuckMVar? (← whnf e) | .mvar .. => let e ← instantiateMVars e match e with | .mvar mvarId => return some mvarId | _ => getStuckMVar? e | .app f .. => let f := f.getAppFn match f with | .mvar .. => let e ← instantiateMVars e match e.getAppFn with | .mvar mvarId => return some mvarId | _ => getStuckMVar? e | .const fName _ => match (← getConstNoEx? fName) with | some <| .recInfo recVal => isRecStuck? recVal e.getAppArgs | some <| .quotInfo recVal => isQuotRecStuck? recVal e.getAppArgs | _ => unless e.hasExprMVar do return none -- Projection function support let some projInfo ← getProjectionFnInfo? fName | return none -- This branch is relevant if `e` is a type class projection that is stuck because the instance has not been synthesized yet. unless projInfo.fromClass do return none let args := e.getAppArgs -- First check whether `e`s instance is stuck. if let some major := args.get? projInfo.numParams then if let some mvarId ← getStuckMVar? major then return mvarId /- Then, recurse on the explicit arguments We want to detect the stuck instance in terms such as `HAdd.hAdd Nat Nat Nat (instHAdd Nat instAddNat) n (OfNat.ofNat Nat 2 ?m)` See issue https://github.com/leanprover/lean4/issues/1408 for an example where this is needed. -/ let info ← getFunInfo f for pinfo in info.paramInfo, arg in args do if pinfo.isExplicit then if let some mvarId ← getStuckMVar? arg then return some mvarId return none | .proj _ _ e => getStuckMVar? (← whnf e) | _ => return none | _ => return none end -- =========================== /-! # Weak Head Normal Form auxiliary combinators -/ -- =========================== /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do match e with | .forallE .. => return e | .lam .. => return e | .sort .. => return e | .lit .. => return e | .bvar .. => unreachable! | .letE .. => k e | .const .. => k e | .app .. => k e | .proj .. => k e | .mdata _ e => whnfEasyCases e k | .fvar fvarId => let decl ← fvarId.getDecl match decl with | .cdecl .. => return e | .ldecl (value := v) (nonDep := nonDep) .. => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then return e else if cfg.trackZeta then modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | .mvar mvarId => match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => return e @[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := do if c.levelParams.length != lvls.length then failK () else successK (← instantiateValueLevelParams c lvls) @[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) (preserveMData := false) : MetaM α := do if c.levelParams.length != lvls.length then failK () else let val ← instantiateValueLevelParams c lvls let val := val.betaRev revArgs (preserveMData := preserveMData) successK val inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp /-- The "match" compiler uses `if-then-else` expressions and other auxiliary declarations to compile match-expressions such as ``` match v with | 'a' => 1 | 'b' => 2 | _ => 3 ``` because it is more efficient than using `casesOn` recursors. The method `reduceMatcher?` fails if these auxiliary definitions (e.g., `ite`) cannot be unfolded in the current transparency setting. This is problematic because tactics such as `simp` use `TransparencyMode.reducible`, and most users assume that expressions such as ``` match 0 with | 0 => 1 | 100 => 2 | _ => 3 ``` should reduce in any transparency mode. Thus, we define a custom `canUnfoldAtMatcher` predicate for `whnfMatcher`. This solution is not very modular because modications at the `match` compiler require changes here. We claim this is defensible because it is reducing the auxiliary declaration defined by the `match` compiler. Alternative solution: tactics that use `TransparencyMode.reducible` should rely on the equations we generated for match-expressions. This solution is also not perfect because the match-expression above will not reduce during type checking when we are not using `TransparencyMode.default` or `TransparencyMode.all`. -/ def canUnfoldAtMatcher (cfg : Config) (info : ConstantInfo) : CoreM Bool := do match cfg.transparency with | TransparencyMode.all => return true | TransparencyMode.default => return true | _ => if (← isReducible info.name) || isGlobalInstance (← getEnv) info.name then return true else if hasMatchPatternAttribute (← getEnv) info.name then return true else return info.name == ``ite || info.name == ``dite || info.name == ``decEq || info.name == ``Nat.decEq || info.name == ``Char.ofNat || info.name == ``Char.ofNatAux || info.name == ``String.decEq || info.name == ``List.hasDecEq || info.name == ``Fin.ofNat || info.name == ``UInt8.ofNat || info.name == ``UInt8.decEq || info.name == ``UInt16.ofNat || info.name == ``UInt16.decEq || info.name == ``UInt32.ofNat || info.name == ``UInt32.decEq || info.name == ``UInt64.ofNat || info.name == ``UInt64.decEq /- Remark: we need to unfold the following two definitions because they are used for `Fin`, and lazy unfolding at `isDefEq` does not unfold projections. -/ || info.name == ``HMod.hMod || info.name == ``Mod.mod private def whnfMatcher (e : Expr) : MetaM Expr := do /- When reducing `match` expressions, if the reducibility setting is at `TransparencyMode.reducible`, we increase it to `TransparencyMode.instance`. We use the `TransparencyMode.reducible` in many places (e.g., `simp`), and this setting prevents us from reducing `match` expressions where the discriminants are terms such as `OfNat.ofNat α n inst`. For example, `simp [Int.div]` will not unfold the application `Int.div 2 1` occuring in the target. TODO: consider other solutions; investigate whether the solution above produces counterintuitive behavior. -/ let mut transparency ← getTransparency if transparency == TransparencyMode.reducible then transparency := TransparencyMode.instances withTransparency transparency <| withReader (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher }) do whnf e def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels => let some info ← getMatcherInfo? declName | return ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then return ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f ← instantiateValueLevelParams constInfo declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp ← whnfMatcher (mkAppN auxApp hs) let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i]! auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher private def projectCore? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e := e.toCtorIfLit matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.numParams + i if idx < numArgs then return some (e.getArg! idx) else return none def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do projectCore? (← whnf e) i /-- Reduce kernel projection `Expr.proj ..` expression. -/ def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c => project? c i | _ => return none /-- Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned. Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been "filled". -/ private def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do if f'.isMVar then match (← getDelayedMVarAssignment? f'.mvarId!) with | none => return none | some { fvars, mvarIdPending } => let args := e.getAppArgs if fvars.size > args.size then -- Insufficient number of argument to expand delayed assignment return none else let newVal ← instantiateMVars (mkMVar mvarIdPending) if newVal.hasExprMVar then -- Delayed assignment still contains metavariables return none else let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args return mkAppRange result fvars.size args.size args else return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. The parameter `deltaAtProj` controls how to reduce projections `s.i`. If `deltaAtProj == true`, then delta reduction is used to reduce `s` (i.e., `whnf` is used), otherwise `whnfCore`. We only set this flag to `false` when implementing `isDefEq`. -/ partial def whnfCore (e : Expr) (deltaAtProj : Bool := true) : MetaM Expr := go e where go (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf] e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => go <| b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← go f if f'.isLambda then let revArgs := e.getAppRevArgs go <| f'.betaRev revArgs else if let some eNew ← whnfDelayedAssigned? f' e then go eNew else let e := if f == f' then e else e.updateFn f' match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => go eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => matchConstAux f' (fun _ => return e) fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs (fun _ => return e) go | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) go | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) go else return e | _ => return e | Expr.proj _ i c => let c ← if deltaAtProj then whnf c else whnfCore c match (← projectCore? c i) with | some e => go e | none => return e | _ => unreachable! /-- Recall that `_sunfold` auxiliary definitions contains the markers: `markSmartUnfoldingMatch` (*) and `markSmartUnfoldingMatchAlt` (**). For example, consider the following definition ``` def r (i j : Nat) : Nat := i + match j with | Nat.zero => 1 | Nat.succ j => i + match j with | Nat.zero => 2 | Nat.succ j => r i j ``` produces the following `_sunfold` auxiliary definition with the markers ``` def r._sunfold (i j : Nat) : Nat := i + (*) match j with | Nat.zero => (**) 1 | Nat.succ j => i + (*) match j with | Nat.zero => (**) 2 | Nat.succ j => (**) r i j ``` `match` expressions marked with `markSmartUnfoldingMatch` (*) must be reduced, otherwise the resulting term is not definitionally equal to the given expression. The recursion may be interrupted as soon as the annotation `markSmartUnfoldingAlt` (**) is reached. For example, the term `r i j.succ.succ` reduces to the definitionally equal term `i + i * r i j` -/ partial def smartUnfoldingReduce? (e : Expr) : MetaM (Option Expr) := go e |>.run where go (e : Expr) : OptionT MetaM Expr := do match e with | Expr.letE n t v b _ => withLetDecl n t (← go v) fun x => do mkLetFVars #[x] (← go (b.instantiate1 x)) | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← go b) | Expr.app f a .. => return mkApp (← go f) (← go a) | Expr.proj _ _ s => return e.updateProj! (← go s) | Expr.mdata _ b => if let some m := smartUnfoldingMatch? e then goMatch m else return e.updateMData! (← go b) | _ => return e goMatch (e : Expr) : OptionT MetaM Expr := do match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => if let some alt := smartUnfoldingMatchAlt? e then return alt else go e | ReduceMatcherResult.stuck e' => let mvarId ← getStuckMVar? e' /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then goMatch e else failure | _ => failure mutual /-- Auxiliary method for unfolding a class projection. -/ partial def unfoldProjInst? (e : Expr) : MetaM (Option Expr) := do match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { fromClass := true, .. } => match (← withDefault <| unfoldDefinition? e) with | none => return none | some e => match (← withReducibleAndInstances <| reduceProj? e.getAppFn) with | none => return none | some r => return mkAppN r e.getAppArgs |>.headBeta | _ => return none | _ => return none /-- Auxiliary method for unfolding a class projection. when transparency is set to `TransparencyMode.instances`. Recall that class instance projections are not marked with `[reducible]` because we want them to be in "reducible canonical form". -/ partial def unfoldProjInstWhenIntances? (e : Expr) : MetaM (Option Expr) := do if (← getTransparency) != TransparencyMode.instances then return none else unfoldProjInst? e /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ => matchConstAux f.getAppFn (fun _ => unfoldProjInstWhenIntances? e) fun fInfo fLvls => do if fInfo.levelParams.length != fLvls.length then return none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none if smartUnfolding.get (← getOptions) then match ((← getEnv).find? (mkSmartUnfoldingNameFor fInfo.name)) with | some fAuxInfo@(ConstantInfo.defnInfo _) => -- We use `preserveMData := true` to make sure the smart unfolding annotation are not erased in an over-application. deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (preserveMData := true) (fun _ => pure none) fun e₁ => do let some r ← smartUnfoldingReduce? e₁ | return none /- If `smartUnfoldingReduce?` succeeds, we should still check whether the argument the structural recursion is recursing on reduces to a constructor. This extra check is necessary in definitions (see issue #1081) such as ``` inductive Vector (α : Type u) : Nat → Type u where | nil : Vector α 0 | cons : α → Vector α n → Vector α (n+1) def Vector.insert (a: α) (i : Fin (n+1)) (xs : Vector α n) : Vector α (n+1) := match i, xs with | ⟨0, _⟩, xs => cons a xs | ⟨i+1, h⟩, cons x xs => cons x (xs.insert a ⟨i, Nat.lt_of_succ_lt_succ h⟩) ``` The structural recursion is being performed using the vector `xs`. That is, we used `Vector.brecOn` to define `Vector.insert`. Thus, an application `xs.insert a ⟨0, h⟩` is **not** definitionally equal to `Vector.cons a xs` because `xs` is not a constructor application (the `Vector.brecOn` application is blocked). Remark 1: performing structural recursion on `Fin (n+1)` is not an option here because it is a `Subtype` and and the repacking in recursive applications confuses the structural recursion module. Remark 2: the match expression reduces reduces to `cons a xs` when the discriminants are `⟨0, h⟩` and `xs`. Remark 3: this check is unnecessary in most cases, but we don't need dependent elimination to trigger the issue fixed by this extra check. Here is another example that triggers the issue fixed by this check. ``` def f : Nat → Nat → Nat | 0, y => y | x+1, y+1 => f (x-2) y | x+1, 0 => 0 theorem ex : f 0 y = y := rfl ``` Remark 4: the `return some r` in the following `let` is not a typo. Binport generated .olean files do not store the position of recursive arguments for definitions using structural recursion. Thus, we should keep `return some r` until Mathlib has been ported to Lean 3. Note that the `Vector` example above does not even work in Lean 3. -/ let some recArgPos ← getStructuralRecArgPos? fInfo.name | return some r let numArgs := e.getAppNumArgs if recArgPos >= numArgs then return none let recArg := e.getArg! recArgPos numArgs if !(← whnfMatcher recArg).isConstructorApp (← getEnv) then return none return some r | _ => if (← getMatcherInfo? fInfo.name).isSome then -- Recall that `whnfCore` tries to reduce "matcher" applications. return none else unfoldDefault () else unfoldDefault () | Expr.const declName lvls => do if smartUnfolding.get (← getOptions) && (← getEnv).contains (mkSmartUnfoldingNameFor declName) then return none else let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? declName | pure none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => return none end def unfoldDefinition (e : Expr) : MetaM Expr := do let some e ← unfoldDefinition? e | throwError "failed to unfold definition{indentExpr e}" return e @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => return e else return e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => return !e.isAppOf declName) if e.isAppOf declName then return e else return none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none | _ => return none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implementedBy reduceBoolNativeUnsafe] opaque reduceBoolNative (constName : Name) : MetaM Bool @[implementedBy reduceNatNativeUnsafe] opaque reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _) (Expr.const argName _) => if fName == ``Lean.reduceBool then do return toExpr (← reduceBoolNative argName) else if fName == ``Lean.reduceNat then do return toExpr (← reduceNatNative argName) else return none | _ => return none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ => k 0 | Expr.lit (Literal.natVal v) => k v | _ => return none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => return mkRawNatLit <| f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp] "{a} op {b}" return mkRawNatLit <| f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => return toExpr <| f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then return none else match e with | Expr.app (Expr.const fn _) a => if fn == ``Nat.succ then reduceUnaryNatOp Nat.succ a else return none | Expr.app (Expr.app (Expr.const fn _) a1) a2 => if fn == ``Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == ``Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == ``Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == ``Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == ``Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == ``Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == ``Nat.ble then reduceBinNatPred Nat.ble a1 a2 else return none | _ => return none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar || (← read).canUnfold?.isSome then return false else match (← getConfig).transparency with | TransparencyMode.default => return true | TransparencyMode.all => return true | _ => return false @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.whnfDefault.find? e | TransparencyMode.all => return (← get).cache.whnfAll.find? e | _ => unreachable! else return none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r } | TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r } | _ => unreachable! return r @[export lean_whnf] partial def whnfImp (e : Expr) : MetaM Expr := withIncRecDepth <| whnfEasyCases e fun e => do checkMaxHeartbeats "whnf" let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' /-- If `e` is a projection function that satisfies `p`, then reduce it -/ def reduceProjOf? (e : Expr) (p : Name → Bool) : 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 p structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none builtin_initialize registerTraceClass `Meta.whnf registerTraceClass `Meta.isDefEq.whnf.reduceBinOp end Lean.Meta
08d9783c1a73677720f2345e700df632432043ba
e07b1aca72e83a272dd59d24c6e0fa246034d774
/src/tutorials/01_equality_rewriting.lean
d710ea8dfd1b04c6ae20928f481ab48f73fd2241
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pedrominicz/learn
637a343bd4f8669d76819ac660a2d2d3e0958710
b79b802a9846c86c21d4b6f3e17af36e7382f0ef
refs/heads/master
1,671,746,990,402
1,670,778,113,000
1,670,778,113,000
265,735,177
1
0
null
null
null
null
UTF-8
Lean
false
false
5,136
lean
import data.real.basic /- One of the earliest kind of proofs one encounters while learning mathematics is proving by a calculation. It may not sound like a proof, but this is actually using lemmas expressing properties of operations on numbers. It also uses the fundamental property of equality: if two mathematical objects A and B are equal then, in any statement involving A, one can replace A by B. This operation is called rewriting, and the Lean "tactic" for this is `rw`. In the following exercises, we will use the following two lemmas: mul_assoc a b c : a * b * c = a * (b * c) mul_comm a b : a*b = b*a Hence the command rw mul_assoc a b c, will replace a*b*c by a*(b*c) in the current goal. In order to replace backward, we use rw ← mul_assoc a b c, replacing a*(b*c) by a*b*c in the current goal. Of course we don't want to constantly invoke those lemmas, and we will eventually introduce more powerful solutions. -/ example (a b c : ℝ) : (a * b) * c = b * (a * c) := begin rw mul_comm a b, rw mul_assoc b a c, end -- 0001 example (a b c : ℝ) : (c * b) * a = b * (a * c) := begin rw mul_comm c b, rw mul_assoc, rw mul_comm c a, end -- 0002 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin rw ←mul_assoc, rw mul_comm a b, rw mul_assoc, end /- Now let's return to the preceding example to experiment with what happens if we don't give arguments to mul_assoc or mul_comm. For instance, you can start the next proof with rw ← mul_assoc, Try to figure out what happens. -/ -- 0003 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin rw ←mul_assoc, rw mul_comm a b, rw mul_assoc, end /- We can also perform rewriting in an assumption of the local context, using for instance rw mul_comm a b at hyp, in order to replace a*b by b*a in assumption hyp. The next example will use a third lemma: two_mul a : 2*a = a + a Also we use the `exact` tactic, which allows to provide a direct proof term. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin rw hyp' at hyp, rw mul_comm d a at hyp, rw ← two_mul (a*d) at hyp, rw ← mul_assoc 2 a d at hyp, exact hyp, -- Our assumption hyp is now exactly what we have to prove end /- And the next one can use: sub_self x : x - x = 0 -/ -- 0004 example (a b c d : ℝ) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 := begin rw mul_comm at hyp', rw hyp' at hyp, rwa sub_self at hyp, end /- What is written in the two preceding example is very far away from what we would write on paper. Let's now see how to get a more natural layout. Inside each pair of curly braces below, the goal is to prove equality with the preceding line. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin calc c = d*a + b : by { rw hyp } ... = d*a + a*d : by { rw hyp' } ... = a*d + a*d : by { rw mul_comm d a } ... = 2*(a*d) : by { rw two_mul } ... = 2*a*d : by { rw mul_assoc }, end /- Let's note there is no comma at the end of each line of calculation. `calc` is really one command, and the comma comes only after it's fully done. From a practical point of view, when writing such a proof, it is convenient to: * pause the tactic state view update in VScode by clicking the Pause icon button in the top right corner of the Lean Goal buffer * write the full calculation, ending each line with ": by {}" * resume tactic state update by clicking the Play icon button and fill in proofs between curly braces. Let's return to the other example using this method. -/ -- 0005 example (a b c d : ℝ) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 := begin calc c = b*a - d : by { rw hyp } ... = b*a - a*b : by { rw hyp'} ... = a*b - a*b : by { rw mul_comm } ... = 0 : by { rw sub_self } end /- The preceding proofs have exhauted our supply of "mul_comm" patience. Now it's time to get the computer to work harder. The `ring` tactic will prove any goal that follows by applying only the axioms of commutative (semi-)rings, in particuler commutativity and associativity of addition and multiplication, as well as distributivity. We also note that curly braces are not necessary when we write a single tactic proof, so let's get rid of them. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin calc c = d*a + b : by rw hyp ... = d*a + a*d : by rw hyp' ... = 2*a*d : by ring, end /- Of course we can use `ring` outside of `calc`. Let's do the next one in one line. -/ -- 0006 example (a b c : ℝ) : a * (b * c) = b * (a * c) := by ring /- This is too much fun. Let's do it again. -/ -- 0007 example (a b : ℝ) : (a + b) + a = 2*a + b := by ring /- Maybe this is cheating. Let's try to do the next computation without ring. We could use: pow_two x : x^2 = x*x mul_sub a b c : a*(b-c) = a*b - a*c add_mul a b c : (a+b)*c = a*c + b*c add_sub a b c : a + (b - c) = (a + b) - c sub_sub a b c : a - b - c = a - (b + c) add_zero a : a + 0 = a -/ -- 0008 example (a b : ℝ) : (a + b)*(a - b) = a^2 - b^2 := by ring /- Let's stick to ring in the end. -/
96e5093d8b72da7f6338559338bbdc82965fed69
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/algebra/ordered_monoid.lean
02ab9b2ef16e4fae626132993097468205618d38
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,037
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 Ordered (non-cancellative) monoids -/ import data.set order.galois_connection open set lattice function section old_structure_cmd set_option old_structure_cmd true class ordered_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α := (le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c) end old_structure_cmd section ordered_comm_monoid variables {α : Type*} [ordered_comm_monoid α] {a b c d : α} lemma add_le_add_left' (h : a ≤ b) : c + a ≤ c + b := ordered_comm_monoid.add_le_add_left a b h c lemma add_le_add_right' (h : a ≤ b) : a + c ≤ b + c := add_comm c a ▸ add_comm c b ▸ add_le_add_left' h lemma lt_of_add_lt_add_left' : a + b < a + c → b < c := ordered_comm_monoid.lt_of_add_lt_add_left a b c lemma add_le_add' (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (add_le_add_right' h₁) (add_le_add_left' h₂) lemma le_add_of_nonneg_right' (h : b ≥ 0) : a ≤ a + b := have a + b ≥ a + 0, from add_le_add_left' h, by rwa add_zero at this lemma le_add_of_nonneg_left' (h : b ≥ 0) : a ≤ b + a := have 0 + a ≤ b + a, from add_le_add_right' h, by rwa zero_add at this lemma lt_of_add_lt_add_right' (h : a + b < c + b) : a < c := lt_of_add_lt_add_left' (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) -- here we start using properties of zero. lemma le_add_of_nonneg_of_le' (ha : 0 ≤ a) (hbc : b ≤ c) : b ≤ a + c := zero_add b ▸ add_le_add' ha hbc lemma le_add_of_le_of_nonneg' (hbc : b ≤ c) (ha : 0 ≤ a) : b ≤ c + a := add_zero b ▸ add_le_add' hbc ha lemma add_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := le_add_of_nonneg_of_le' ha hb lemma add_pos_of_pos_of_nonneg' (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b := lt_of_lt_of_le ha $ le_add_of_nonneg_right' hb lemma add_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a + b := add_pos_of_pos_of_nonneg' ha $ le_of_lt hb lemma add_pos_of_nonneg_of_pos' (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b := lt_of_lt_of_le hb $ le_add_of_nonneg_left' ha lemma add_nonpos' (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 := zero_add (0:α) ▸ (add_le_add' ha hb) lemma add_le_of_nonpos_of_le' (ha : a ≤ 0) (hbc : b ≤ c) : a + b ≤ c := zero_add c ▸ add_le_add' ha hbc lemma add_le_of_le_of_nonpos' (hbc : b ≤ c) (ha : a ≤ 0) : b + a ≤ c := add_zero c ▸ add_le_add' hbc ha lemma add_neg_of_neg_of_nonpos' (ha : a < 0) (hb : b ≤ 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) hb) ha lemma add_neg_of_nonpos_of_neg' (ha : a ≤ 0) (hb : b < 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hb lemma add_neg' (ha : a < 0) (hb : b < 0) : a + b < 0 := add_neg_of_nonpos_of_neg' (le_of_lt ha) hb lemma lt_add_of_nonneg_of_lt' (ha : 0 ≤ a) (hbc : b < c) : b < a + c := lt_of_lt_of_le hbc $ le_add_of_nonneg_left' ha lemma lt_add_of_lt_of_nonneg' (hbc : b < c) (ha : 0 ≤ a) : b < c + a := lt_of_lt_of_le hbc $ le_add_of_nonneg_right' ha lemma lt_add_of_pos_of_lt' (ha : 0 < a) (hbc : b < c) : b < a + c := lt_add_of_nonneg_of_lt' (le_of_lt ha) hbc lemma lt_add_of_lt_of_pos' (hbc : b < c) (ha : 0 < a) : b < c + a := lt_add_of_lt_of_nonneg' hbc (le_of_lt ha) lemma add_lt_of_nonpos_of_lt' (ha : a ≤ 0) (hbc : b < c) : a + b < c := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hbc lemma add_lt_of_lt_of_nonpos' (hbc : b < c) (ha : a ≤ 0) : b + a < c := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) ha) hbc lemma add_lt_of_neg_of_lt' (ha : a < 0) (hbc : b < c) : a + b < c := add_lt_of_nonpos_of_lt' (le_of_lt ha) hbc lemma add_lt_of_lt_of_neg' (hbc : b < c) (ha : a < 0) : b + a < c := add_lt_of_lt_of_nonpos' hbc (le_of_lt ha) lemma add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume hab : a + b = 0, have a ≤ 0, from hab ▸ le_add_of_le_of_nonneg' (le_refl _) hb, have a = 0, from le_antisymm this ha, have b ≤ 0, from hab ▸ le_add_of_nonneg_of_le' ha (le_refl _), have b = 0, from le_antisymm this hb, and.intro ‹a = 0› ‹b = 0›) (assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero]) end ordered_comm_monoid section canonically_ordered_monoid variables {α : Type*} [canonically_ordered_monoid α] {a b c d : α} lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c := canonically_ordered_monoid.le_iff_exists_add a b @[simp] lemma zero_le : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩ @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg' zero_le zero_le end canonically_ordered_monoid
67bd6e296f205bb057dd211ecc02bd29b9ffcb81
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/clifford_algebra/basic.lean
44ce8373e82ade01cafa420ff7a8ffcddc066d6f
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
7,463
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Utensil Song -/ import algebra.ring_quot import linear_algebra.tensor_algebra import linear_algebra.exterior_algebra import linear_algebra.quadratic_form /-! # Clifford Algebras We construct the Clifford algebra of a module `M` over a commutative ring `R`, equipped with a quadratic_form `Q`. ## Notation The Clifford algebra of the `R`-module `M` equipped with a quadratic_form `Q` is denoted as `clifford_algebra Q`. Given a linear morphism `f : M → A` from a module `M` to another `R`-algebra `A`, such that `cond : ∀ m, f m * f m = algebra_map _ _ (Q m)`, there is a (unique) lift of `f` to an `R`-algebra morphism, which is denoted `clifford_algebra.lift Q f cond`. The canonical linear map `M → clifford_algebra Q` is denoted `clifford_algebra.ι Q`. ## Theorems The main theorems proved ensure that `clifford_algebra Q` satisfies the universal property of the Clifford algebra. 1. `ι_comp_lift` is the fact that the composition of `ι Q` with `lift Q f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift Q f cond` with respect to 1. Additionally, when `Q = 0` an `alg_equiv` to the `exterior_algebra` is provided as `as_exterior`. ## Implementation details The Clifford algebra of `M` is constructed as a quotient of the tensor algebra, as follows. 1. We define a relation `clifford_algebra.rel Q` on `tensor_algebra R M`. This is the smallest relation which identifies squares of elements of `M` with `Q m`. 2. The Clifford algebra is the quotient of the tensor algebra by this relation. This file is almost identical to `linear_algebra/exterior_algebra.lean`. -/ variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables (Q : quadratic_form R M) variable {n : ℕ} namespace clifford_algebra open tensor_algebra /-- `rel` relates each `ι m * ι m`, for `m : M`, with `Q m`. The Clifford algebra of `M` is defined as the quotient modulo this relation. -/ inductive rel : tensor_algebra R M → tensor_algebra R M → Prop | of (m : M) : rel (ι R m * ι R m) (algebra_map R _ (Q m)) end clifford_algebra /-- The Clifford algebra of an `R`-module `M` equipped with a quadratic_form `Q`. -/ @[derive [inhabited, ring, algebra R]] def clifford_algebra := ring_quot (clifford_algebra.rel Q) namespace clifford_algebra /-- The canonical linear map `M →ₗ[R] clifford_algebra Q`. -/ def ι : M →ₗ[R] clifford_algebra Q := (ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R) /-- As well as being linear, `ι Q` squares to the quadratic form -/ @[simp] theorem ι_sq_scalar (m : M) : ι Q m * ι Q m = algebra_map R _ (Q m) := begin erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.commutes], refl, end variables {Q} {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_sq_scalar (g : clifford_algebra Q →ₐ[R] A) (m : M) : g (ι Q m) * g (ι Q m) = algebra_map _ _ (Q m) := by rw [←alg_hom.map_mul, ι_sq_scalar, alg_hom.commutes] variables (Q) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = Q(m)`, this is the canonical lift of `f` to a morphism of `R`-algebras from `clifford_algebra Q` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = algebra_map _ _ (Q m)} ≃ (clifford_algebra Q →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A), (λ x y (h : rel Q x y), by { induction h, rw [alg_hom.commutes, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop], })⟩, inv_fun := λ F, ⟨F.to_linear_map.comp (ι Q), λ m, by rw [ linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_sq_scalar]⟩, left_inv := λ f, by { ext, simp [ι] }, right_inv := λ F, by { ext, simp [ι] } } variables {Q} @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) : (lift Q ⟨f, cond⟩).to_linear_map.comp (ι Q) = f := (subtype.mk_eq_mk.mp $ (lift Q).symm_apply_apply ⟨f, cond⟩) @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) (x) : lift Q ⟨f, cond⟩ (ι Q x) = f x := (linear_map.ext_iff.mp $ ι_comp_lift f cond) x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m : M, f m * f m = algebra_map _ _ (Q m)) (g : clifford_algebra Q →ₐ[R] A) : g.to_linear_map.comp (ι Q) = f ↔ g = lift Q ⟨f, cond⟩ := begin convert (lift Q).symm_apply_eq, rw lift_symm_apply, simp only, end attribute [irreducible] clifford_algebra ι lift @[simp] theorem lift_comp_ι (g : clifford_algebra Q →ₐ[R] A) : lift Q ⟨g.to_linear_map.comp (ι Q), comp_ι_sq_scalar _⟩ = g := begin convert (lift Q).apply_symm_apply g, rw lift_symm_apply, refl, end /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {A : Type*} [semiring A] [algebra R A] {f g : clifford_algebra Q →ₐ[R] A} : f.to_linear_map.comp (ι Q) = g.to_linear_map.comp (ι Q) → f = g := begin intro h, apply (lift Q).symm.injective, rw [lift_symm_apply, lift_symm_apply], simp only [h], end /-- If `C` holds for the `algebra_map` of `r : R` into `clifford_algebra Q`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `clifford_algebra Q`. -/ -- This proof closely follows `tensor_algebra.induction` @[elab_as_eliminator] lemma induction {C : clifford_algebra Q → Prop} (h_grade0 : ∀ r, C (algebra_map R (clifford_algebra Q) r)) (h_grade1 : ∀ x, C (ι Q x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : clifford_algebra Q) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from M let s : subalgebra R (clifford_algebra Q) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : { f : M →ₗ[R] s // ∀ m, f m * f m = algebra_map _ _ (Q m) } := ⟨(ι Q).cod_restrict s.to_submodule h_grade1, λ m, subtype.eq $ ι_sq_scalar Q m ⟩, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (clifford_algebra Q) = s.val.comp (lift Q of), { ext, simp [of], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift Q of a), exact alg_hom.congr_fun of_id a, end /-- A Clifford algebra with a zero quadratic form is isomorphic to an `exterior_algebra` -/ def as_exterior : clifford_algebra (0 : quadratic_form R M) ≃ₐ[R] exterior_algebra R M := alg_equiv.of_alg_hom (clifford_algebra.lift 0 ⟨(exterior_algebra.ι R), by simp⟩) (exterior_algebra.lift R ⟨(ι (0 : quadratic_form R M)), by simp⟩) (by { ext, simp, }) (by { ext, simp, }) end clifford_algebra namespace tensor_algebra variables {Q} /-- The canonical image of the `tensor_algebra` in the `clifford_algebra`, which maps `tensor_algebra.ι R x` to `clifford_algebra.ι Q x`. -/ def to_clifford : tensor_algebra R M →ₐ[R] clifford_algebra Q := tensor_algebra.lift R (clifford_algebra.ι Q) @[simp] lemma to_clifford_ι (m : M) : (tensor_algebra.ι R m).to_clifford = clifford_algebra.ι Q m := by simp [to_clifford] end tensor_algebra
4ca5a9f17ab5367d60f558bf4b2fe2f11624c58a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/calculus/extend_deriv.lean
24384191f303faf5baf1db1c823ab3c34c044131
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
11,065
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value import tactic.monotonicity /-! # Extending differentiability to the boundary We investigate how differentiable functions inside a set extend to differentiable functions on the boundary. For this, it suffices that the function and its derivative admit limits there. A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`. One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or the right endpoint of an interval, are given in `has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and `has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms of the one-dimensional derivative `deriv ℝ f`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open filter set metric continuous_linear_map open_locale topological_space local attribute [mono] prod_mono /-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there with derivative `f'`. -/ theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F} (f_diff : differentiable_on ℝ f s) (s_conv : convex s) (s_open : is_open s) (f_cont : ∀y ∈ closure s, continuous_within_at f s y) (h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) : has_fderiv_within_at f f' (closure s) x := begin classical, -- one can assume without loss of generality that `x` belongs to the closure of `s`, as the -- statement is empty otherwise by_cases hx : x ∉ closure s, { rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx }, push_neg at hx, rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff], /- One needs to show that `∥f y - f x - f' (y - x)∥ ≤ ε ∥y - x∥` for `y` close to `x` in `closure s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/ assume ε ε_pos, obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ∥fderiv ℝ f y - f'∥ < ε, by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos, set B := ball x δ, suffices : ∀ y ∈ B ∩ (closure s), ∥f y - f x - (f' y - f' x)∥ ≤ ε * ∥y - x∥, from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩, suffices : ∀ p : E × E, p ∈ closure ((B ∩ s).prod (B ∩ s)) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥ ≤ ε * ∥p.2 - p.1∥, { rw closure_prod_eq at this, intros y y_in, apply this ⟨x, y⟩, have : B ∩ closure s ⊆ closure (B ∩ s), from closure_inter_open is_open_ball, exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ }, have key : ∀ p : E × E, p ∈ (B ∩ s).prod (B ∩ s) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥ ≤ ε * ∥p.2 - p.1∥, { rintros ⟨u, v⟩ ⟨u_in, v_in⟩, have conv : convex (B ∩ s) := (convex_ball _ _).inter s_conv, have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _), have bound : ∀ z ∈ (B ∩ s), ∥fderiv_within ℝ f (B ∩ s) z - f'∥ ≤ ε, { intros z z_in, convert le_of_lt (hδ _ z_in.2 z_in.1), have op : is_open (B ∩ s) := is_open_ball.inter s_open, rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in), exact (diff z z_in).differentiable_at (is_open.mem_nhds op z_in) }, simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in }, rintros ⟨u, v⟩ uv_in, refine continuous_within_at.closure_le uv_in _ _ key, have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y, { intros y y_in, exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) }, all_goals { -- common start for both continuity proofs have : (B ∩ s).prod (B ∩ s) ⊆ s.prod s, by mono ; exact inter_subset_right _ _, obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s, by simpa [closure_prod_eq] using closure_mono this uv_in, apply continuous_within_at.mono _ this, simp only [continuous_within_at] }, rw nhds_within_prod_eq, { have : f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by abel, rw this, convert tendsto.comp continuous_norm.continuous_at ((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $ tendsto.comp (f_cont' u u_in) tendsto_fst), intros, simp, abel }, { apply tendsto_nhds_within_of_tendsto_nhds, rw nhds_prod_eq, exact tendsto_const_nhds.mul (tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) }, end /-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/ lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ 𝓝[Ioi a] a) (f_lim' : tendsto (λx, deriv f x) (𝓝[Ioi a] a) (𝓝 e)) : has_deriv_within_at f e (Ici a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ab, sab⟩ : ∃ b ∈ Ioi a, Ioc a b ⊆ s := mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs, let t := Ioo a b, have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex t := convex_Ioo a b, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc a b := closure_Ioo ab, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)), { simp [deriv_fderiv.symm], refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _, exact tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim' }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc a b) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (mem_nhds_within_Ici_iff_exists_Icc_subset.2 ⟨b, ab, subset.refl _⟩) end /-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/ lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ 𝓝[Iio a] a) (f_lim' : tendsto (λx, deriv f x) (𝓝[Iio a] a) (𝓝 e)) : has_deriv_within_at f e (Iic a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s := mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs, let t := Ioo b a, have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex t := convex_Ioo b a, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc b a := closure_Ioo ba, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)), { simp [deriv_fderiv.symm], refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _, exact tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim' }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc b a) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (mem_nhds_within_Iic_iff_exists_Icc_subset.2 ⟨b, ba, subset.refl _⟩) end /-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are continuous at this point, then `g` is also the derivative of `f` at this point. -/ lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ} (f_diff : ∀ y ≠ x, has_deriv_at f (g y) y) (hf : continuous_at f x) (hg : continuous_at g x) : has_deriv_at f (g x) x := begin have A : has_deriv_within_at f (g x) (Ici x) x, { have diff : differentiable_on ℝ f (Ioi x) := λy hy, (f_diff y (ne_of_gt hy)).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 hf.continuous_within_at self_mem_nhds_within, have : tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) := tendsto_inf_left hg, apply this.congr' _, apply mem_sets_of_superset self_mem_nhds_within (λy hy, _), exact (f_diff y (ne_of_gt hy)).deriv.symm }, have B : has_deriv_within_at f (g x) (Iic x) x, { have diff : differentiable_on ℝ f (Iio x) := λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at self_mem_nhds_within, have : tendsto g (𝓝[Iio x] x) (𝓝 (g x)) := tendsto_inf_left hg, apply this.congr' _, apply mem_sets_of_superset self_mem_nhds_within (λy hy, _), exact (f_diff y (ne_of_lt hy)).deriv.symm }, simpa using B.union A end
5d30a578dacebf1ceffc6c5509ba842b698c6bd2
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/analysis/normed_space/basic.lean
77e0d1d51f3534d2f421dfea60992c609a46b669
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
46,645
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.instances.nnreal import topology.instances.complex import topology.algebra.module import topology.metric_space.antilipschitz /-! # Normed spaces -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e section prio set_option default_priority 100 -- see Note [default priority] /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) end prio /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥s.sum f∥ ≤ s.sum n := by { haveI := classical.dec_eq β, exact le_trans (norm_sum_le s f) (finset.sum_le_sum h) } lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } @[nolint ge_or_gt] -- see Note [nolint_ge] theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (s.sum f) ≤ s.sum (λa, nnnorm (f a)) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add' (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], apply le_div_of_mul_le (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl } lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto.comp continuous_norm.continuous_at h lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm, sub_eq_add_neg]; abel ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _ ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) end prio @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_add_le }, { rw ←zero_add (0 : ℝ), apply tendsto.add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto.mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto.mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) end prio @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt (norm_pos_iff.2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b @[simp] lemma nnnorm_one [normed_field α] : nnnorm (1:α) = 1 := nnreal.eq $ by simp instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (s.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := begin classical, by_cases hb : b = 0, {simp [hb]}, apply eq_div_of_mul_eq, { apply ne_of_gt, apply norm_pos_iff.mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma nnnorm_inv {α : Type*} [normed_field α] (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α] (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) : nhds_within x (-{x}) ≠ ⊥ := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := begin refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _), let δ := min (ε/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0, have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos (half_pos εpos) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨δ, δpos, λ x hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp [sub_sub_cancel], have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2, by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div, div_eq_inv_mul, mul_comm] }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } end lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} := begin assume x hx, apply continuous_at.continuous_within_at, exact (tendsto_inv hx) end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } end normed_field /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α} (hy : y ≠ 0) (h : tendsto f l (𝓝 y)) : tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) := (normed_field.tendsto_inv hy).comp h lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) : tendsto (λa, f a / g a) l (𝓝 (x / y)) := hf.mul (hg.inv' hy) lemma filter.tendsto.div_const [normed_field α] {l : filter β} {f : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) := by { simp only [div_eq_inv_mul], exact tendsto_const_nhds.mul hf } /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) : continuous_at (λ x, f x / g x) x := hf.div hg hnz namespace real lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _) @[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp end real @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option default_priority 920 -- see Note [default priority]. Here, we set a rather high priority, -- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better -- unification properties. -- see Note[vector space definition] for why we extend `semimodule`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends semimodule α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin classical, by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _ ... = ∥s • x∥ : _, exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _), rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul], rwa [ne.def, norm_eq_zero] } end lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end /-- In a normed space over a nondiscrete normed field, only `⊤` submodule has a nonempty interior. See also `submodule.eq_top_of_nonempty_interior'` for a `topological_module` version. -/ lemma submodule.eq_top_of_nonempty_interior {α E : Type*} [nondiscrete_normed_field α] [normed_group E] [normed_space α E] (s : submodule α E) (hs : (interior (s:set E)).nonempty) : s = ⊤ := begin refine s.eq_top_of_nonempty_interior' _ hs, simp only [is_unit_iff_ne_zero, @ne.def α, set.mem_singleton_iff.symm], exact normed_field.punctured_nhds_ne_bot _ end theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, interior_eq_of_open is_open_ball], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem interior_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases hE with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure (-{x} : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_eq_of_is_closed is_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] theorem frontier_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_eq_of_is_closed is_closed_ball, interior_closed_ball' x r hE, closed_ball_diff_ball] open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos (norm_pos_iff.2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], -- TODO: without the next two lines Lean unfolds `≤` to `real.le` add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.semimodule } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } end normed_space section normed_algebra section prio set_option default_priority 100 -- see Note [default priority] /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) end prio @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ @[priority 100] instance to_normed_space (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] /-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/ -- We could add a type synonym equipped with this as an instance, -- as we've done for `module.restrict_scalars`. def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..module.restrict_scalars' 𝕜 𝕜' E } end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, s.sum f) ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := begin simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, s.sum f) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, s.sum f) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : β → finset ι} {p : filter β} (hp : p ≠ ⊥) (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hp hs ha /-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) := begin by_cases h : summable f, { have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (𝓝 ∥(∑' i, f i)∥) := (continuous_norm.tendsto _).comp h.has_sum, have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (𝓝 (∑' i, ∥f i∥)) := hf.has_sum, exact le_of_tendsto_of_tendsto' at_top_ne_bot h₁ h₂ (assume s, norm_sum_le _ _) }, { rw tsum_eq_zero_of_not_summable h, simp [tsum_nonneg] } end lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf at_top_ne_bot tendsto_finset_range h⟩ variable [complete_space α] lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
9715cc1681a7d6090b08b093ccc40572829ebd8f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/no_confusion_bug.lean
a451524da6a78e7aa8016fc5cddd5415bc02faf9
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
358
lean
import data.nat.basic open nat inductive fin : nat → Type := | fz : Π {n : nat}, fin (succ n) | fs : Π {n : nat}, fin n → fin (succ n) namespace fin inductive le : ∀ {n : nat}, fin n → fin n → Prop := | lez : ∀ {n : nat} (j : fin (succ n)), le fz j | les : ∀ {n : nat} {i j : fin n}, le i j → le (fs i) (fs j) end fin
89a12cb333b8c66d934f8253e3f551623ec0ff66
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/K/rules.lean
a7dbcfc178c8550465d55c3a17add80148e95ceb
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
3,238
lean
import .marking open nnf subtype list batch_sat inductive node (Γ : list nnf) : Type | closed : Π m, unsatisfiable Γ → pmark Γ m → node | open_ : {s // sat builder s Γ} → node open node def and_rule {Γ Δ} (i : and_instance Γ Δ) : node Δ → node Γ | (closed m h p) := begin left, {apply unsat_of_closed_and, repeat {assumption}}, exact (pmark_of_closed_and i m h p).2 end | (open_ w) := begin right, clear and_rule, cases i with φ ψ h, constructor, exact sat_and_of_sat_split _ _ _ _ _ h w.2 end def jump_rule {Γ₁ Γ₂ Δ : list nnf} (i : or_instance Δ Γ₁ Γ₂) (m : list nnf) (h₁ : unsatisfiable Γ₁) (h₂ : pmark Γ₁ m) (h₃ : left_prcp i ∉ m) : node Δ := begin left, {apply unsat_of_jump, repeat {assumption}}, exact (pmark_of_jump i m h₁ h₂ h₃).2 end def or_rule {Γ₁ Γ₂ Δ} (i : or_instance Δ Γ₁ Γ₂) : node Γ₁ → node Γ₂ → node Δ | (open_ w) _ := begin right, clear or_rule, cases i with φ ψ h, constructor, exact sat_or_of_sat_split_left _ _ _ _ _ h w.2 end | _ (open_ w) := begin right, clear or_rule, cases i with φ ψ h, constructor, exact sat_or_of_sat_split_right _ _ _ _ _ h w.2 end | (closed m₁ h₁ p₁) (closed m₂ h₂ p₂):= begin left, {apply unsat_of_closed_or, repeat {assumption}}, exact (pmark_of_closed_or i h₁ p₁ h₂ p₂).2 end def open_rule {Γ₁ Γ₂ Δ} {s} (i : or_instance Δ Γ₁ Γ₂) (h : sat builder s Γ₁) : node Δ := begin right, constructor, cases i with φ ψ hin, swap, exact s, exact sat_or_of_sat_split_left _ _ _ _ _ hin h end def contra_rule {Δ n} (h : var n ∈ Δ ∧ neg n ∈ Δ) : node Δ := begin left, {exact unsat_contra h.1 h.2}, swap, {exact [var n, neg n]}, {intros Δ' hΔ' hsub, apply unsat_contra, {apply mem_diff_of_mem, exact h.1, intro, apply hΔ' (var n) a, simp}, {apply mem_diff_of_mem, exact h.2, intro, apply hΔ' (neg n) a, simp} } end /- This is essentially the modal rule. -/ def tmap {p : list nnf → Prop} (f : Π Γ, p Γ → node Γ): Π Γ : list $ list nnf, (∀ i∈Γ, p i) → psum ({ c : list nnf × list nnf // c.1 ∈ Γ ∧ unsatisfiable c.1 ∧ pmark c.1 c.2}) {x // batch_sat x Γ} | [] h := psum.inr ⟨[], bs_nil⟩ | (hd :: tl) h := match f hd (h hd (by simp)) with | (node.closed m pr pm) := psum.inl ⟨⟨hd,m⟩, by simp, pr, pm⟩ | (node.open_ w₁) := match tmap tl (λ x hx, h x $ by simp [hx]) with | (psum.inl uw) := begin left, rcases uw with ⟨w, hin, h⟩, split, split, swap, exact h, simp [hin] end | (psum.inr w₂) := psum.inr ⟨(w₁.1::w₂), bs_cons _ _ _ _ w₁.2 w₂.2⟩ end end
455b13b43398e37073c4952cf022f11e94a330f3
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/toFromJson.lean
cd824bae3be12a7705fed8a57fc01d974a3820fd
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
2,353
lean
import Lean open Lean open Lean Parser Term declare_syntax_cat json syntax strLit : json syntax numLit : json syntax "{" (Lean.Parser.ident ": " json),* "}" : json syntax "[" json,* "]" : json syntax "json " json : term /- declare a micro json parser, so we can write our tests in a more legible way. -/ open Json in macro_rules | `(json $s:strLit) => s | `(json $n:numLit) => n | `(json { $[$ns : $js],* }) => do let mut fields := #[] for n in ns, j in js do fields := fields.push (← `(($(quote n.getId.getString!), json $j))) `(mkObj [$fields,*]) | `(json [ $[$js],* ]) => do let mut fields := #[] for j in js do fields := fields.push (← `(json $j)) `(Json.arr #[$fields,*]) def checkToJson [ToJson α] (obj : α) (rhs : Json) : MetaM Unit := let lhs := (obj |> toJson).pretty if lhs == rhs.pretty then () else throwError "{lhs} ≟ {rhs}" def checkRoundTrip [Repr α] [BEq α] [ToJson α] [FromJson α] (obj : α) : MetaM Unit := let roundTripped := obj |> toJson |> fromJson? if let some roundTripped := roundTripped then if obj == roundTripped then () else throwError "{repr obj} ≟ {repr roundTripped}" else throwError "couldn't parse: {repr obj} ≟ {obj |> toJson}" -- set_option trace.Meta.debug true in structure Foo where x : Nat y : String deriving ToJson, FromJson, Repr, BEq #eval checkToJson { x := 1, y := "bla" : Foo} (json { y : "bla", x : 1 }) #eval checkRoundTrip { x := 1, y := "bla" : Foo } -- set_option trace.Elab.command true structure WInfo where a : Nat b : Nat deriving ToJson, FromJson, Repr, BEq -- set_option trace.Elab.command true inductive E | W : WInfo → E | WAlt (a b : Nat) | X : Nat → Nat → E | Y : Nat → E | YAlt (a : Nat) | Z deriving ToJson, FromJson, Repr, BEq #eval checkToJson (E.W { a := 2, b := 3}) (json { W : { a : 2, b : 3 } }) #eval checkRoundTrip (E.W { a := 2, b := 3 }) #eval checkToJson (E.WAlt 2 3) (json { WAlt : { a : 2, b : 3 } }) #eval checkRoundTrip (E.WAlt 2 3) #eval checkToJson (E.X 2 3) (json { X : [2, 3] }) #eval checkRoundTrip (E.X 2 3) #eval checkToJson (E.Y 4) (json { Y : 4 }) #eval checkRoundTrip (E.Y 4) #eval checkToJson (E.YAlt 5) (json { YAlt : { a : 5 } }) #eval checkRoundTrip (E.YAlt 5) #eval checkToJson E.Z (json "Z") #eval checkRoundTrip E.Z
be7e4288c2d2339f5de279f7f6c5d5c1e69485e1
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/whenIO.lean
fd2a8bab3eb1ca5b24d0ca0c8fc22e700395ca12
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
203
lean
import system.io open io variable [io.interface] def iowhen (b : bool) (a : io unit) : io unit := if b = tt then a else return () #eval iowhen tt (put_str "hello\n") #eval iowhen ff (put_str "error\n")
0fe5ec8837f3eaf1a9ddde138e136d00fa339e5f
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Control/Option.lean
8b587200d4d671530f24924a63f928f07cef0a21
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,205
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Data.Option.Basic import Init.Control.Basic import Init.Control.Except universe u v instance {α} : ToBool (Option α) := ⟨Option.toBool⟩ def OptionT (m : Type u → Type v) (α : Type u) : Type v := m (Option α) @[inline] def OptionT.run {m : Type u → Type v} {α : Type u} (x : OptionT m α) : m (Option α) := x namespace OptionT variable {m : Type u → Type v} [Monad m] {α β : Type u} protected def mk (x : m (Option α)) : OptionT m α := x @[inline] protected def bind (x : OptionT m α) (f : α → OptionT m β) : OptionT m β := OptionT.mk do match (← x) with | some a => f a | none => pure none @[inline] protected def pure (a : α) : OptionT m α := OptionT.mk do pure (some a) instance : Monad (OptionT m) where pure := OptionT.pure bind := OptionT.bind @[inline] protected def orElse (x : OptionT m α) (y : Unit → OptionT m α) : OptionT m α := OptionT.mk do match (← x) with | some a => pure (some a) | _ => y () @[inline] protected def fail : OptionT m α := OptionT.mk do pure none instance : Alternative (OptionT m) where failure := OptionT.fail orElse := OptionT.orElse @[inline] protected def lift (x : m α) : OptionT m α := OptionT.mk do return some (← x) instance : MonadLift m (OptionT m) := ⟨OptionT.lift⟩ instance : MonadFunctor m (OptionT m) := ⟨fun f x => f x⟩ @[inline] protected def tryCatch (x : OptionT m α) (handle : Unit → OptionT m α) : OptionT m α := OptionT.mk do let some a ← x | handle () pure a instance : MonadExceptOf Unit (OptionT m) where throw := fun _ => OptionT.fail tryCatch := OptionT.tryCatch instance (ε : Type u) [Monad m] [MonadExceptOf ε m] : MonadExceptOf ε (OptionT m) where throw e := OptionT.mk <| throwThe ε e tryCatch x handle := OptionT.mk <| tryCatchThe ε x handle end OptionT instance [Monad m] : MonadControl m (OptionT m) where stM := Option liftWith f := liftM <| f fun x => x.run restoreM x := x
33d3db2ceae7f000d89f21aed9695b63ed593191
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/homotopy/susp.hlean
7097106dfd3fb185a425431e5bc8e398905ed890
[ "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
12,226
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, Ulrik Buchholtz Declaration of suspension -/ import hit.pushout types.pointed cubical.square .connectedness open pushout unit eq equiv definition susp (A : Type) : Type := pushout (λ(a : A), star) (λ(a : A), star) namespace susp variable {A : Type} definition north {A : Type} : susp A := inl star definition south {A : Type} : susp A := inr star definition merid (a : A) : @north A = @south A := glue a protected definition rec {P : susp A → Type} (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) (x : susp A) : P x := begin induction x with u u, { cases u, exact PN}, { cases u, exact PS}, { apply Pm}, end protected definition rec_on [reducible] {P : susp A → Type} (y : susp A) (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) : P y := susp.rec PN PS Pm y theorem rec_merid {P : susp A → Type} (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) (a : A) : apd (susp.rec PN PS Pm) (merid a) = Pm a := !rec_glue protected definition elim {P : Type} (PN : P) (PS : P) (Pm : A → PN = PS) (x : susp A) : P := susp.rec PN PS (λa, pathover_of_eq (Pm a)) x protected definition elim_on [reducible] {P : Type} (x : susp A) (PN : P) (PS : P) (Pm : A → PN = PS) : P := susp.elim PN PS Pm x theorem elim_merid {P : Type} {PN PS : P} (Pm : A → PN = PS) (a : A) : ap (susp.elim PN PS Pm) (merid a) = Pm a := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (merid a)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑susp.elim,rec_merid], end protected definition elim_type (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (x : susp A) : Type := pushout.elim_type (λx, PN) (λx, PS) Pm x protected definition elim_type_on [reducible] (x : susp A) (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) : Type := susp.elim_type PN PS Pm x theorem elim_type_merid (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (a : A) : transport (susp.elim_type PN PS Pm) (merid a) = Pm a := !elim_type_glue theorem elim_type_merid_inv {A : Type} (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (a : A) : transport (susp.elim_type PN PS Pm) (merid a)⁻¹ = to_inv (Pm a) := !elim_type_glue_inv protected definition merid_square {a a' : A} (p : a = a') : square (merid a) (merid a') idp idp := by cases p; apply vrefl end susp attribute susp.north susp.south [constructor] attribute susp.rec susp.elim [unfold 6] [recursor 6] attribute susp.elim_type [unfold 5] attribute susp.rec_on susp.elim_on [unfold 3] attribute susp.elim_type_on [unfold 2] namespace susp open is_trunc is_conn trunc -- Theorem 8.2.1 definition is_conn_susp [instance] (n : trunc_index) (A : Type) [H : is_conn n A] : is_conn (n .+1) (susp A) := is_contr.mk (tr north) begin apply trunc.rec, fapply susp.rec, { reflexivity }, { exact (trunc.rec (λa, ap tr (merid a)) (center (trunc n A))) }, { intro a, generalize (center (trunc n A)), apply trunc.rec, intro a', apply pathover_of_tr_eq, rewrite [transport_eq_Fr,idp_con], revert H, induction n with [n, IH], { intro H, apply is_prop.elim }, { intros H, change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a'), generalize a', apply is_conn_fun.elim n (is_conn_fun_from_unit n A a) (λx : A, trunctype.mk' n (ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid x))), intros, change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a), reflexivity } } end end susp /- Flattening lemma -/ namespace susp open prod prod.ops section universe variable u parameters (A : Type) (PN PS : Type.{u}) (Pm : A → PN ≃ PS) include Pm local abbreviation P [unfold 5] := susp.elim_type PN PS Pm local abbreviation F : A × PN → PN := λz, z.2 local abbreviation G : A × PN → PS := λz, Pm z.1 z.2 protected definition flattening : sigma P ≃ pushout F G := begin apply equiv.trans !pushout.flattening, fapply pushout.equiv, { exact sigma.equiv_prod A PN }, { apply sigma.sigma_unit_left }, { apply sigma.sigma_unit_left }, { reflexivity }, { reflexivity } end end end susp /- Functoriality and equivalence -/ namespace susp variables {A B : Type} (f : A → B) include f protected definition functor : susp A → susp B := begin intro x, induction x with a, { exact north }, { exact south }, { exact merid (f a) } end variable [Hf : is_equiv f] include Hf open is_equiv protected definition is_equiv_functor [instance] : is_equiv (susp.functor f) := adjointify (susp.functor f) (susp.functor f⁻¹) abstract begin intro sb, induction sb with b, do 2 reflexivity, apply eq_pathover, rewrite [ap_id,ap_compose' (susp.functor f) (susp.functor f⁻¹)], krewrite [susp.elim_merid,susp.elim_merid], apply transpose, apply susp.merid_square (right_inv f b) end end abstract begin intro sa, induction sa with a, do 2 reflexivity, apply eq_pathover, rewrite [ap_id,ap_compose' (susp.functor f⁻¹) (susp.functor f)], krewrite [susp.elim_merid,susp.elim_merid], apply transpose, apply susp.merid_square (left_inv f a) end end end susp namespace susp variables {A B : Type} (f : A ≃ B) protected definition equiv : susp A ≃ susp B := equiv.mk (susp.functor f) _ end susp namespace susp open pointed definition pointed_susp [instance] [constructor] (X : Type) : pointed (susp X) := pointed.mk north end susp open susp definition psusp [constructor] (X : Type) : Type* := pointed.mk' (susp X) namespace susp open pointed variables {X Y Z : Type*} definition psusp_functor (f : X →* Y) : psusp X →* psusp Y := begin fconstructor, { exact susp.functor f }, { reflexivity } end definition is_equiv_psusp_functor (f : X →* Y) [Hf : is_equiv f] : is_equiv (psusp_functor f) := susp.is_equiv_functor f definition psusp_equiv (f : X ≃* Y) : psusp X ≃* psusp Y := pequiv_of_equiv (susp.equiv f) idp definition psusp_functor_compose (g : Y →* Z) (f : X →* Y) : psusp_functor (g ∘* f) ~* psusp_functor g ∘* psusp_functor f := begin fconstructor, { intro a, induction a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, rewrite [▸*,ap_compose' _ (psusp_functor f),↑psusp_functor], krewrite +susp.elim_merid } }, { reflexivity } end -- adjunction from Coq-HoTT definition loop_susp_unit [constructor] (X : Type*) : X →* Ω(psusp X) := begin fconstructor, { intro x, exact merid x ⬝ (merid pt)⁻¹}, { apply con.right_inv}, end definition loop_susp_unit_natural (f : X →* Y) : loop_susp_unit Y ∘* f ~* ap1 (psusp_functor f) ∘* loop_susp_unit X := begin induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf, fconstructor, { intro x', esimp [psusp_functor], symmetry, exact !idp_con ⬝ (!ap_con ⬝ whisker_left _ !ap_inv) ⬝ (!elim_merid ◾ (inverse2 !elim_merid)) }, { rewrite [▸*,idp_con (con.right_inv _)], apply inv_con_eq_of_eq_con, refine _ ⬝ !con.assoc', rewrite inverse2_right_inv, refine _ ⬝ !con.assoc', rewrite [ap_con_right_inv], unfold psusp_functor, xrewrite [idp_con_idp, -ap_compose (concat idp)]}, end definition loop_susp_counit [constructor] (X : Type*) : psusp (Ω X) →* X := begin fconstructor, { intro x, induction x, exact pt, exact pt, exact a}, { reflexivity}, end definition loop_susp_counit_natural (f : X →* Y) : f ∘* loop_susp_counit X ~* loop_susp_counit Y ∘* (psusp_functor (ap1 f)) := begin induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf, fconstructor, { intro x', induction x' with p, { reflexivity}, { reflexivity}, { esimp, apply eq_pathover, apply hdeg_square, xrewrite [ap_compose' f, ap_compose' (susp.elim (f x) (f x) (λ (a : f x = f x), a)),▸*], xrewrite [+elim_merid,▸*,idp_con]}}, { reflexivity} end definition loop_susp_counit_unit (X : Type*) : ap1 (loop_susp_counit X) ∘* loop_susp_unit (Ω X) ~* pid (Ω X) := begin induction X with X x, fconstructor, { intro p, esimp, refine !idp_con ⬝ (!ap_con ⬝ whisker_left _ !ap_inv) ⬝ (!elim_merid ◾ inverse2 !elim_merid)}, { rewrite [▸*,inverse2_right_inv (elim_merid id idp)], refine !con.assoc ⬝ _, xrewrite [ap_con_right_inv (susp.elim x x (λa, a)) (merid idp),idp_con_idp,-ap_compose]} end definition loop_susp_unit_counit (X : Type*) : loop_susp_counit (psusp X) ∘* psusp_functor (loop_susp_unit X) ~* pid (psusp X) := begin induction X with X x, fconstructor, { intro x', induction x', { reflexivity}, { exact merid pt}, { apply eq_pathover, xrewrite [▸*, ap_id, ap_compose' (susp.elim north north (λa, a)), +elim_merid,▸*], apply square_of_eq, exact !idp_con ⬝ !inv_con_cancel_right⁻¹}}, { reflexivity} end definition susp_adjoint_loop (X Y : Type*) : pointed.mk' (susp X) →* Y ≃ X →* Ω Y := begin fapply equiv.MK, { intro f, exact ap1 f ∘* loop_susp_unit X}, { intro g, exact loop_susp_counit Y ∘* psusp_functor g}, { intro g, apply eq_of_phomotopy, esimp, refine !pwhisker_right !ap1_compose ⬝* _, refine !passoc ⬝* _, refine !pwhisker_left !loop_susp_unit_natural⁻¹* ⬝* _, refine !passoc⁻¹* ⬝* _, refine !pwhisker_right !loop_susp_counit_unit ⬝* _, apply pid_comp}, { intro f, apply eq_of_phomotopy, esimp, refine !pwhisker_left !psusp_functor_compose ⬝* _, refine !passoc⁻¹* ⬝* _, refine !pwhisker_right !loop_susp_counit_natural⁻¹* ⬝* _, refine !passoc ⬝* _, refine !pwhisker_left !loop_susp_unit_counit ⬝* _, apply comp_pid}, end definition susp_adjoint_loop_nat_right (f : psusp X →* Y) (g : Y →* Z) : susp_adjoint_loop X Z (g ∘* f) ~* ap1 g ∘* susp_adjoint_loop X Y f := begin esimp [susp_adjoint_loop], refine _ ⬝* !passoc, apply pwhisker_right, apply ap1_compose end definition susp_adjoint_loop_nat_left (f : Y →* Ω Z) (g : X →* Y) : (susp_adjoint_loop X Z)⁻¹ᵉ (f ∘* g) ~* (susp_adjoint_loop Y Z)⁻¹ᵉ f ∘* psusp_functor g := begin esimp [susp_adjoint_loop], refine _ ⬝* !passoc⁻¹*, apply pwhisker_left, apply psusp_functor_compose end definition iterate_susp (n : ℕ) (A : Type) : Type := iterate susp n A definition iterate_psusp (n : ℕ) (A : Type*) : Type* := iterate (λX, psusp X) n A open is_conn trunc_index nat definition iterate_susp_succ (n : ℕ) (A : Type) : iterate_susp (succ n) A = susp (iterate_susp n A) := idp definition is_conn_iterate_susp [instance] (n : ℕ₋₂) (m : ℕ) (A : Type) [H : is_conn n A] : is_conn (n + m) (iterate_susp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end definition is_conn_iterate_psusp [instance] (n : ℕ₋₂) (m : ℕ) (A : Type*) [H : is_conn n A] : is_conn (n + m) (iterate_psusp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end -- Separate cases for n = 0, which comes up often definition is_conn_iterate_susp_zero [instance] (m : ℕ) (A : Type) [H : is_conn 0 A] : is_conn m (iterate_susp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end definition is_conn_iterate_psusp_zero [instance] (m : ℕ) (A : Type*) [H : is_conn 0 A] : is_conn m (iterate_psusp m A) := begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end end susp
ea3ea0b78799cec4dc5d5e131e42c90bf8894ccc
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/set/basic.lean
b0e04cc0214baea29e24753f4ab486b093913372
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
42,485
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.ext tactic.finish data.subtype tactic.interactive open function /- set coercion to a type -/ namespace set instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} @[simp] theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[extensionality] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨begin intros h x, rw h end, ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {α} {s : set α} : {a | a ∈ s} = s := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := begin split, { rintro ⟨a⟩ H2, show a ∈ (∅ : set α), by rw ←H2 ; trivial }, { intro H, cases exists_mem_of_ne_empty H with a _, exact ⟨a⟩ } end /- union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} ∪ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] /- separation -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /- complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff /- set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage_eq {s : set β} {a : α} : (a ∈ f ⁻¹' s) = (f a ∈ s) := rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm lemma inter_singleton_ne_empty {α : Type*} {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) lemma surjective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma subtype_val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ι : Type*} {f : ι → β} {s : set β} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma nonempty_of_nonempty_range {α : Type*} {β : Type*} {f : α → β} (H : ¬range f = ∅) : nonempty α := begin cases exists_mem_of_ne_empty H with x h, cases mem_range.1 h with y _, exact ⟨y⟩ end theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' preimage f t = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ preimage f t, by simp [preimage, h_eq, hx]⟩ @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep end range lemma subtype_val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype_val_image] /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y end set namespace set section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ @[simp] theorem prod_empty {s : set α} : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set β} : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp [not_eq_empty_iff_exists] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] end prod section pi variables {α : Type*} {π : α → Type*} def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi end set
7d1decc6066f474156f788b82f170695e0893bd9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/array/lemmas_auto.lean
02506109160b191dbaeaa6ce3b91d6c8f425a172
[]
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,646
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, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.traversable.equiv import Mathlib.data.vector2 import Mathlib.PostPort universes u u_1 w v namespace Mathlib namespace d_array protected instance inhabited {n : ℕ} {α : fin n → Type u} [(i : fin n) → Inhabited (α i)] : Inhabited (d_array n α) := { default := mk fun (_x : fin n) => Inhabited.default } end d_array namespace array protected instance inhabited {n : ℕ} {α : Type u_1} [Inhabited α] : Inhabited (array n α) := d_array.inhabited theorem to_list_of_heq {n₁ : ℕ} {n₂ : ℕ} {α : Type u_1} {a₁ : array n₁ α} {a₂ : array n₂ α} (hn : n₁ = n₂) (ha : a₁ == a₂) : to_list a₁ = to_list a₂ := sorry /- rev_list -/ theorem rev_list_reverse_aux {n : ℕ} {α : Type u} {a : array n α} (i : ℕ) (h : i ≤ n) (t : List α) : list.reverse_core (d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h []) t = d_array.rev_iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h t := sorry @[simp] theorem rev_list_reverse {n : ℕ} {α : Type u} {a : array n α} : list.reverse (rev_list a) = to_list a := rev_list_reverse_aux n d_array.iterate._proof_1 [] @[simp] theorem to_list_reverse {n : ℕ} {α : Type u} {a : array n α} : list.reverse (to_list a) = rev_list a := sorry /- mem -/ theorem mem.def {n : ℕ} {α : Type u} {v : α} {a : array n α} : v ∈ a ↔ ∃ (i : fin n), read a i = v := iff.rfl theorem mem_rev_list_aux {n : ℕ} {α : Type u} {v : α} {a : array n α} {i : ℕ} (h : i ≤ n) : (∃ (j : fin n), ↑j < i ∧ read a j = v) ↔ v ∈ d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h [] := sorry @[simp] theorem mem_rev_list {n : ℕ} {α : Type u} {v : α} {a : array n α} : v ∈ rev_list a ↔ v ∈ a := sorry @[simp] theorem mem_to_list {n : ℕ} {α : Type u} {v : α} {a : array n α} : v ∈ to_list a ↔ v ∈ a := eq.mpr (id (Eq._oldrec (Eq.refl (v ∈ to_list a ↔ v ∈ a)) (Eq.symm rev_list_reverse))) (iff.trans list.mem_reverse mem_rev_list) /- foldr -/ theorem rev_list_foldr_aux {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} {i : ℕ} (h : i ≤ n) : list.foldr f b (d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h []) = d_array.iterate_aux a (fun (_x : fin n) => f) i h b := sorry theorem rev_list_foldr {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} : list.foldr f b (rev_list a) = foldl a b f := rev_list_foldr_aux d_array.iterate._proof_1 /- foldl -/ theorem to_list_foldl {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α} : list.foldl f b (to_list a) = foldl a b (function.swap f) := sorry /- length -/ theorem rev_list_length_aux {n : ℕ} {α : Type u} (a : array n α) (i : ℕ) (h : i ≤ n) : list.length (d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h []) = i := sorry @[simp] theorem rev_list_length {n : ℕ} {α : Type u} (a : array n α) : list.length (rev_list a) = n := rev_list_length_aux a n d_array.iterate._proof_1 @[simp] theorem to_list_length {n : ℕ} {α : Type u} (a : array n α) : list.length (to_list a) = n := eq.mpr (id (Eq._oldrec (Eq.refl (list.length (to_list a) = n)) (Eq.symm rev_list_reverse))) (eq.mpr (id (Eq._oldrec (Eq.refl (list.length (list.reverse (rev_list a)) = n)) (list.length_reverse (rev_list a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (list.length (rev_list a) = n)) (rev_list_length a))) (Eq.refl n))) /- nth -/ theorem to_list_nth_le_aux {n : ℕ} {α : Type u} {a : array n α} (i : ℕ) (ih : i < n) (j : ℕ) {jh : j ≤ n} {t : List α} {h' : i < list.length (d_array.rev_iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) j jh t)} : (∀ (k : ℕ) (tl : k < list.length t), j + k = i → list.nth_le t k tl = read a { val := i, property := ih }) → list.nth_le (d_array.rev_iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) j jh t) i h' = read a { val := i, property := ih } := sorry theorem to_list_nth_le {n : ℕ} {α : Type u} {a : array n α} (i : ℕ) (h : i < n) (h' : i < list.length (to_list a)) : list.nth_le (to_list a) i h' = read a { val := i, property := h } := to_list_nth_le_aux i h n fun (k : ℕ) (tl : k < list.length []) => absurd tl (nat.not_lt_zero k) @[simp] theorem to_list_nth_le' {n : ℕ} {α : Type u} (a : array n α) (i : fin n) (h' : ↑i < list.length (to_list a)) : list.nth_le (to_list a) (↑i) h' = read a i := sorry theorem to_list_nth {n : ℕ} {α : Type u} {a : array n α} {i : ℕ} {v : α} : list.nth (to_list a) i = some v ↔ ∃ (h : i < n), read a { val := i, property := h } = v := sorry theorem write_to_list {n : ℕ} {α : Type u} {a : array n α} {i : fin n} {v : α} : to_list (write a i v) = list.update_nth (to_list a) (↑i) v := sorry /- enum -/ theorem mem_to_list_enum {n : ℕ} {α : Type u} {a : array n α} {i : ℕ} {v : α} : (i, v) ∈ list.enum (to_list a) ↔ ∃ (h : i < n), read a { val := i, property := h } = v := sorry /- to_array -/ @[simp] theorem to_list_to_array {n : ℕ} {α : Type u} (a : array n α) : list.to_array (to_list a) == a := sorry @[simp] theorem to_array_to_list {α : Type u} (l : List α) : to_list (list.to_array l) = l := list.ext_le (to_list_length (list.to_array l)) fun (n : ℕ) (h1 : n < list.length (to_list (list.to_array l))) (h2 : n < list.length l) => to_list_nth_le n h2 h1 /- push_back -/ theorem push_back_rev_list_aux {n : ℕ} {α : Type u} {v : α} {a : array n α} (i : ℕ) (h : i ≤ n + 1) (h' : i ≤ n) : d_array.iterate_aux (push_back a v) (fun (_x : fin (n + 1)) (_x : α) (_y : List α) => _x :: _y) i h [] = d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h' [] := sorry @[simp] theorem push_back_rev_list {n : ℕ} {α : Type u} {v : α} {a : array n α} : rev_list (push_back a v) = v :: rev_list a := sorry @[simp] theorem push_back_to_list {n : ℕ} {α : Type u} {v : α} {a : array n α} : to_list (push_back a v) = to_list a ++ [v] := sorry /- foreach -/ @[simp] theorem read_foreach {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : fin n → α → β} {a : array n α} : read (foreach a f) i = f i (read a i) := rfl /- map -/ theorem read_map {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : α → β} {a : array n α} : read (map a f) i = f (read a i) := read_foreach /- map₂ -/ @[simp] theorem read_map₂ {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ : array n α} {a₂ : array n α} : read (map₂ f a₁ a₂) i = f (read a₁ i) (read a₂ i) := read_foreach end array namespace equiv /-- The natural equivalence between length-`n` heterogeneous arrays and dependent functions from `fin n`. -/ def d_array_equiv_fin {n : ℕ} (α : fin n → Type u_1) : d_array n α ≃ ((i : fin n) → α i) := mk d_array.read d_array.mk sorry sorry /-- The natural equivalence between length-`n` arrays and functions from `fin n`. -/ def array_equiv_fin (n : ℕ) (α : Type u_1) : array n α ≃ (fin n → α) := d_array_equiv_fin fun (_x : fin n) => α /-- The natural equivalence between length-`n` vectors and functions from `fin n`. -/ def vector_equiv_fin (α : Type u_1) (n : ℕ) : vector α n ≃ (fin n → α) := mk vector.nth vector.of_fn vector.of_fn_nth sorry /-- The natural equivalence between length-`n` vectors and length-`n` arrays. -/ def vector_equiv_array (α : Type u_1) (n : ℕ) : vector α n ≃ array n α := equiv.trans (vector_equiv_fin α n) (equiv.symm (array_equiv_fin n α)) end equiv namespace array protected instance traversable {n : ℕ} : traversable (array n) := equiv.traversable fun (α : Type u_1) => equiv.vector_equiv_array α n protected instance is_lawful_traversable {n : ℕ} : is_lawful_traversable (array n) := equiv.is_lawful_traversable fun (α : Type u_1) => equiv.vector_equiv_array α n end Mathlib
a5ece523321f7a51676875325bded18b3de1a0f3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/functor.lean
d8697c8891dfafcc8ac96e8e752ece725da89ee1
[ "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
6,102
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Scott Morrison -/ import data.finset.lattice import data.finset.n_ary import data.multiset.functor /-! # Functoriality of `finset` This file defines the functor structure of `finset`. ## TODO Currently, all instances are classical because the functor classes want to run over all types. If instead we could state that a functor is lawful/applicative/traversable... between two given types, then we could provide the instances for types with decidable equality. -/ universes u open function namespace finset /-! ### Functor -/ section functor variables {α β : Type u} [Π P, decidable P] /-- Because `finset.image` requires a `decidable_eq` instance for the target type, we can only construct `functor finset` when working classically. -/ instance : functor finset := { map := λ α β f s, s.image f } instance : is_lawful_functor finset := { id_map := λ α s, image_id, comp_map := λ α β γ f g s, image_image.symm } @[simp] lemma fmap_def {s : finset α} (f : α → β) : f <$> s = s.image f := rfl end functor /-! ### Pure -/ instance : has_pure finset := ⟨λ α x, {x}⟩ @[simp] lemma pure_def {α} : (pure : α → finset α) = singleton := rfl /-! ### Applicative functor -/ section applicative variables {α β : Type u} [Π P, decidable P] instance : applicative finset := { seq := λ α β t s, t.sup (λ f, s.image f), seq_left := λ α β s t, if t = ∅ then ∅ else s, seq_right := λ α β s t, if s = ∅ then ∅ else t, .. finset.functor, .. finset.has_pure } @[simp] lemma seq_def (s : finset α) (t : finset (α → β)) : t <*> s = t.sup (λ f, s.image f) := rfl @[simp] lemma seq_left_def (s : finset α) (t : finset β) : s <* t = if t = ∅ then ∅ else s := rfl @[simp] lemma seq_right_def (s : finset α) (t : finset β) : s *> t = if s = ∅ then ∅ else t := rfl /-- `finset.image₂` in terms of monadic operations. Note that this can't be taken as the definition because of the lack of universe polymorphism. -/ lemma image₂_def {α β γ : Type*} (f : α → β → γ) (s : finset α) (t : finset β) : image₂ f s t = f <$> s <*> t := by { ext, simp [mem_sup] } instance : is_lawful_applicative finset := { seq_left_eq := λ α β s t, begin rw [seq_def, fmap_def, seq_left_def], obtain rfl | ht := t.eq_empty_or_nonempty, { simp_rw [if_pos rfl, image_empty], exact (sup_bot _).symm }, { ext a, rw [if_neg ht.ne_empty, mem_sup], refine ⟨λ ha, ⟨const β a, mem_image_of_mem _ ha, mem_image_const_self.2 ht⟩, _⟩, rintro ⟨f, hf, ha⟩, rw mem_image at hf ha, obtain ⟨b, hb, rfl⟩ := hf, obtain ⟨_, _, rfl⟩ := ha, exact hb } end, seq_right_eq := λ α β s t, begin rw [seq_def, fmap_def, seq_right_def], obtain rfl | hs := s.eq_empty_or_nonempty, { rw [if_pos rfl, image_empty, sup_empty, bot_eq_empty] }, { ext a, rw [if_neg hs.ne_empty, mem_sup], refine ⟨λ ha, ⟨id, mem_image_const_self.2 hs, by rwa image_id⟩, _⟩, rintro ⟨f, hf, ha⟩, rw mem_image at hf ha, obtain ⟨b, hb, rfl⟩ := ha, obtain ⟨_, _, rfl⟩ := hf, exact hb } end, pure_seq_eq_map := λ α β f s, sup_singleton, map_pure := λ α β f a, image_singleton _ _, seq_pure := λ α β s a, sup_singleton'' _ _, seq_assoc := λ α β γ s t u, begin ext a, simp_rw [seq_def, fmap_def], simp only [exists_prop, mem_sup, mem_image], split, { rintro ⟨g, hg, b, ⟨f, hf, a, ha, rfl⟩, rfl⟩, exact ⟨g ∘ f, ⟨comp g, ⟨g, hg, rfl⟩, f, hf, rfl⟩, a, ha, rfl⟩ }, { rintro ⟨c, ⟨_, ⟨g, hg, rfl⟩, f, hf, rfl⟩, a, ha, rfl⟩, exact ⟨g, hg, f a, ⟨f, hf, a, ha, rfl⟩, rfl⟩ } end, .. finset.is_lawful_functor } instance : is_comm_applicative finset := { commutative_prod := λ α β s t, begin simp_rw [seq_def, fmap_def, sup_image, sup_eq_bUnion], change s.bUnion (λ a, t.image $ λ b, (a, b)) = t.bUnion (λ b, s.image $ λ a, (a, b)), transitivity s ×ˢ t; [rw product_eq_bUnion, rw product_eq_bUnion_right]; congr; ext; simp_rw mem_image, end, .. finset.is_lawful_applicative } end applicative /-! ### Monad -/ section monad variables [Π P, decidable P] instance : monad finset := { bind := λ α β, @sup _ _ _ _, .. finset.applicative } @[simp] lemma bind_def {α β} : (>>=) = @sup (finset α) β _ _ := rfl instance : is_lawful_monad finset := { bind_pure_comp_eq_map := λ α β f s, sup_singleton'' _ _, bind_map_eq_seq := λ α β t s, rfl, pure_bind := λ α β t s, sup_singleton, bind_assoc := λ α β γ s f g, by { convert sup_bUnion _ _, exact sup_eq_bUnion _ _ }, .. finset.is_lawful_applicative } end monad /-! ### Alternative functor -/ section alternative variables [Π P, decidable P] instance : alternative finset := { orelse := λ α, (∪), failure := λ α, ∅, .. finset.applicative } end alternative /-! ### Traversable functor -/ section traversable variables {α β γ : Type u} {F G : Type u → Type u} [applicative F] [applicative G] [is_comm_applicative F] [is_comm_applicative G] /-- Traverse function for `finset`. -/ def traverse [decidable_eq β] (f : α → F β) (s : finset α) : F (finset β) := multiset.to_finset <$> multiset.traverse f s.1 @[simp] lemma id_traverse [decidable_eq α] (s : finset α) : traverse id.mk s = s := by { rw [traverse, multiset.id_traverse], exact s.val_to_finset } open_locale classical @[simp] lemma map_comp_coe (h : α → β) : functor.map h ∘ multiset.to_finset = multiset.to_finset ∘ functor.map h := funext $ λ s, image_to_finset lemma map_traverse (g : α → G β) (h : β → γ) (s : finset α) : functor.map h <$> traverse g s = traverse (functor.map h ∘ g) s := begin unfold traverse, simp only [map_comp_coe] with functor_norm, rw [is_lawful_functor.comp_map, multiset.map_traverse], end end traversable end finset
8bdd39e1133fa9be5062d6b75c03af0e96636c5c
618003631150032a5676f229d13a079ac875ff77
/src/tactic/localized.lean
bbea53c3063e1e53e0848c729f0dadb966e8fade
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
5,335
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.core /-! # Localized notation This consists of two user-commands which allow you to declare notation and commands localized to a namespace. * Declare notation which is localized to a namespace using: ```lean localized "infix ` ⊹ `:60 := my_add" in my.add ``` * After this command it will be available in the same section/namespace/file, just as if you wrote `local infix ` ⊹ `:60 := my_add` * You can open it in other places. The following command will declare the notation again as local notation in that section/namespace/files: ```lean open_locale my.add ``` * More generally, the following will declare all localized notation in the specified namespaces. ```lean open_locale namespace1 namespace2 ... ``` * You can also declare other localized commands, like local attributes ```lean localized "attribute [simp] le_refl" in le ``` The code is inspired by code from Gabriel Ebner from the [hott3 repository](https://github.com/gebner/hott3). -/ open lean lean.parser interactive tactic native reserve notation `localized` @[user_attribute] meta def localized_attr : user_attribute (rb_lmap name string) unit := { name := "_localized", descr := "(interal) attribute that flags localized commands", cache_cfg := ⟨λ ns, (do dcls ← ns.mmap (λ n, mk_const n >>= eval_expr (name × string)), return $ rb_lmap.of_list dcls), []⟩ } /-- Get all commands in the given notation namespace and return them as a list of strings -/ meta def get_localized (ns : list name) : tactic (list string) := do m ← localized_attr.get_cache, ns.mfoldl (λ l nm, match m.find nm with | [] := fail format!"locale {nm} does not exist" | new_l := return $ l.append new_l end) [] /-- Execute all commands in the given notation namespace -/ @[user_command] meta def open_locale_cmd (_ : parse $ tk "open_locale") : parser unit := do ns ← many ident, cmds ← get_localized ns, cmds.mmap' emit_code_here /-- Add a new command to a notation namespace and execute it right now. The new command is added as a declaration to the environment with name `_localized_decl.<number>`. This declaration has attribute `_localized` and as value a name-string pair. -/ @[user_command] meta def localized_cmd (_ : parse $ tk "localized") : parser unit := do cmd ← parser.pexpr, cmd ← i_to_expr cmd, cmd ← eval_expr string cmd, let cmd := "local " ++ cmd, emit_code_here cmd, tk "in", nm ← ident, env ← get_env, let dummy_decl_name := mk_num_name `_localized_decl ((string.hash (cmd ++ nm.to_string) + env.fingerprint) % unsigned_sz), add_decl (declaration.defn dummy_decl_name [] `(name × string) (reflect (⟨nm, cmd⟩ : name × string)) (reducibility_hints.regular 1 tt) ff), localized_attr.set dummy_decl_name unit.star tt /-- This consists of two user-commands which allow you to declare notation and commands localized to a namespace. * Declare notation which is localized to a namespace using: ```lean localized \"infix ` ⊹ `:60 := my_add\" in my.add ``` * After this command it will be available in the same section/namespace/file, just as if you wrote `local infix ` ⊹ `:60 := my_add` * You can open it in other places. The following command will declare the notation again as local notation in that section/namespace/files: ```lean open_locale my.add ``` * More generally, the following will declare all localized notation in the specified namespaces. ```lean open_locale namespace1 namespace2 ... ``` * You can also declare other localized commands, like local attributes ```lean localized \"attribute [simp] le_refl\" in le ``` * To see all localized commands in a given namespace, run: ```lean run_cmd print_localized_commands [`my.add]. ``` * To see a list of all namespaces with localized commands, run: ```lean run_cmd do m ← localized_attr.get_cache, tactic.trace m.keys -- change to `tactic.trace m.to_list` -- to list all the commands in each namespace ``` * Warning 1: as a limitation on user commands, you cannot put `open_locale` directly after your imports. You have to write another command first (e.g. `open`, `namespace`, `universe variables`, `noncomputable theory`, `run_cmd tactic.skip`, ...). * Warning 2: You have to fully specify the names used in localized notation, so that the localized notation also works when the appropriate namespaces are not opened. -/ add_tactic_doc { name := "localized notation", category := doc_category.cmd, decl_names := [`localized_cmd, `open_locale_cmd], tags := ["notation", "type classes"] } /-- Print all commands in a given notation namespace -/ meta def print_localized_commands (ns : list name) : tactic unit := do cmds ← get_localized ns, cmds.mmap' trace -- you can run `open_locale classical` to get the decidability of all propositions. localized "attribute [instance, priority 9] classical.prop_decidable" in classical localized "postfix `?`:9001 := optional" in parser localized "postfix *:9001 := lean.parser.many" in parser
117c4e8bc7da39d0883a05515654b28011feeedc
47181b4ef986292573c77e09fcb116584d37ea8a
/src/ostrowski/rationals/unbounded.lean
b085a1058d20117a06553564370a4af735cf5708
[ "MIT" ]
permissive
RaitoBezarius/berkovich-spaces
87662a2bdb0ac0beed26e3338b221e3f12107b78
0a49f75a599bcb20333ec86b301f84411f04f7cf
refs/heads/main
1,690,520,666,912
1,629,328,012,000
1,629,328,012,000
332,238,095
4
0
MIT
1,629,312,085,000
1,611,414,506,000
Lean
UTF-8
Lean
false
false
15,005
lean
import data.real.basic import data.real.cau_seq import analysis.special_functions.pow import for_mathlib.nat_digits import for_mathlib.geom_sum import for_mathlib.valuations import for_mathlib.specific_limits lemma tendsto_aux1 (n: ℕ) (α: ℝ) {C: ℝ} (C_pos: C > 0): filter.tendsto (λ (N : ℕ), C ^ ((1: ℝ) / N) * ↑n ^ α) filter.at_top (nhds (↑n ^ α)) := begin convert filter.tendsto.mul_const ((n: ℝ)^α) (tendsto_root_at_top_nhds_1_of_pos C_pos), rw one_mul, end lemma technical_aux1 {C: ℝ} {N: ℕ} {n: ℕ} {α: ℝ} (C_pos: C > 0) (N_pos: N ≠ 0) (n_pow_pos: 0 < (n: ℝ) ^ α) (C_pow_pos: 0 < C ^ ((N: ℝ)⁻¹)): (C ^ ((N: ℝ)⁻¹) * (n: ℝ) ^ α) ^ (N: ℝ) = C * ((n ^ N): ℝ) ^ α := begin rw real.mul_rpow, congr' 1, -- (C^(1/N))^N = C { -- FIXME(Ryan): investigate why cannot use real.rpow_nat_inv_pow_nat properly? rw [← real.rpow_mul, inv_mul_cancel, real.rpow_one], exact_mod_cast N_pos, exact le_of_lt C_pos, }, -- (n^α)^N = (n^N)^α { rw ← real.rpow_mul, rw mul_comm α (↑N), rw real.rpow_mul, simp only [real.rpow_nat_cast, nat.cast_pow], all_goals { norm_cast, exact nat.zero_le n, }, }, { exact le_of_lt C_pow_pos }, { exact le_of_lt n_pow_pos }, end lemma sum_le_sum_abv_aux1 {b: ℝ} {l: list ℕ} {abv: ℚ → ℝ} [is_absolute_value abv] (hb_nonneg: 0 ≤ b) (h_abs : ∀ (a: ℕ), a ∈ l → abv a ≤ 1): list.sum (l.map_with_index (λ (i a: ℕ), abv a * b ^ i)) ≤ list.sum (l.map_with_index (λ (i a: ℕ), b ^ i)) := begin have : (λ (i a : ℕ), (abv a) * b ^ i) = (λ (i a : ℕ), b ^ i * (abv a)), { ext, rw mul_comm }, rw this, clear this, simp [list.map_with_index_eq_enum_map, list.enum_eq_zip_range, list.map_uncurry_zip_eq_zip_with], rw [← list.zip_with_map], have : list.take l.length = list.take (list.map (pow (b : ℝ)) (list.range l.length)).length, { congr' 1, simp }, rw [this, list.take_length], clear this, refine list.sum_ext_le (by simp) _, intros i hi, let k : ℕ := l.nth_le i (by simpa using hi), specialize h_abs k (list.nth_le_mem _ _ _), simp, suffices: (b: ℝ) ^ i * abv k ≤ b ^ i * 1, { simpa using this }, refine mul_le_mul (le_refl _) h_abs (is_absolute_value.abv_nonneg abv k) (pow_nonneg hb_nonneg i), end lemma exists_nonneg_const_nat_abs_le_const_mul_pow_alpha {abv: ℚ → ℝ} [habv: is_absolute_value abv] {n₀: ℕ} {α: ℝ} (h_exponent_pos: 0 < α) (h_n0_ge_2: n₀ ≥ 2) (h_abv_n0: abv n₀ = (n₀: ℝ) ^ α) (h_abv_n0_gt_one: abv n₀ > 1) (h_smallest: ∀ (a: ℕ), a < n₀ → abv a ≤ 1): ∃ (C: ℝ) (C_pos: C > 0), ∀ (n: ℕ), abv n ≤ C * n^α := begin set C := (1 - ((n₀: ℝ) ^ α)⁻¹)⁻¹ with hc, use C, have h_n0_pow_alpha_pos: 0 < (n₀: ℝ)^α, { apply real.rpow_pos_of_pos, refine lt_of_lt_of_le zero_lt_two _, norm_cast, exact h_n0_ge_2, }, have h_n0_pow_alpha_inv_lt_one: ((n₀: ℝ) ^ α)⁻¹ < 1, { apply inv_lt_one, rw h_abv_n0 at h_abv_n0_gt_one, exact h_abv_n0_gt_one, }, have C_pos: C > 0, { apply inv_pos.1, rw [hc, inv_inv', sub_pos], exact h_n0_pow_alpha_inv_lt_one, }, split, { exact C_pos }, { intro n, by_cases hn: n = 0, rw_mod_cast [hn, is_absolute_value.abv_zero abv, real.zero_rpow, mul_zero], exact ne_of_gt h_exponent_pos, set base_repr := n₀.digits n with h_base_repr, have h_coeff_abv_pos: ∀ (a: ℕ), a ∈ base_repr → abv a ≤ 1, { intros a h_a_in_base_repr, apply h_smallest, rw h_base_repr at h_a_in_base_repr, exact nat.digits_lt_base (h_n0_ge_2) h_a_in_base_repr, }, have h_n0_pow_alpha_inv_nonneg: 0 ≤ ((n₀: ℝ) ^ α)⁻¹, from inv_nonneg.2 (le_of_lt h_n0_pow_alpha_pos), have h_n0_pow_alpha_pow_len_pos: 0 < ((n₀: ℝ) ^ α) ^ (base_repr.length - 1), from pow_pos (h_n0_pow_alpha_pos) _, have h_n0_pow_neq_0: (n₀: ℝ) ^ α ≠ 0, from ne_of_gt h_n0_pow_alpha_pos, have h_n0_pow_neq_1: (n₀: ℝ) ^ α ≠ 1, { rw ← h_abv_n0, exact ne_of_gt h_abv_n0_gt_one }, have h_n0_pow_alpha_pow_len_le_n_pow_alpha: ((n₀: ℝ) ^ α) ^ (base_repr.length - 1) ≤ (n: ℝ) ^ α, { have h_n0_nonneg: 0 ≤ n₀, from le_trans zero_le_two h_n0_ge_2, suffices: ((n₀: ℝ) ^ α) ^ (base_repr.length - 1) = ((n₀: ℝ) ^ (base_repr.length - 1)) ^ α, { rw this, apply real.rpow_le_rpow, apply pow_nonneg, norm_cast, exact h_n0_nonneg, rw h_base_repr, norm_cast, apply (mul_le_mul_right (lt_of_lt_of_le zero_lt_two h_n0_ge_2)).1, rw [← pow_succ', nat.sub_add_cancel], conv_rhs { rw mul_comm, }, apply nat.base_pow_length_digits_le _ n h_n0_ge_2 hn, exact one_le_of_nonzero_digits_length _ _ hn, exact le_of_lt h_exponent_pos, }, rw [← real.rpow_nat_cast _ (base_repr.length - 1), ← real.rpow_mul, mul_comm, real.rpow_mul, real.rpow_nat_cast _ (base_repr.length - 1)], all_goals { norm_cast, exact h_n0_nonneg }, }, have h_aux1: base_repr.length - 1 + 1 = base_repr.length, from nat.sub_add_cancel (one_le_of_nonzero_digits_length n n₀ hn), exact calc (abv n: ℝ) = abv (nat.of_digits n₀ base_repr) : by rw_mod_cast [h_base_repr, nat.of_digits_digits n₀ n] ... = abv (list.sum (base_repr.map_with_index (λ i a, a * (n₀: ℚ) ^ i))) : fun_of_digits_eq_fun_of_sum_map_with_index abv n₀ base_repr ... ≤ list.sum (base_repr.map_with_index (λ i a, abv ((a: ℚ) * (n₀ : ℚ) ^ i))) : by { rw ← list.map_map_with_index, exact list.abv_sum_le_sum_abv abv _ } ... = list.sum (base_repr.map_with_index (λ i a, (abv a) * (abv n₀) ^ i)) : by simp [is_absolute_value.abv_mul abv, is_absolute_value.abv_pow abv] ... = list.sum (base_repr.map_with_index (λ (i a: ℕ), (abv a) * ((n₀: ℝ) ^ α) ^ i)) : by rw_mod_cast h_abv_n0 ... ≤ list.sum (base_repr.map_with_index (λ (i a: ℕ), ((n₀: ℝ) ^ α) ^ i)) : sum_le_sum_abv_aux1 (le_of_lt h_n0_pow_alpha_pos) h_coeff_abv_pos ... = list.sum (list.map (pow ((n₀: ℝ) ^ α)) (list.range base_repr.length)) : by rw list.map_with_index_eq_range_map (λ i a, ((n₀ : ℝ) ^ α) ^ i) (λ i, ((n₀ : ℝ) ^ α) ^ i) base_repr (by simp) ... = geom_sum ((n₀: ℝ) ^ α) (base_repr.length) : geom_sum_of_sum_of_range_map ((n₀: ℝ) ^ α) base_repr.length ... = (n₀ ^ α) ^ (base_repr.length - 1) * geom_sum (((n₀: ℝ) ^ α)⁻¹) (base_repr.length) : by { rw ← h_aux1, exact geom_sum_eq_factor_inv_geom_sum (base_repr.length - 1) h_n0_pow_neq_0 h_n0_pow_neq_1} ... ≤ (n₀ ^ α) ^ (base_repr.length - 1) * ∑' n: ℕ, (((n₀: ℝ) ^ α)⁻¹) ^ n : (mul_le_mul_left h_n0_pow_alpha_pow_len_pos).2 $ real.finite_geom_sum_le_infinite_geom_sum_of_lt_1 (base_repr.length) h_n0_pow_alpha_inv_nonneg (by assumption) ... = (n₀ ^ α) ^ (base_repr.length - 1) * C : by erw tsum_geometric_of_lt_1 (inv_nonneg.2 (le_of_lt h_n0_pow_alpha_pos)) h_n0_pow_alpha_inv_lt_one ... ≤ n^α * C : (mul_le_mul_right C_pos).2 h_n0_pow_alpha_pow_len_le_n_pow_alpha ... = C * n^α : mul_comm _ _, }, end lemma nat_abs_val_le_nat_pow_alpha {abv: ℚ → ℝ} [habv: is_absolute_value abv] {n₀: ℕ} {n: ℕ} {α: ℝ} (h_exponent_pos: 0 < α) (h_n0_ge_2: n₀ ≥ 2) (h_abv_n0: abv n₀ = (n₀: ℝ) ^ α) (h_abv_n0_gt_one: abv n₀ > 1) (h_smallest: ∀ (a: ℕ), a < n₀ → abv a ≤ 1): (abv n: ℝ) ≤ n^α := begin obtain ⟨ C, ⟨ C_pos, abv_pos ⟩ ⟩ := exists_nonneg_const_nat_abs_le_const_mul_pow_alpha h_exponent_pos h_n0_ge_2 h_abv_n0 h_abv_n0_gt_one h_smallest, have h_nthroot: ∀ᶠ (N: ℕ) in filter.at_top, abv n ≤ C^((1:ℝ)/N) * n^α, { simp, use 1, intros N N_pos, by_cases hn: n = 0, rw_mod_cast [hn, is_absolute_value.abv_zero abv, real.zero_rpow (ne_of_gt h_exponent_pos), mul_zero], have C_pow_pos: 0 < C^((N: ℝ)⁻¹), from real.rpow_pos_of_pos C_pos _, have n_pow_alpha_pos: 0 < (n: ℝ)^α, from real.rpow_pos_of_pos (by exact_mod_cast nat.pos_of_ne_zero hn) _, have N_pos: 0 < (N: ℝ), by norm_cast; exact lt_of_lt_of_le zero_lt_one N_pos, apply (real.rpow_le_rpow_iff _ _ N_pos).1, -- |n|^N ≤ (C^(1/N)*n^α)^N { convert abv_pos (n ^ N), -- |n|^N = |n^N| { simp, symmetry, exact is_absolute_value.abv_pow abv n N, }, -- (C^(1/N)n^α)^N = C(n^N)^α { exact_mod_cast technical_aux1 C_pos (by exact_mod_cast ne_of_gt N_pos) n_pow_alpha_pos (by exact_mod_cast C_pow_pos), }, }, apply habv.abv_nonneg, { -- C > 0 → C^(1/N) > 0 as N > 0 -- n > 0 → n^α > 0 as α > 0 -- therefore C^(1/N) * n^α > 0 apply (zero_le_mul_left (gt_iff_lt.1 C_pow_pos)).2, exact le_of_lt (gt_iff_lt.1 n_pow_alpha_pos), } }, exact ge_of_tendsto (tendsto_aux1 n α C_pos) h_nthroot, end lemma exists_nonneg_const_pow_alpha_le_abs_nat {abv: ℚ → ℝ} [habv: is_absolute_value abv] {n₀: ℕ} {α: ℝ} (h_exponent_pos: 0 < α) (h_n0_ge_2: n₀ ≥ 2) (h_abv_n0: abv n₀ = (n₀: ℝ) ^ α) (h_abv_n0_gt_one: abv n₀ > 1) (h_smallest: ∀ (a: ℕ), a < n₀ → abv a ≤ 1): ∃ (C: ℝ) (C_pos: C > 0), ∀ (n: ℕ), C * n^α ≤ abv n := begin set C := (1 - (1 - (n₀: ℝ)⁻¹) ^ α) with C_def, have C_pos: C > 0, { simp [C_def], apply real.rpow_lt_one, rw sub_nonneg, apply inv_le_one, norm_cast, rotate 1, simp only [sub_lt_self_iff, nat.cast_pos, inv_pos], any_goals { linarith }, }, use C, split, { exact C_pos, }, { intro n, by_cases (n = 0), rw_mod_cast [h, real.zero_rpow, is_absolute_value.abv_zero abv, mul_zero], exact ne_of_gt h_exponent_pos, set base_repr := n₀.digits n with base_repr_def, set s := base_repr.length with s_def, have aux0: n < n₀ ^ s, { rw [s_def, base_repr_def], exact nat.lt_base_pow_length_digits h_n0_ge_2, }, have aux1: abv (n₀ ^ s - n) ≤ (n₀ ^ s - n) ^ α, { convert @nat_abs_val_le_nat_pow_alpha _ _ _ (n₀ ^ s - n) _ h_exponent_pos h_n0_ge_2 h_abv_n0 h_abv_n0_gt_one h_smallest, all_goals { simp [nat.cast_sub (le_of_lt aux0)], }, }, have aux2: ((n₀: ℝ) ^ s - (n₀: ℝ) ^ (s - 1)) ^ α = (n₀: ℝ) ^ (α * s) * (1 - (n₀: ℝ)⁻¹) ^ α, { rw [mul_comm α (s: ℝ), real.rpow_mul, ← real.mul_rpow, mul_sub_left_distrib ((n₀: ℝ) ^ (s: ℝ)) _ _, mul_one, ← real.rpow_neg_one, ← real.rpow_add], congr' 2, rw real.rpow_nat_cast, rw ← sub_eq_add_neg, rw ← real.rpow_nat_cast, congr, rw [nat.cast_sub, nat.cast_one, s_def, base_repr_def], exact one_le_of_nonzero_digits_length n n₀ h, rotate 1, rw real.rpow_nat_cast, apply pow_nonneg, rotate 1, simp, apply inv_le_one, any_goals { norm_cast, linarith }, -- finisher move. }, have aux3: (n: ℝ) ^ α ≤ (n₀: ℝ) ^ (α * s), { rw [mul_comm, real.rpow_mul], apply real.rpow_le_rpow, rotate 1, rw_mod_cast real.rpow_nat_cast _ _, exact le_of_lt aux0, exact le_of_lt h_exponent_pos, all_goals { norm_cast, exact zero_le _, } }, have aux4: ((n₀: ℝ) ^ s - (n: ℝ)) ^ α ≤ ((n₀: ℝ) ^ s - (n₀: ℝ) ^ (s - 1)) ^ α, { apply real.rpow_le_rpow, rw sub_nonneg, any_goals { norm_cast }, exact le_of_lt (nat.lt_base_pow_length_digits h_n0_ge_2), rotate 1, exact le_of_lt h_exponent_pos, apply sub_le_sub_left, have: 0 < (n₀: ℝ) := by exact_mod_cast lt_of_lt_of_le zero_lt_two h_n0_ge_2, apply (mul_le_mul_left this).1, norm_cast, rw ← pow_succ, convert nat.base_pow_length_digits_le n₀ n h_n0_ge_2 h, rw [← base_repr_def, ← s_def, nat.sub_add_cancel], exact one_le_of_nonzero_digits_length n n₀ h, }, calc abv n = abv (n₀ ^ s - (n₀ ^ s - n)) : by abel ... ≥ abv (n₀ ^ s) - abv (n₀ ^ s - n) : is_absolute_value.sub_abv_le_abv_sub abv _ _ ... = (abv n₀) ^ s - abv (n₀ ^ s - n) : by rw is_absolute_value.abv_pow abv _ _ ... ≥ (abv n₀) ^ s - (n₀ ^ s - n) ^ α : sub_le_sub_left aux1 _ ... = (n₀ ^ α) ^ s - (n₀ ^ s - n) ^ α : by rw h_abv_n0 ... = n₀ ^ (α * s) - (n₀ ^ s - n) ^ α : by { rw_mod_cast [real.rpow_mul _ _ _, real.rpow_nat_cast _ _], exact zero_le _ } ... ≥ n₀ ^ (α * s) - (n₀ ^ s - n₀ ^ (s - 1)) ^ α : sub_le_sub_left aux4 _ ... = C * n₀ ^ (α * s) : by rw [mul_comm C _, C_def, mul_sub_left_distrib, mul_one, aux2] ... ≥ C * n ^ α : (mul_le_mul_left C_pos).2 aux3, } end lemma nat_pow_alpha_le_nat_abs_val {abv: ℚ → ℝ} [habv: is_absolute_value abv] {n₀: ℕ} {n: ℕ} {α: ℝ} (h_exponent_pos: 0 < α) (h_n0_ge_2: n₀ ≥ 2) (h_abv_n0: abv n₀ = (n₀: ℝ) ^ α) (h_abv_n0_gt_one: abv n₀ > 1) (h_smallest: ∀ (a: ℕ), a < n₀ → abv a ≤ 1): (n: ℝ)^α ≤ (abv n: ℝ) := begin obtain ⟨ C, ⟨ C_pos, abv_pos ⟩ ⟩ := exists_nonneg_const_pow_alpha_le_abs_nat h_exponent_pos h_n0_ge_2 h_abv_n0 h_abv_n0_gt_one h_smallest, refine le_of_tendsto (tendsto_aux1 n α C_pos) _, { simp only [filter.eventually_at_top, one_div, ge_iff_le], use 1, intros N N_pos, by_cases hn: n = 0, rw_mod_cast [hn, is_absolute_value.abv_zero abv, real.zero_rpow (ne_of_gt h_exponent_pos), mul_zero], have C_pow_pos: 0 < C^((N: ℝ)⁻¹), from real.rpow_pos_of_pos C_pos _, have n_pow_alpha_pos: 0 < (n: ℝ)^α, from real.rpow_pos_of_pos (by exact_mod_cast nat.pos_of_ne_zero hn) _, have N_pos: 0 < (N: ℝ), by norm_cast; exact lt_of_lt_of_le zero_lt_one N_pos, apply (real.rpow_le_rpow_iff _ _ N_pos).1, -- |n|^N ≤ (C^(1/N)*n^α)^N { convert abv_pos (n ^ N), { -- (C^(1/N)n^α)^N = C(n^N)^α exact_mod_cast technical_aux1 C_pos (by exact_mod_cast ne_of_gt N_pos) n_pow_alpha_pos (by exact_mod_cast C_pow_pos), }, -- |n|^N = |n^N| { simp, symmetry, exact is_absolute_value.abv_pow abv n N, }, }, { -- C > 0 → C^(1/N) > 0 as N > 0 -- n > 0 → n^α > 0 as α > 0 -- therefore C^(1/N) * n^α > 0 apply (zero_le_mul_left (gt_iff_lt.1 C_pow_pos)).2, exact le_of_lt (gt_iff_lt.1 n_pow_alpha_pos), }, { exact is_absolute_value.abv_nonneg abv _ }, }, end
566d7b3584f530129de9b8bf7420878390399989
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/spaces.lean
8148124c359f54e294523401d0b0fbe0ddac501d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,647
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.grothendieck import category_theory.sites.pretopology import category_theory.limits.lattice import topology.sets.opens /-! # Grothendieck topology on a topological space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Define the Grothendieck topology and the pretopology associated to a topological space, and show that the pretopology induces the topology. The covering (pre)sieves on `X` are those for which the union of domains contains `X`. ## Tags site, Grothendieck topology, space ## References * [nLab, *Grothendieck topology*](https://ncatlab.org/nlab/show/Grothendieck+topology) * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] ## Implementation notes We define the two separately, rather than defining the Grothendieck topology as that generated by the pretopology for the purpose of having nice definitional properties for the sieves. -/ universe u namespace opens variables (T : Type u) [topological_space T] open category_theory topological_space category_theory.limits /-- The Grothendieck topology associated to a topological space. -/ def grothendieck_topology : grothendieck_topology (opens T) := { sieves := λ X S, ∀ x ∈ X, ∃ U (f : U ⟶ X), S f ∧ x ∈ U, top_mem' := λ X x hx, ⟨_, 𝟙 _, trivial, hx⟩, pullback_stable' := λ X Y S f hf y hy, begin rcases hf y (f.le hy) with ⟨U, g, hg, hU⟩, refine ⟨U ⊓ Y, hom_of_le inf_le_right, _, hU, hy⟩, apply S.downward_closed hg (hom_of_le inf_le_left), end, transitive' := λ X S hS R hR x hx, begin rcases hS x hx with ⟨U, f, hf, hU⟩, rcases hR hf _ hU with ⟨V, g, hg, hV⟩, exact ⟨_, g ≫ f, hg, hV⟩, end } /-- The Grothendieck pretopology associated to a topological space. -/ def pretopology : pretopology (opens T) := { coverings := λ X R, ∀ x ∈ X, ∃ U (f : U ⟶ X), R f ∧ x ∈ U, has_isos := λ X Y f i x hx, by exactI ⟨_, _, presieve.singleton_self _, (inv f).le hx⟩, pullbacks := λ X Y f S hS x hx, begin rcases hS _ (f.le hx) with ⟨U, g, hg, hU⟩, refine ⟨_, _, presieve.pullback_arrows.mk _ _ hg, _⟩, have : U ⊓ Y ≤ pullback g f, refine le_of_hom (pullback.lift (hom_of_le inf_le_left) (hom_of_le inf_le_right) rfl), apply this ⟨hU, hx⟩, end, transitive := λ X S Ti hS hTi x hx, begin rcases hS x hx with ⟨U, f, hf, hU⟩, rcases hTi f hf x hU with ⟨V, g, hg, hV⟩, exact ⟨_, _, ⟨_, g, f, hf, hg, rfl⟩, hV⟩, end } /-- The pretopology associated to a space is the largest pretopology that generates the Grothendieck topology associated to the space. -/ @[simp] lemma pretopology_of_grothendieck : pretopology.of_grothendieck _ (opens.grothendieck_topology T) = opens.pretopology T := begin apply le_antisymm, { intros X R hR x hx, rcases hR x hx with ⟨U, f, ⟨V, g₁, g₂, hg₂, _⟩, hU⟩, exact ⟨V, g₂, hg₂, g₁.le hU⟩ }, { intros X R hR x hx, rcases hR x hx with ⟨U, f, hf, hU⟩, exact ⟨U, f, sieve.le_generate R U hf, hU⟩ }, end /-- The pretopology associated to a space induces the Grothendieck topology associated to the space. -/ @[simp] lemma pretopology_to_grothendieck : pretopology.to_grothendieck _ (opens.pretopology T) = opens.grothendieck_topology T := begin rw ← pretopology_of_grothendieck, apply (pretopology.gi (opens T)).l_u_eq, end end opens
fc0f2c091d0552fe7270dd759c3763e3e45fa83b
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/abelian/basic.lean
a5e6cb05d0aa94d161ce147473dfb813a17f4705
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
22,912
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.shapes.constructions.pullbacks import category_theory.limits.shapes.regular_mono import category_theory.limits.shapes.biproducts import category_theory.limits.shapes.images /-! # Abelian categories This file contains the definition and basic properties of abelian categories. There are many definitions of abelian category. Our definition is as follows: A category is called abelian if it is preadditive, has a zero object, binary products, kernels and cokernels, and if every monomorphism and epimorphism is normal. It should be noted that if we also assume coproducts, then preadditivity is actually a consequence of the other properties. However, this fact is of little practical relevance (and, as of now, there is no proof of this in mathlib), since essentially all interesting abelian categories come with a preadditive structure. In this way, by requiring preadditivity, we allow the user to pass in the preadditive structure the specific category they are working with has natively. ## Main definitions * `abelian` is the type class indicating that a category is abelian. It extends `preadditive`. * `abelian.image f` is `kernel (cokernel.π f)`, and * `abelian.coimage f` is `cokernel (kernel.ι f)`. ## Main results * In an abelian category, mono + epi = iso. * If `f : X ⟶ Y`, then the map `factor_thru_image f : X ⟶ image f` is an epimorphism, and the map `factor_thru_coimage f : coimage f ⟶ Y` is a monomorphism. * Factoring through the image and coimage is a strong epi-mono factorisation. This means that * every abelian category has images. We instantiated this in such a way that `abelian.image f` is definitionally equal to `limits.image f`, and * there is a canonical isomorphism `coimage_iso_image : coimage f ≅ image f` such that `coimage.π f ≫ (coimage_iso_image f).hom ≫ image.ι f = f`. The lemma stating this is called `full_image_factorisation`. * Every epimorphism is a cokernel of its kernel. Every monomorphism is a kernel of its cokernel. * The pullback of an epimorphism is an epimorphism. The pushout of a monomorphism is a monomorphism. (This is not to be confused with the fact that the pullback of a monomorphism is a monomorphism, which is true in any category). ## Implementation notes We don't show this yet, but abelian categories are finitely complete and finitely cocomplete. However, the limits we can construct at this level of generality will most likely be less nice than the ones that can be created in specific applications. For this reason, we adopt the following convention: * If the statement of a theorem involves limits, the existence of these limits should be made an explicit typeclass parameter. * If a limit only appears in a proof, but not in the statement of a theorem, the limit should not be a typeclass parameter, but instead be created using `abelian.has_pullbacks` or a similar definition. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] * [P. Aluffi, *Algebra: Chaper 0*][aluffi2016] -/ open category_theory open category_theory.preadditive open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables (C) section prio set_option default_priority 100 /-- A (preadditive) category `C` is called abelian if it has a zero object, all binary products and coproducts, all kernels and cokernels, and if every monomorphism is the kernel of some morphism and every epimorphism is the cokernel of some morphism. -/ class abelian extends preadditive.{v} C := [has_zero_object : has_zero_object.{v} C] [has_binary_products : has_binary_products.{v} C] [has_kernels : has_kernels.{v} C] [has_cokernels : has_cokernels.{v} C] (normal_mono : Π {X Y : C} (f : X ⟶ Y) [mono f], normal_mono.{v} f) (normal_epi : Π {X Y : C} (f : X ⟶ Y) [epi f], normal_epi.{v} f) attribute [instance] abelian.has_zero_object attribute [instance] abelian.has_binary_products attribute [instance] abelian.has_kernels abelian.has_cokernels end prio end category_theory open category_theory namespace category_theory.abelian variables {C : Type u} [category.{v} C] [abelian.{v} C] section strong local attribute [instance] abelian.normal_epi /-- In an abelian category, every epimorphism is strong. -/ def strong_epi_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := by apply_instance end strong section mono_epi_iso variables {X Y : C} (f : X ⟶ Y) local attribute [instance] strong_epi_of_epi /-- In an abelian category, a monomorphism which is also an epimorphism is an isomorphism. -/ def is_iso_of_mono_of_epi [mono f] [epi f] : is_iso f := is_iso_of_mono_of_strong_epi _ end mono_epi_iso section factor variables {P Q : C} (f : P ⟶ Q) /-- The kernel of the cokernel of `f` is called the image of `f`. -/ protected abbreviation image : C := kernel (cokernel.π f) /-- The inclusion of the image into the codomain. -/ protected abbreviation image.ι : abelian.image f ⟶ Q := kernel.ι (cokernel.π f) /-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/ protected abbreviation factor_thru_image : P ⟶ abelian.image f := kernel.lift (cokernel.π f) f $ cokernel.condition f /-- `f` factors through its image via the canonical morphism `p`. -/ @[simp, reassoc] protected lemma image.fac : abelian.factor_thru_image f ≫ image.ι f = f := kernel.lift_ι _ _ _ /-- The map `p : P ⟶ image f` is an epimorphism -/ instance : epi (abelian.factor_thru_image f) := let I := abelian.image f, p := abelian.factor_thru_image f, i := kernel.ι (cokernel.π f) in -- It will suffice to consider some g : I ⟶ R such that p ≫ g = 0 and show that g = 0. epi_of_cancel_zero _ $ λ R (g : I ⟶ R) (hpg : p ≫ g = 0), begin -- Since C is abelian, u := ker g ≫ i is the kernel of some morphism h. let u := kernel.ι g ≫ i, haveI : mono u := mono_comp _ _, have hu := abelian.normal_mono u, let h := hu.g, -- By hypothesis, p factors through the kernel of g via some t. obtain ⟨t, ht⟩ := kernel.lift' g p hpg, have fh : f ≫ h = 0, calc f ≫ h = (p ≫ i) ≫ h : (image.fac f).symm ▸ rfl ... = ((t ≫ kernel.ι g) ≫ i) ≫ h : ht ▸ rfl ... = t ≫ u ≫ h : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc } ... = t ≫ 0 : hu.w ▸ rfl ... = 0 : has_zero_morphisms.comp_zero _ _, -- h factors through the cokernel of f via some l. obtain ⟨l, hl⟩ := cokernel.desc' f h fh, have hih : i ≫ h = 0, calc i ≫ h = i ≫ cokernel.π f ≫ l : hl ▸ rfl ... = 0 ≫ l : by rw [←category.assoc, kernel.condition] ... = 0 : has_zero_morphisms.zero_comp _ _, -- i factors through u = ker h via some s. obtain ⟨s, hs⟩ := normal_mono.lift' u i hih, have hs' : (s ≫ kernel.ι g) ≫ i = 𝟙 I ≫ i, by rw [category.assoc, hs, category.id_comp], haveI : epi (kernel.ι g) := epi_of_epi_fac ((cancel_mono _).1 hs'), -- ker g is an epimorphism, but ker g ≫ g = 0 = ker g ≫ 0, so g = 0 as required. exact zero_of_epi_comp _ (kernel.condition g) end instance mono_factor_thru_image [mono f] : mono (abelian.factor_thru_image f) := mono_of_mono_fac $ image.fac f instance is_iso_factor_thru_image [mono f] : is_iso (abelian.factor_thru_image f) := is_iso_of_mono_of_epi _ /-- Factoring through the image is a strong epi-mono factorisation. -/ @[simps] def image_strong_epi_mono_factorisation : strong_epi_mono_factorisation f := { I := abelian.image f, m := image.ι f, m_mono := by apply_instance, e := abelian.factor_thru_image f, e_strong_epi := strong_epi_of_epi _ } /-- The cokernel of the kernel of `f` is called the coimage of `f`. -/ protected abbreviation coimage : C := cokernel (kernel.ι f) /-- The projection onto the coimage. -/ protected abbreviation coimage.π : P ⟶ abelian.coimage f := cokernel.π (kernel.ι f) /-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/ protected abbreviation factor_thru_coimage : abelian.coimage f ⟶ Q := cokernel.desc (kernel.ι f) f $ kernel.condition f /-- `f` factors through its coimage via the canonical morphism `p`. -/ protected lemma coimage.fac : coimage.π f ≫ abelian.factor_thru_coimage f = f := cokernel.π_desc _ _ _ /-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/ instance : mono (abelian.factor_thru_coimage f) := let I := abelian.coimage f, i := abelian.factor_thru_coimage f, p := cokernel.π (kernel.ι f) in mono_of_cancel_zero _ $ λ R (g : R ⟶ I) (hgi : g ≫ i = 0), begin -- Since C is abelian, u := p ≫ coker g is the cokernel of some morphism h. let u := p ≫ cokernel.π g, haveI : epi u := epi_comp _ _, have hu := abelian.normal_epi u, let h := hu.g, -- By hypothesis, i factors through the cokernel of g via some t. obtain ⟨t, ht⟩ := cokernel.desc' g i hgi, have hf : h ≫ f = 0, calc h ≫ f = h ≫ (p ≫ i) : (coimage.fac f).symm ▸ rfl ... = h ≫ (p ≫ (cokernel.π g ≫ t)) : ht ▸ rfl ... = h ≫ u ≫ t : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc } ... = 0 ≫ t : by rw [←category.assoc, hu.w] ... = 0 : has_zero_morphisms.zero_comp _ _, -- h factors through the kernel of f via some l. obtain ⟨l, hl⟩ := kernel.lift' f h hf, have hhp : h ≫ p = 0, calc h ≫ p = (l ≫ kernel.ι f) ≫ p : hl ▸ rfl ... = l ≫ 0 : by rw [category.assoc, cokernel.condition] ... = 0 : has_zero_morphisms.comp_zero _ _, -- p factors through u = coker h via some s. obtain ⟨s, hs⟩ := normal_epi.desc' u p hhp, have hs' : p ≫ cokernel.π g ≫ s = p ≫ 𝟙 I, by rw [←category.assoc, hs, category.comp_id], haveI : mono (cokernel.π g) := mono_of_mono_fac ((cancel_epi _).1 hs'), -- coker g is a monomorphism, but g ≫ coker g = 0 = 0 ≫ coker g, so g = 0 as required. exact zero_of_comp_mono _ (cokernel.condition g) end instance epi_factor_thru_coimage [epi f] : epi (abelian.factor_thru_coimage f) := epi_of_epi_fac $ coimage.fac f instance is_iso_factor_thru_coimage [epi f] : is_iso (abelian.factor_thru_coimage f) := is_iso_of_mono_of_epi _ /-- Factoring through the coimage is a strong epi-mono factorisation. -/ @[simps] def coimage_strong_epi_mono_factorisation : strong_epi_mono_factorisation f := { I := abelian.coimage f, m := abelian.factor_thru_coimage f, m_mono := by apply_instance, e := coimage.π f, e_strong_epi := strong_epi_of_epi _ } end factor section has_strong_epi_mono_factorisations /-- An abelian category has strong epi-mono factorisations. -/ @[priority 100] instance : has_strong_epi_mono_factorisations.{v} C := ⟨λ X Y f, image_strong_epi_mono_factorisation f⟩ /- In particular, this means that it has well-behaved images. -/ example : has_images.{v} C := by apply_instance example : has_image_maps.{v} C := by apply_instance end has_strong_epi_mono_factorisations section images variables {X Y : C} (f : X ⟶ Y) lemma image_eq_image : limits.image f = abelian.image f := rfl /-- There is a canonical isomorphism between the coimage and the image of a morphism. -/ abbreviation coimage_iso_image : abelian.coimage f ≅ abelian.image f := is_image.iso_ext (coimage_strong_epi_mono_factorisation f).to_mono_is_image (image_strong_epi_mono_factorisation f).to_mono_is_image lemma full_image_factorisation : coimage.π f ≫ (coimage_iso_image f).hom ≫ image.ι f = f := by rw [limits.is_image.iso_ext_hom, ←image_strong_epi_mono_factorisation_to_mono_factorisation_m, is_image.lift_fac, coimage_strong_epi_mono_factorisation_to_mono_factorisation_m, coimage.fac] end images section cokernel_of_kernel variables {X Y : C} {f : X ⟶ Y} /-- In an abelian category, an epi is the cokernel of its kernel. More precisely: If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel of `fork.ι s`. -/ def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) : is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) := is_cokernel.cokernel_iso _ _ (cokernel.of_iso_comp _ _ (limits.is_limit.cone_point_unique_up_to_iso (limit.is_limit _) h) (cone_morphism.w (limits.is_limit.unique_up_to_iso (limit.is_limit _) h).hom _)) (as_iso $ abelian.factor_thru_coimage f) (coimage.fac f) /-- In an abelian category, a mono is the kernel of its cokernel. More precisely: If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel of `cofork.π s`. -/ def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) : is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) := is_kernel.iso_kernel _ _ (kernel.of_comp_iso _ _ (limits.is_colimit.cocone_point_unique_up_to_iso h (colimit.is_colimit _)) (cocone_morphism.w (limits.is_colimit.unique_up_to_iso h $ colimit.is_colimit _).hom _)) (as_iso $ abelian.factor_thru_image f) (image.fac f) end cokernel_of_kernel section local attribute [instance] preadditive.has_equalizers_of_has_kernels /-- Any abelian category has pullbacks -/ def has_pullbacks : has_pullbacks.{v} C := has_pullbacks_of_has_binary_products_of_has_equalizers C end section local attribute [instance] preadditive.has_coequalizers_of_has_cokernels local attribute [instance] has_preadditive_binary_biproducts_of_has_binary_products /-- Any abelian category has pushouts -/ def has_pushouts : has_pushouts.{v} C := has_pushouts_of_has_binary_coproducts_of_has_coequalizers C end namespace pullback_to_biproduct_is_kernel variables [limits.has_pullbacks.{v} C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) local attribute [instance] has_preadditive_binary_biproducts_of_has_binary_products /-! This section contains a slightly technical result about pullbacks and biproducts. We will need it in the proof that the pullback of an epimorphism is an epimorpism. -/ /-- The canonical map `pullback f g ⟶ X ⊞ Y` -/ abbreviation pullback_to_biproduct : pullback f g ⟶ X ⊞ Y := biprod.lift pullback.fst pullback.snd /-- The canonical map `pullback f g ⟶ X ⊞ Y` induces a kernel cone on the map `biproduct X Y ⟶ Z` induced by `f` and `g`. A slightly more intuitive way to think of this may be that it induces an equalizer fork on the maps induced by `(f, 0)` and `(0, g)`. -/ abbreviation pullback_to_biproduct_fork : kernel_fork (biprod.desc f (-g)) := kernel_fork.of_ι (pullback_to_biproduct f g) $ by rw [biprod.lift_desc, comp_neg, pullback.condition, add_right_neg] local attribute [irreducible] has_limit_cospan_of_has_limit_pair_of_has_limit_parallel_pair /-- The canonical map `pullback f g ⟶ X ⊞ Y` is a kernel of the map induced by `(f, -g)`. -/ def is_limit_pullback_to_biproduct : is_limit (pullback_to_biproduct_fork f g) := fork.is_limit.mk _ (λ s, pullback.lift (fork.ι s ≫ biprod.fst) (fork.ι s ≫ biprod.snd) $ sub_eq_zero.1 $ by rw [category.assoc, category.assoc, ←comp_sub, sub_eq_add_neg, ←comp_neg, biprod.fst_add_snd, kernel_fork.condition s]) (λ s, begin ext; rw [fork.ι_of_ι, category.assoc], { rw [prod.lift_fst, pullback.lift_fst] }, { rw [prod.lift_snd, pullback.lift_snd] } end) (λ s m h, by ext; simp [fork.ι_eq_app_zero, ←h walking_parallel_pair.zero]) end pullback_to_biproduct_is_kernel namespace biproduct_to_pushout_is_cokernel variables [limits.has_pushouts.{v} C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) local attribute [instance] has_preadditive_binary_biproducts_of_has_binary_products /-- The canonical map `Y ⊞ Z ⟶ pushout f g` -/ abbreviation biproduct_to_pushout : Y ⊞ Z ⟶ pushout f g := biprod.desc pushout.inl pushout.inr /-- The canonical map `Y ⊞ Z ⟶ pushout f g` induces a cokernel cofork on the map `X ⟶ Y ⊞ Z` induced by `f` and `-g`. -/ abbreviation biproduct_to_pushout_cofork : cokernel_cofork (biprod.lift f (-g)) := cokernel_cofork.of_π (biproduct_to_pushout f g) $ by rw [biprod.lift_desc, neg_comp, pushout.condition, add_right_neg] /-- The cofork induced by the canonical map `Y ⊞ Z ⟶ pushout f g` is in fact a colimit cokernel cofork. -/ def is_colimit_biproduct_to_pushout : is_colimit (biproduct_to_pushout_cofork f g) := cofork.is_colimit.mk _ (λ s, pushout.desc (biprod.inl ≫ cofork.π s) (biprod.inr ≫ cofork.π s) $ sub_eq_zero.1 $ by rw [←category.assoc, ←category.assoc, ←sub_comp, sub_eq_add_neg, ←neg_comp, biprod.inl_add_inr, cofork.condition s, has_zero_morphisms.zero_comp]) (λ s, by ext; simp) (λ s m h, by ext; simp [cofork.π_eq_app_one, ←h walking_parallel_pair.one] ) end biproduct_to_pushout_is_cokernel section epi_pullback variables [limits.has_pullbacks.{v} C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) local attribute [instance] has_preadditive_binary_biproducts_of_has_binary_products /-- In an abelian category, the pullback of an epimorphism is an epimorphism. Proof from [aluffi2016, IX.2.3], cf. [borceux-vol2, 1.7.6] -/ instance epi_pullback_of_epi_f [epi f] : epi (pullback.snd : pullback f g ⟶ Y) := -- It will suffice to consider some morphism e : Y ⟶ R such that -- pullback.snd ≫ e = 0 and show that e = 0. epi_of_cancel_zero _ $ λ R e h, begin -- Consider the morphism u := (0, e) : X ⊞ Y⟶ R. let u := biprod.desc (0 : X ⟶ R) e, -- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption. have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa, -- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a -- cokernel of pullback_to_biproduct f g have := epi_is_cokernel_of_kernel _ (pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g), -- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R. obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu, change Z ⟶ R at d, change biprod.desc f (-g) ≫ d = u at hd, -- But then f ≫ d = 0: have : f ≫ d = 0, calc f ≫ d = (biprod.inl ≫ biprod.desc f (-g)) ≫ d : by rw coprod.inl_desc ... = biprod.inl ≫ u : by rw [category.assoc, hd] ... = 0 : coprod.inl_desc _ _, -- But f is an epimorphism, so d = 0... have : d = 0 := (cancel_epi f).1 (by simpa), -- ...or, in other words, e = 0. calc e = biprod.inr ≫ u : by rw coprod.inr_desc ... = biprod.inr ≫ biprod.desc f (-g) ≫ d : by rw ←hd ... = biprod.inr ≫ biprod.desc f (-g) ≫ 0 : by rw this ... = (biprod.inr ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc ... = 0 : has_zero_morphisms.comp_zero _ _ end /-- In an abelian category, the pullback of an epimorphism is an epimorphism. -/ instance epi_pullback_of_epi_g [epi g] : epi (pullback.fst : pullback f g ⟶ X) := -- It will suffice to consider some morphism e : X ⟶ R such that -- pullback.fst ≫ e = 0 and show that e = 0. epi_of_cancel_zero _ $ λ R e h, begin -- Consider the morphism u := (e, 0) : X ⊞ Y ⟶ R. let u := biprod.desc e (0 : Y ⟶ R), -- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption. have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa, -- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a -- cokernel of pullback_to_biproduct f g have := epi_is_cokernel_of_kernel _ (pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g), -- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R. obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu, change Z ⟶ R at d, change biprod.desc f (-g) ≫ d = u at hd, -- But then (-g) ≫ d = 0: have : (-g) ≫ d = 0, calc (-g) ≫ d = (biprod.inr ≫ biprod.desc f (-g)) ≫ d : by rw coprod.inr_desc ... = biprod.inr ≫ u : by rw [category.assoc, hd] ... = 0 : coprod.inr_desc _ _, -- But g is an epimorphism, thus so is -g, so d = 0... have : d = 0 := (cancel_epi (-g)).1 (by simpa), -- ...or, in other words, e = 0. calc e = biprod.inl ≫ u : by rw coprod.inl_desc ... = biprod.inl ≫ biprod.desc f (-g) ≫ d : by rw ←hd ... = biprod.inl ≫ biprod.desc f (-g) ≫ 0 : by rw this ... = (biprod.inl ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc ... = 0 : has_zero_morphisms.comp_zero _ _ end end epi_pullback section mono_pushout variables [limits.has_pushouts.{v} C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) local attribute [instance] has_preadditive_binary_biproducts_of_has_binary_products instance mono_pushout_of_mono_f [mono f] : mono (pushout.inr : Z ⟶ pushout f g) := mono_of_cancel_zero _ $ λ R e h, begin let u := biprod.lift (0 : R ⟶ Y) e, have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa, have := mono_is_kernel_of_cokernel _ (biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g), obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu, change R ⟶ X at d, change d ≫ biprod.lift f (-g) = u at hd, have : d ≫ f = 0, calc d ≫ f = d ≫ biprod.lift f (-g) ≫ biprod.fst : by rw prod.lift_fst ... = u ≫ biprod.fst : by rw [←category.assoc, hd] ... = 0 : prod.lift_fst _ _, have : d = 0 := (cancel_mono f).1 (by simpa), calc e = u ≫ biprod.snd : by rw prod.lift_snd ... = (d ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw ←hd ... = (0 ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw this ... = 0 ≫ biprod.lift f (-g) ≫ biprod.snd : by rw category.assoc ... = 0 : has_zero_morphisms.zero_comp _ _ end instance mono_pushout_of_mono_g [mono g] : mono (pushout.inl : Y ⟶ pushout f g) := mono_of_cancel_zero _ $ λ R e h, begin let u := biprod.lift e (0 : R ⟶ Z), have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa, have := mono_is_kernel_of_cokernel _ (biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g), obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu, change R ⟶ X at d, change d ≫ biprod.lift f (-g) = u at hd, have : d ≫ (-g) = 0, calc d ≫ (-g) = d ≫ biprod.lift f (-g) ≫ biprod.snd : by rw prod.lift_snd ... = u ≫ biprod.snd : by rw [←category.assoc, hd] ... = 0 : prod.lift_snd _ _, have : d = 0 := (cancel_mono (-g)).1 (by simpa), calc e = u ≫ biprod.fst : by rw prod.lift_fst ... = (d ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw ←hd ... = (0 ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw this ... = 0 ≫ biprod.lift f (-g) ≫ biprod.fst : by rw category.assoc ... = 0 : has_zero_morphisms.zero_comp _ _ end end mono_pushout end category_theory.abelian
265616b8ba10aaeb4992e2442dbb0190bda717e9
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/KeyedDeclsAttribute.lean
31d7626e519a548c67fd836a68c4dd733782e24c
[ "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
7,738
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Attributes import Lean.Compiler.InitAttr import Lean.ToExpr import Lean.ScopedEnvExtension import Lean.Compiler.IR.CompilerM /-! A builder for attributes that are applied to declarations of a common type and group them by the given attribute argument (an arbitrary `Name`, currently). Also creates a second "builtin" attribute used for bootstrapping, which saves the applied declarations in an `IO.Ref` instead of an environment extension. Used to register elaborators, macros, tactics, and delaborators. -/ namespace Lean namespace KeyedDeclsAttribute -- could be a parameter as well, but right now it's all names abbrev Key := Name /-- `KeyedDeclsAttribute` definition. Important: `mkConst valueTypeName` and `γ` must be definitionally equal. -/ structure Def (γ : Type) where builtinName : Name := Name.anonymous -- Builtin attribute name, if any (e.g., `builtinTermElab) name : Name -- Attribute name (e.g., `termElab) descr : String -- Attribute description valueTypeName : Name -- Convert `Syntax` into a `Key`, the default implementation expects an identifier. evalKey : Bool → Syntax → AttrM Key := fun builtin stx => Attribute.Builtin.getId stx deriving Inhabited structure OLeanEntry where key : Key declName : Name -- Name of a declaration stored in the environment which has type `mkConst Def.valueTypeName`. deriving Inhabited structure AttributeEntry (γ : Type) extends OLeanEntry where /- Recall that we cannot store `γ` into .olean files because it is a closure. Given `OLeanEntry.declName`, we convert it into a `γ` by using the unsafe function `evalConstCheck`. -/ value : γ abbrev Table (γ : Type) := SMap Key (List (AttributeEntry γ)) structure ExtensionState (γ : Type) where newEntries : List OLeanEntry := [] table : Table γ := {} declNames : Std.PHashSet Name := {} erased : Std.PHashSet Name := {} deriving Inhabited abbrev Extension (γ : Type) := ScopedEnvExtension OLeanEntry (AttributeEntry γ) (ExtensionState γ) end KeyedDeclsAttribute structure KeyedDeclsAttribute (γ : Type) where defn : KeyedDeclsAttribute.Def γ -- imported/builtin instances tableRef : IO.Ref (KeyedDeclsAttribute.Table γ) -- instances from current module ext : KeyedDeclsAttribute.Extension γ deriving Inhabited namespace KeyedDeclsAttribute private def Table.insert (table : Table γ) (v : AttributeEntry γ) : Table γ := match table.find? v.key with | some vs => SMap.insert table v.key (v::vs) | none => SMap.insert table v.key [v] def ExtensionState.insert (s : ExtensionState γ) (v : AttributeEntry γ) : ExtensionState γ := { table := s.table.insert v newEntries := v.toOLeanEntry :: s.newEntries declNames := s.declNames.insert v.declName erased := s.erased.erase v.declName } def addBuiltin (attr : KeyedDeclsAttribute γ) (key : Key) (declName : Name) (value : γ) : IO Unit := attr.tableRef.modify fun m => m.insert { key, declName, value } def mkStateOfTable (table : Table γ) : ExtensionState γ := { table declNames := table.fold (init := {}) fun s _ es => es.foldl (init := s) fun s e => s.insert e.declName } def ExtensionState.erase (s : ExtensionState γ) (attrName : Name) (declName : Name) : CoreM (ExtensionState γ) := do unless s.declNames.contains declName do throwError "'{declName}' does not have [{attrName}] attribute" return { s with erased := s.erased.insert declName, declNames := s.declNames.erase declName } /-- def _regBuiltin$(declName) : IO Unit := @addBuiltin $(mkConst valueTypeName) $(mkConst attrDeclName) $(key) $(declName) $(mkConst declName) -/ def declareBuiltin {γ} (df : Def γ) (attrDeclName : Name) (env : Environment) (key : Key) (declName : Name) : IO Environment := let name := `_regBuiltin ++ declName let type := mkApp (mkConst `IO) (mkConst `Unit) let val := mkAppN (mkConst `Lean.KeyedDeclsAttribute.addBuiltin) #[mkConst df.valueTypeName, mkConst attrDeclName, toExpr key, toExpr declName, mkConst declName] let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error e => do let msg ← (e.toMessageData {}).toString throw (IO.userError s!"failed to emit registration code for builtin '{declName}': {msg}") | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) protected unsafe def init {γ} (df : Def γ) (attrDeclName : Name) : IO (KeyedDeclsAttribute γ) := do let tableRef ← IO.mkRef ({} : Table γ) let ext : Extension γ ← registerScopedEnvExtension { name := df.name mkInitial := return mkStateOfTable (← tableRef.get) ofOLeanEntry := fun s entry => do let ctx ← read match ctx.env.evalConstCheck γ ctx.opts df.valueTypeName entry.declName with | Except.ok f => return { toOLeanEntry := entry, value := f } | Except.error ex => throw (IO.userError ex) addEntry := fun s e => s.insert e toOLeanEntry := (·.toOLeanEntry) } unless df.builtinName.isAnonymous do registerBuiltinAttribute { name := df.builtinName, descr := "(builtin) " ++ df.descr, add := fun declName stx kind => do unless kind == AttributeKind.global do throwError "invalid attribute '{df.builtinName}', must be global" let key ← df.evalKey true stx let decl ← getConstInfo declName match decl.type with | Expr.const c _ _ => if c != df.valueTypeName then throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected" else let env ← getEnv let env ← declareBuiltin df attrDeclName env key declName setEnv env | _ => throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected", applicationTime := AttributeApplicationTime.afterCompilation } registerBuiltinAttribute { name := df.name descr := df.descr erase := fun declName => do let s ← ext.getState (← getEnv) let s ← s.erase df.name declName modifyEnv fun env => ext.modifyState env fun _ => s add := fun declName stx attrKind => do let key ← df.evalKey false stx match IR.getSorryDep (← getEnv) declName with | none => let val ← evalConstCheck γ df.valueTypeName declName ext.add { key := key, declName := declName, value := val } attrKind | _ => -- If the declaration contains `sorry`, we skip `evalConstCheck` to avoid unnecessary bizarre error message pure () applicationTime := AttributeApplicationTime.afterCompilation } pure { defn := df, tableRef := tableRef, ext := ext } /-- Retrieve entries tagged with `[attr key]` or `[builtinAttr key]`. -/ def getEntries {γ} (attr : KeyedDeclsAttribute γ) (env : Environment) (key : Name) : List (AttributeEntry γ) := let s := attr.ext.getState env let attrs := s.table.findD key [] if s.erased.isEmpty then attrs else attrs.filter fun attr => !s.erased.contains attr.declName /-- Retrieve values tagged with `[attr key]` or `[builtinAttr key]`. -/ def getValues {γ} (attr : KeyedDeclsAttribute γ) (env : Environment) (key : Name) : List γ := (getEntries attr env key).map AttributeEntry.value end KeyedDeclsAttribute end Lean
fd397ba7554ac2cf43dfeaba46c091472515e5dd
9028d228ac200bbefe3a711342514dd4e4458bff
/src/linear_algebra/char_poly/coeff.lean
db6b7ac934c33b4c5aeaec0b99436d8b0229213d
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,961
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark. -/ import data.matrix.char_p import linear_algebra.char_poly import linear_algebra.matrix import ring_theory.polynomial.basic import algebra.polynomial.big_operators import group_theory.perm.cycles import field_theory.finite.basic /-! # Characteristic polynomials We give methods for computing coefficients of the characteristic polynomial. ## Main definitions - `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial over a nonzero ring is the dimension of the matrix - `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the characteristic polynomial, up to sign. - `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the characteristic polynomial, where d is the dimension of the matrix. For a nonzero ring, this is the second-highest coefficient. -/ noncomputable theory universes u v w z open polynomial matrix open_locale big_operators variables {R : Type u} [comm_ring R] variables {n G : Type v} [decidable_eq n] [fintype n] variables {α β : Type v} [decidable_eq α] open finset open polynomial variable {M : matrix n n R} lemma char_matrix_apply_nat_degree [nontrivial R] (i j : n) : (char_matrix M i j).nat_degree = ite (i = j) 1 0 := by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], } lemma char_matrix_apply_nat_degree_le (i j : n) : (char_matrix M i j).nat_degree ≤ ite (i = j) 1 0 := by split_ifs; simp [h, nat_degree_X_sub_C_le] variable (M) lemma char_poly_sub_diagonal_degree_lt : (char_poly M - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) := begin rw [char_poly, det, ← insert_erase (mem_univ (equiv.refl n)), sum_insert (not_mem_erase (equiv.refl n) univ), add_comm], simp only [char_matrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one, units.coe_one, add_sub_cancel, equiv.coe_refl], rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)), intros c hc, rw [← C_eq_int_cast, C_mul'], apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c), rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe, apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)), apply le_trans (polynomial.nat_degree_prod_le univ (λ i : n, (char_matrix M (c i) i))) _, rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum, intros, apply char_matrix_apply_nat_degree_le, end lemma char_poly_coeff_eq_prod_coeff_of_le {k : ℕ} (h : fintype.card n - 1 ≤ k) : (char_poly M).coeff k = (∏ i : n, (X - C (M i i))).coeff k := begin apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt, apply lt_of_lt_of_le (char_poly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h, end lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 := by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext, tauto } theorem char_poly_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).degree = fintype.card n := begin by_cases fintype.card n = 0, rw h, unfold char_poly, rw det_of_card_zero, simpa, rw ← sub_add_cancel (char_poly M) (∏ (i : n), (X - C (M i i))), have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n, { rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h, rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp, simp_rw (monic_X_sub_C _).leading_coeff, simp, }, rw degree_add_eq_of_degree_lt, exact h1, rw h1, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem char_poly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).nat_degree = fintype.card n := nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M) lemma char_poly_monic (M : matrix n n R) : monic (char_poly M) := begin nontriviality, by_cases fintype.card n = 0, rw [char_poly, det_of_card_zero h], apply monic_one, have mon : (∏ (i : n), (X - C (M i i))).monic, { apply monic_prod_of_monic univ (λ i : n, (X - C (M i i))), simp [monic_X_sub_C], }, rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) (char_poly M) at mon, rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon, rw char_poly_degree_eq_dim, rw ← neg_sub, rw degree_neg, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem trace_eq_neg_char_poly_coeff [nonempty n] (M : matrix n n R) : (matrix.trace n R R) M = -(char_poly M).coeff (fintype.card n - 1) := begin nontriviality, rw char_poly_coeff_eq_prod_coeff_of_le, swap, refl, rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (λ i : n, M i i)], simp, rw [← fintype.card, fintype.card_pos_iff], apply_instance, end -- I feel like this should use polynomial.alg_hom_eval₂_algebra_map lemma mat_poly_equiv_eval (M : matrix n n (polynomial R)) (r : R) (i j : n) : (mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r := begin unfold polynomial.eval, unfold eval₂, transitivity finsupp.sum (mat_poly_equiv M) (λ (e : ℕ) (a : matrix n n R), (a * (scalar n) r ^ e) i j), { unfold finsupp.sum, rw sum_apply, rw sum_apply, dsimp, refl, }, { simp_rw ← (scalar n).map_pow, simp_rw ← (matrix.scalar.commute _ _).eq, simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply, smul_apply, mul_eq_mul, algebra.smul_mul_assoc], have h : ∀ x : ℕ, (λ (e : ℕ) (a : R), r ^ e * a) x 0 = 0 := by simp, symmetry, rw ← finsupp.sum_map_range_index h, swap, refl, refine congr (congr rfl _) (by {ext, rw mul_comm}), ext, rw finsupp.map_range_apply, simp [apply_eq_coeff], } end lemma eval_det (M : matrix n n (polynomial R)) (r : R) : polynomial.eval r M.det = (polynomial.eval (matrix.scalar n r) (mat_poly_equiv M)).det := begin rw [polynomial.eval, ← coe_eval₂_ring_hom, ring_hom.map_det], apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _, end theorem det_eq_sign_char_poly_coeff (M : matrix n n R) : M.det = (-1)^(fintype.card n) * (char_poly M).coeff 0:= begin rw [coeff_zero_eq_eval_zero, char_poly, eval_det, mat_poly_equiv_char_matrix, ← det_smul], simp end variables {p : ℕ} [fact p.prime] @[simp] lemma finite_field.char_poly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : char_poly (M ^ (fintype.card K)) = char_poly M := begin by_cases hn : nonempty n, { letI := hn, cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩, letI : fact p.prime := hp, dsimp at hk, rw hk at *, apply (frobenius_inj (polynomial K) p).iterate k, repeat { rw iterate_frobenius, rw ← hk }, rw ← finite_field.expand_card, unfold char_poly, rw [alg_hom.map_det, ← is_monoid_hom.map_pow], apply congr_arg det, apply mat_poly_equiv.injective, swap, { apply_instance }, rw [← mat_poly_equiv.coe_alg_hom, alg_hom.map_pow, mat_poly_equiv.coe_alg_hom, mat_poly_equiv_char_matrix, hk, sub_pow_char_pow_of_commute, ← C_pow], swap, { apply polynomial.commute_X }, -- the following is a nasty case bash that should be abstracted as a lemma -- (and maybe it can be proven more... algebraically?) ext, rw [coeff_sub, coeff_C], by_cases hij : i = j; simp [char_matrix, hij, coeff_X_pow]; simp only [coeff_C]; split_ifs; simp *, }, { congr, apply @subsingleton.elim _ (subsingleton_of_empty_left hn) _ _, }, end @[simp] lemma zmod.char_poly_pow_card (M : matrix n n (zmod p)) : char_poly (M ^ p) = char_poly M := by { have h := finite_field.char_poly_pow_card M, rwa zmod.card at h, } lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] [nonempty n] (M : matrix n n K) : trace n K K (M ^ (fintype.card K)) = (trace n K K M) ^ (fintype.card K) := by rw [trace_eq_neg_char_poly_coeff, trace_eq_neg_char_poly_coeff, finite_field.char_poly_pow_card, finite_field.pow_card] lemma zmod.trace_pow_card {p:ℕ} [fact p.prime] [nonempty n] (M : matrix n n (zmod p)) : trace n (zmod p) (zmod p) (M ^ p) = (trace n (zmod p) (zmod p) M)^p := by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, } namespace matrix theorem is_integral : is_integral R M := ⟨char_poly M, ⟨char_poly_monic M, aeval_self_char_poly M⟩⟩ theorem min_poly_dvd_char_poly {K : Type*} [field K] (M : matrix n n K) : (minimal_polynomial M.is_integral) ∣ char_poly M := minimal_polynomial.dvd M.is_integral (aeval_self_char_poly M) end matrix
a3a7145bae7eeec28ee1f21b010d57bb53f28b9d
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/del/semantics/completenessDEL.lean
16479fb619fa6fb6056e87121c3fd1088f853217
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
6,946
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley Following the textbook "Dynamic Epistemic Logic" by Hans van Ditmarsch, Wiebe van der Hoek, and Barteld Kooi -/ import del.semantics.consistencyDEL del.syntax.soundnessDEL import data.list.basic local attribute [instance] classical.prop_decidable variables {agents : Type} open prfS5 open S5lemma ---------------------- Canonical Model Construction ---------------------- namespace canonical def canonical [hax : sem_cons (∅ : ctx agents) equiv_class] : frame agents := { states := {xΓ : ctx agents // max_ax_consist xΓ}, h := begin have h1 := max_ax_exists hax, choose Γ h1 using h1, exact ⟨⟨Γ, h1⟩⟩ end, rel := λ a, λ xΓ yΔ, ∀ φ : form agents, K a φ ∈ xΓ.val → φ ∈ yΔ.val } def val_canonical [hax : sem_cons (∅ : ctx agents) equiv_class] : nat → canonical.states → Prop := λ n, λ xΓ : canonical.states, (form.var n) ∈ (xΓ.val : ctx agents) lemma existence (hax : sem_cons (∅ : ctx agents) equiv_class) (xΓ : canonical.states) : ∀ a, ∀ φ : form agents, (¬ K a (¬φ)) ∈ xΓ.val ↔ ∃ yΔ : canonical.states, φ ∈ yΔ.val ∧ canonical.rel a xΓ yΔ := begin intros a φ, split, intro h1, let Γbox : ctx agents := {ψ : form agents | K a ψ ∈ xΓ.val}, have h1 : ax_consist (Γbox ∪ {φ}), {by_contradiction h2, simp at h2, have h3 := five Γbox φ h2, cases h3 with L h3, cases h3 with h3 h4, have h5 := cut fin_conj_boxn (mp kdist (nec h4)), have h6 := exercise1, have h7 : ∀ ψ ∈ (list.map (form.box a) L), ψ ∈ xΓ.1, intros ψ h8, simp at *, cases h8 with a h8, cases h8 with h8l h8r, subst h8r, exact h3 a h8l, specialize h6 xΓ.2 h7 h5, have h8 := (six xΓ.1 (max_imp_ax xΓ.2)).mp xΓ.2 (K a (¬φ)), cases h8 with h8l h8r, simp at *, exact absurd h1 (h8r h6), }, have h2 := lindenbaum (Γbox ∪ {φ}) h1, cases h2 with Δ h2, cases h2 with h2 h3, let xΔ : canonical.states := ⟨Δ, h2⟩, existsi (xΔ : canonical.states), have h5 := set.union_subset_iff.mp h3, cases h5, split, simp at h5_right, exact h5_right, have h3 : ∀ φ : form agents, K a φ ∈ xΓ.val → φ ∈ xΔ.val, intros ψ h4, apply h5_left, exact h4, exact h3, simp at *, intros yΔ h1 h2, by_contradiction h4, have h5 := (max_notiff xΓ.1 xΓ.2 (C a φ)).mp h4, have h6 := (max_dn xΓ.1 xΓ.2 (K a ¬φ)).mpr h5, exact absurd h1 ((max_notiff yΔ.1 yΔ.2 φ).mpr ((h2 (¬φ)) h6)) end lemma truth (hax : sem_cons (∅ : ctx agents) equiv_class) (xΓ : canonical.states) : ∀ φ : form agents, forces canonical val_canonical xΓ φ ↔ (φ ∈ xΓ.val) := begin intro φ, induction φ with n φ ψ ih_φ ih_ψ φ ψ ih_φ ih_ψ φ ih_φ generalizing xΓ, split, intro h1, exact false.elim h1, intro h1, rw forces, have h2 := xΓ.2, cases h2, specialize h2_left [⊥], simp at *, exact absurd not_contra (h2_left h1), repeat {rw forces, rw val_canonical}, split, intro h1, cases h1 with h1 h2, exact max_conj_1 xΓ.2 (and.intro ((ih_φ xΓ).mp h1) ((ih_ψ xΓ).mp h2)), intro h1, split, apply (ih_φ xΓ).mpr, exact max_conj_2 xΓ.2 h1, apply (ih_ψ xΓ).mpr, exact max_conj_3 xΓ.2 h1, split, intro h1, apply max_imp_1 xΓ.2, intro h2, exact (ih_ψ xΓ).mp (h1 ((ih_φ xΓ).mpr h2)), intros h1 h2, apply (ih_ψ xΓ).mpr, exact max_imp_2 xΓ.2 h1 ((ih_φ xΓ).mp h2), rename φ a, rename ih_φ φ, split, intros h1, by_contradiction h2, have h4 := (existence hax xΓ a (¬φ)).mp, have h5 := max_boxdn xΓ.1 xΓ.2 φ a ((max_notiff xΓ.1 xΓ.2 (K a φ)).mp h2), cases h4 h5 with xΔ h4, cases h4 with h4 h6, have h7 := max_notiff xΔ.1 xΔ.2 φ, cases h7 with h7l h7r, exact absurd ((φ_ih xΔ).mp (h1 xΔ h6)) (h7r h4), intros h1 xΔ h2, apply (φ_ih xΔ).mpr, exact (h2 φ h1), end lemma comphelper (φ : form agents) (hax : sem_cons (∅ : ctx agents) equiv_class) : ¬ prfS5 ∅ φ → ax_consist ({¬φ} : ctx agents) := begin intros h1 L h2, rw fin_ax_consist, induction L, by_contradiction h3, exact absurd (mp dne h3) (nprfalse hax), have h4 : (∀ ψ ∈ L_hd::L_tl, ψ = ¬φ) → prfS5 ∅ (¬fin_conj (L_hd::L_tl)) → prfS5 ∅ φ, from fin_conj_repeat hax, simp at *, cases h2 with h2 h3, intro h6, apply h1, apply h4 h2, exact h3, exact h6 end theorem forcesAX (hax : sem_cons (∅ : ctx agents) equiv_class) : forces_ctx canonical val_canonical (∅ : ctx agents) := begin intros φ xΓ h1, have h2 := mp prfS5.pl1 (ax h1), have h3 : ∀ ψ ∈ list.nil, ψ ∈ xΓ.val, {intros ψ h3, have h5 := list.ne_nil_of_length_pos (list.length_pos_of_mem h3), simp at *, exact false.elim h5}, have h4 := exercise1 xΓ.2 h3 h2, exact (truth hax xΓ φ).mpr h4 end lemma euclid_dual {a : agents} {φ : form agents} : prfS5 ∅ ((C a (¬φ) ⊃ K a (C a (¬φ))) ⊃ (C a (K a φ) ⊃ K a φ)) := begin have h1 := contrapos.mpr negintro, have h2 := cut h1 (mp pl6 dual_equiv1), have h3 : prfS5 ∅ ((¬K a (C a ¬φ)) ↔ (¬¬C a (¬(C a ¬φ)))), from (mp (mp pl4 (contrapos.mpr (mp pl6 dual_equiv1))) (contrapos.mpr (mp pl5 dual_equiv1))), have h4 := cut dni (cut (mp pl6 h3) h2), have h5 := (contrapos.mpr (mp kdist (nec (contrapos.mpr (mp pl5 dual_equiv1))))), exact (mp pl1 (cut h5 h4)) end lemma S5_equiv (hax : sem_cons (∅ : ctx agents) equiv_class) : canonical ∈ (equiv_class : set (frame agents)) := begin rw equiv_ref_euclid, split, intros a x φ h1, have h2 : ∀ a, (∀ ψ ∈ [(K a φ)], ψ ∈ x.1) → prfS5 ∅ (fin_conj [(K a φ)] ⊃ φ) → φ ∈ x.1, from λ a, exercise1 x.2, have h3 : prfS5 ∅ (fin_conj [(K a φ)] ⊃ φ), {exact cut (mp pl5 phi_and_true) prfS5.truth}, specialize h2 a, simp at *, exact h2 h1 h3, intros a x y z h1 h2 φ h3, apply h2 φ, have h4 := mp euclid_dual negintro, have h5 : ∀ a, (∀ ψ ∈ [(C a (K a φ))], ψ ∈ x.1) → prfS5 ∅ (fin_conj [(C a (K a φ))] ⊃ K a φ) → K a φ ∈ x.1, from λ a, exercise1 x.2, simp at *, apply h5, by_contradiction h6, have h7 := max_notiff x.1 x.2 (¬K a (¬K a φ)), have h8 := max_dn x.1 x.2 (K a (¬K a φ)), have h9 := (max_notiff y.1 y.2 (K a φ)).mpr (h1 (¬K a φ) (h8.mpr (h7.mp h6))), exact absurd h3 h9, exact (cut (mp pl5 phi_and_true) h4) end theorem completeness (hax : sem_cons (∅ : ctx agents) equiv_class) (φ : form agents) : global_sem_csq ∅ equiv_class φ → prfS5 ∅ φ := begin rw ←not_imp_not, intro h1, have h2 := comphelper φ hax h1, have h3 := lindenbaum {¬φ} h2, simp at *, cases h3 with Γ' h3, cases h3 with h3 h4, rw global_sem_csq, push_neg, let f := canonical, use f, let v := val_canonical, split, exact S5_equiv hax, use v, let xΓ' : f.states := ⟨Γ', h3⟩, split, exact forcesAX hax, use xΓ', have h5 : forces f v xΓ' (¬φ) ↔ ((¬φ) ∈ xΓ'.val), from truth hax xΓ' ¬φ, cases h5 with h5 h6, have h7 : ¬forces f v xΓ' φ ↔ forces f v xΓ' ¬φ, from not_forces_imp f v xΓ' φ, cases h7 with h7 h8, apply h8, apply h6, exact h4 end end canonical
852abf4d134fd81820974de5366505f6d262a50a
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/pequiv.lean
e2dda7e503ce30397b26a9768995db181c19db5e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
11,215
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.set.lattice universes u v w x /-- A `pequiv` is a partial equivalence, a representation of a bijection between a subset of `α` and a subset of `β` -/ structure pequiv (α : Type u) (β : Type v) := (to_fun : α → option β) (inv_fun : β → option α) (inv : ∀ (a : α) (b : β), a ∈ inv_fun b ↔ b ∈ to_fun a) infixr ` ≃. `:25 := pequiv namespace pequiv variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open function option instance : has_coe_to_fun (α ≃. β) := ⟨_, to_fun⟩ @[simp] lemma coe_mk_apply (f₁ : α → option β) (f₂ : β → option α) (h) (x : α) : (pequiv.mk f₁ f₂ h : α → option β) x = f₁ x := rfl @[ext] lemma ext : ∀ {f g : α ≃. β} (h : ∀ x, f x = g x), f = g | ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ h := have h : f₁ = g₁, from funext h, have ∀ b, f₂ b = g₂ b, begin subst h, assume b, have hf := λ a, hf a b, have hg := λ a, hg a b, cases h : g₂ b with a, { simp only [h, option.not_mem_none, false_iff] at hg, simp only [hg, iff_false] at hf, rwa [option.eq_none_iff_forall_not_mem] }, { rw [← option.mem_def, hf, ← hg, h, option.mem_def] } end, by simp [*, funext_iff] lemma ext_iff {f g : α ≃. β} : f = g ↔ ∀ x, f x = g x := ⟨congr_fun ∘ congr_arg _, ext⟩ @[refl] protected def refl (α : Type*) : α ≃. α := { to_fun := some, inv_fun := some, inv := λ _ _, eq_comm } @[symm] protected def symm (f : α ≃. β) : β ≃. α := { to_fun := f.2, inv_fun := f.1, inv := λ _ _, (f.inv _ _).symm } lemma mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a := f.3 lemma eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b := f.3 @[trans] protected def trans (f : α ≃. β) (g : β ≃. γ) : pequiv α γ := { to_fun := λ a, (f a).bind g, inv_fun := λ a, (g.symm a).bind f.symm, inv := λ a b, by simp [*, and.comm, eq_some_iff f, eq_some_iff g] at * } @[simp] lemma refl_apply (a : α) : pequiv.refl α a = some a := rfl @[simp] lemma symm_refl : (pequiv.refl α).symm = pequiv.refl α := rfl @[simp] lemma symm_symm (f : α ≃. β) : f.symm.symm = f := by cases f; refl lemma symm_injective : function.injective (@pequiv.symm α β) := left_inverse.injective symm_symm lemma trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) : (f.trans g).trans h = f.trans (g.trans h) := ext (λ _, option.bind_assoc _ _ _) lemma mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b := option.bind_eq_some' lemma trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c := option.bind_eq_some' lemma trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) : f.trans g a = none ↔ (∀ b c, b ∉ f a ∨ c ∉ g b) := begin simp only [eq_none_iff_forall_not_mem, mem_trans, imp_iff_not_or.symm], push_neg, tauto end @[simp] lemma refl_trans (f : α ≃. β) : (pequiv.refl α).trans f = f := by ext; dsimp [pequiv.trans]; refl @[simp] lemma trans_refl (f : α ≃. β) : f.trans (pequiv.refl β) = f := by ext; dsimp [pequiv.trans]; simp protected lemma inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) : a₁ = a₂ := by rw ← mem_iff_mem at *; cases h : f.symm b; simp * at * lemma injective_of_forall_ne_is_some (f : α ≃. β) (a₂ : α) (h : ∀ (a₁ : α), a₁ ≠ a₂ → is_some (f a₁)) : injective f := has_left_inverse.injective ⟨λ b, option.rec_on b a₂ (λ b', option.rec_on (f.symm b') a₂ id), λ x, begin classical, cases hfx : f x, { have : x = a₂, from not_imp_comm.1 (h x) (hfx.symm ▸ by simp), simp [this] }, { simp only [hfx], rw [(eq_some_iff f).2 hfx], refl } end⟩ lemma injective_of_forall_is_some {f : α ≃. β} (h : ∀ (a : α), is_some (f a)) : injective f := (classical.em (nonempty α)).elim (λ hn, injective_of_forall_ne_is_some f (classical.choice hn) (λ a _, h a)) (λ hn x, (hn ⟨x⟩).elim) section of_set variables (s : set α) [decidable_pred s] def of_set (s : set α) [decidable_pred s] : α ≃. α := { to_fun := λ a, if a ∈ s then some a else none, inv_fun := λ a, if a ∈ s then some a else none, inv := λ a b, by split_ifs; finish [eq_comm] } lemma mem_of_set_self_iff {s : set α} [decidable_pred s] {a : α} : a ∈ of_set s a ↔ a ∈ s := by dsimp [of_set]; split_ifs; simp * lemma mem_of_set_iff {s : set α} [decidable_pred s] {a b : α} : a ∈ of_set s b ↔ a = b ∧ a ∈ s := by dsimp [of_set]; split_ifs; split; finish @[simp] lemma of_set_eq_some_iff {s : set α} {h : decidable_pred s} {a b : α} : of_set s b = some a ↔ a = b ∧ a ∈ s := mem_of_set_iff @[simp] lemma of_set_eq_some_self_iff {s : set α} {h : decidable_pred s} {a : α} : of_set s a = some a ↔ a ∈ s := mem_of_set_self_iff @[simp] lemma of_set_symm : (of_set s).symm = of_set s := rfl @[simp] lemma of_set_univ : of_set set.univ = pequiv.refl α := by ext; dsimp [of_set]; simp [eq_comm] @[simp] lemma of_set_eq_refl {s : set α} [decidable_pred s] : of_set s = pequiv.refl α ↔ s = set.univ := ⟨λ h, begin rw [set.eq_univ_iff_forall], intro, rw [← mem_of_set_self_iff, h], exact rfl end, λ h, by simp only [of_set_univ.symm, h]; congr⟩ end of_set lemma symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm := rfl lemma trans_symm (f : α ≃. β) : f.trans f.symm = of_set {a | (f a).is_some} := begin ext, dsimp [pequiv.trans], simp only [eq_some_iff f, option.is_some_iff_exists, option.mem_def, bind_eq_some', of_set_eq_some_iff], split, { rintros ⟨b, hb₁, hb₂⟩, exact ⟨pequiv.inj _ hb₂ hb₁, b, hb₂⟩ }, { simp {contextual := tt} } end lemma symm_trans (f : α ≃. β) : f.symm.trans f = of_set {b | (f.symm b).is_some} := symm_injective $ by simp [symm_trans_rev, trans_symm, -symm_symm] lemma trans_symm_eq_iff_forall_is_some {f : α ≃. β} : f.trans f.symm = pequiv.refl α ↔ ∀ a, is_some (f a) := by rw [trans_symm, of_set_eq_refl, set.eq_univ_iff_forall]; refl instance : has_bot (α ≃. β) := ⟨{ to_fun := λ _, none, inv_fun := λ _, none, inv := by simp }⟩ @[simp] lemma bot_apply (a : α) : (⊥ : α ≃. β) a = none := rfl @[simp] lemma symm_bot : (⊥ : α ≃. β).symm = ⊥ := rfl @[simp] lemma trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ := by ext; dsimp [pequiv.trans]; simp @[simp] lemma bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ := by ext; dsimp [pequiv.trans]; simp lemma is_some_symm_get (f : α ≃. β) {a : α} (h : is_some (f a)) : is_some (f.symm (option.get h)) := is_some_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩ section single variables [decidable_eq α] [decidable_eq β] [decidable_eq γ] def single (a : α) (b : β) : α ≃. β := { to_fun := λ x, if x = a then some b else none, inv_fun := λ x, if x = b then some a else none, inv := λ _ _, by simp; split_ifs; cc } lemma mem_single (a : α) (b : β) : b ∈ single a b a := if_pos rfl lemma mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ := by dsimp [single]; split_ifs; simp [*, eq_comm] @[simp] lemma symm_single (a : α) (b : β) : (single a b).symm = single b a := rfl @[simp] lemma single_apply (a : α) (b : β) : single a b a = some b := if_pos rfl lemma single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none := if_neg h.symm lemma single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) : (single a b).trans f = single a c := begin ext, dsimp [single, pequiv.trans], split_ifs; simp * at * end lemma trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) : f.trans (single b c) = single a c := symm_injective $ single_trans_of_mem _ ((mem_iff_mem f).2 h) @[simp] lemma single_trans_single (a : α) (b : β) (c : γ) : (single a b).trans (single b c) = single a c := single_trans_of_mem _ (mem_single _ _) @[simp] lemma single_subsingleton_eq_refl [subsingleton α] (a b : α) : single a b = pequiv.refl α := begin ext i j, dsimp [single], rw [if_pos (subsingleton.elim i a), subsingleton.elim i j, subsingleton.elim b j] end lemma trans_single_of_eq_none {b : β} (c : γ) {f : δ ≃. β} (h : f.symm b = none) : f.trans (single b c) = ⊥ := begin ext, simp only [eq_none_iff_forall_not_mem, option.mem_def, f.eq_some_iff] at h, dsimp [pequiv.trans, single], simp, intros, split_ifs; simp * at * end lemma single_trans_of_eq_none (a : α) {b : β} {f : β ≃. δ} (h : f b = none) : (single a b).trans f = ⊥ := symm_injective $ trans_single_of_eq_none _ h lemma single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) : (single a b₁).trans (single b₂ c) = ⊥ := single_trans_of_eq_none _ (single_apply_of_ne h.symm _) end single section order instance : partial_order (α ≃. β) := { le := λ f g, ∀ (a : α) (b : β), b ∈ f a → b ∈ g a, le_refl := λ _ _ _, id, le_trans := λ f g h fg gh a b, (gh a b) ∘ (fg a b), le_antisymm := λ f g fg gf, ext begin assume a, cases h : g a with b, { exact eq_none_iff_forall_not_mem.2 (λ b hb, option.not_mem_none b $ h ▸ fg a b hb) }, { exact gf _ _ h } end } lemma le_def {f g : α ≃. β} : f ≤ g ↔ (∀ (a : α) (b : β), b ∈ f a → b ∈ g a) := iff.rfl instance : order_bot (α ≃. β) := { bot_le := λ _ _ _ h, (not_mem_none _ h).elim, ..pequiv.partial_order, ..pequiv.has_bot } instance [decidable_eq α] [decidable_eq β] : semilattice_inf_bot (α ≃. β) := { inf := λ f g, { to_fun := λ a, if f a = g a then f a else none, inv_fun := λ b, if f.symm b = g.symm b then f.symm b else none, inv := λ a b, begin have := @mem_iff_mem _ _ f a b, have := @mem_iff_mem _ _ g a b, split_ifs; finish end }, inf_le_left := λ _ _ _ _, by simp; split_ifs; cc, inf_le_right := λ _ _ _ _, by simp; split_ifs; cc, le_inf := λ f g h fg gh a b, begin have := fg a b, have := gh a b, simp [le_def], split_ifs; finish end, ..pequiv.order_bot } end order end pequiv namespace equiv variables {α : Type*} {β : Type*} {γ : Type*} def to_pequiv (f : α ≃ β) : α ≃. β := { to_fun := some ∘ f, inv_fun := some ∘ f.symm, inv := by simp [equiv.eq_symm_apply, eq_comm] } @[simp] lemma to_pequiv_refl : (equiv.refl α).to_pequiv = pequiv.refl α := rfl lemma to_pequiv_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g).to_pequiv = f.to_pequiv.trans g.to_pequiv := rfl lemma to_pequiv_symm (f : α ≃ β) : f.symm.to_pequiv = f.to_pequiv.symm := rfl lemma to_pequiv_apply (f : α ≃ β) (x : α) : f.to_pequiv x = some (f x) := rfl end equiv
c67d72faac2fa6ed727585600dbf27cc2f31e1ff
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/subgroup.lean
71b3eb5491fcdf1d24e0c5d478d82f77cb027d22
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,951
lean
import group_theory.subgroup import algebra.pi_instances section variables {α : Type*} [group α] {β : Type*} [group β] @[to_additive is_add_subgroup.prod] instance is_subgroup.prod (s : set α) (t : set β) [is_subgroup s] [is_subgroup t] : is_subgroup (s.prod t) := { one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem, mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto, inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto } end namespace add_group -- TODO(jmc): generalise using to_additive variables {α : Type*} {β : Type*} [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] lemma image_closure (s : set α) : f '' closure s = closure (f '' s) := le_antisymm (by rintros _ ⟨x, hx, rfl⟩; exact in_closure.rec_on hx (λ a ha, mem_closure ⟨a, ha, rfl⟩) (by {rw [is_add_monoid_hom.map_zero f]; apply is_add_submonoid.zero_mem, }) (by {intros, rw [is_add_group_hom.map_neg f]; apply is_add_subgroup.neg_mem, assumption }) (by {intros, rw [is_add_monoid_hom.map_add f]; apply is_add_submonoid.add_mem, assumption' })) (closure_subset $ set.image_subset _ subset_closure) end add_group namespace add_monoid -- TODO(jmc): generalise using to_additive variables {α : Type*} [add_comm_monoid α] {β : Type*} local attribute [instance] classical.prop_decidable lemma sum_mem_closure (s : set α) (ι : finset β) (f : β → α) (h : ∀ i ∈ ι, f i ∈ s) : ι.sum f ∈ add_monoid.closure s := begin revert h, apply finset.induction_on ι, { intros, rw finset.sum_empty, apply is_add_submonoid.zero_mem }, { intros i ι' hi IH h, rw finset.sum_insert hi, apply is_add_submonoid.add_mem, { apply add_monoid.subset_closure, apply h, apply finset.mem_insert_self }, { apply IH, intros i' hi', apply h, apply finset.mem_insert_of_mem hi' } } end end add_monoid
909a6a110e41cf91da6c13661c95c90dfca8a8e9
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/tower_law.lean
753843fc9aae20fb411b03be786888793ee263dd
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
1,591
lean
import ring_theory.algebra_operations linear_algebra.dimension ring_theory.noetherian universes u v w section variables {α : Type*} {β : Type*} [comm_ring α] [comm_ring β] [algebra α β] variables {γ : Type w} [add_comm_group γ] [module α γ] [module β γ] open submodule #print nat.to_digits lemma span_subset_span {s : set γ} : (span α s : set γ) ⊆ span β s := λ x hx, span_induction hx (λ _ h, subset_span h) (zero_mem (span β s)) (λ _ _, add_mem (span β s)) (λ x y h, begin have : algebra_map β x • y = x • y, from _, simp at this, end) lemma span_subset_ideal_span {s : set β} : (span α s).carrier ⊆ (ideal.span s).carrier := λ x hx, span_induction hx (λ _ h, ideal.subset_span h) (ideal.zero_mem (ideal.span s)) (λ _ _, ideal.add_mem (ideal.span s)) (λ x y h, by rw algebra.smul_def; exact ideal.mul_mem_left (ideal.span s) h) open vector_space submodule -- set_option trace.class_instances true -- set_option class.instance_max_depth 40 #print span_smul_span lemma tower_law (s : set β) (t : set γ) (hs : span α s = ⊤) (ht : span β t = ⊤) : span α (⋃ (x ∈ s) (y ∈ t), {x • y} : set γ) = ⊤ := have h : ideal.span s = ⊤, from (ideal.eq_top_iff_one _).2 (span_subset_ideal_span (eq_top_iff'.1 hs _)), calc span α (⋃ (x ∈ s) (y ∈ t), {x • y} : set γ) = span α (span β (⋃ (x ∈ s) (y ∈ t), {x • y} : set γ)) : le_antisymm (span_mono subset_span) (λ y hy, _) ... = span α ((ideal.span s • span β t) : submodule β γ) : by rw span_smul_span ... = _ : _ end
702be64c0371236ca519d8d43085af18ffd13cc4
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/order/omega_complete_partial_order.lean
54bcd8bb997f8b79c72e01cf1a7e0b90170b0f72
[ "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
27,539
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfun import order.preorder_hom import tactic.wlog import tactic.monotonicity /-! # Omega Complete Partial Orders An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. The concept of an omega-complete partial order (ωCPO) is useful for the formalization of the semantics of programming languages. Its notion of supremum helps define the meaning of recursive procedures. ## Main definitions * class `omega_complete_partial_order` * `ite`, `map`, `bind`, `seq` as continuous morphisms ## Instances of `omega_complete_partial_order` * `part` * every `complete_lattice` * pi-types * product types * `monotone_hom` * `continuous_hom` (with notation →𝒄) * an instance of `omega_complete_partial_order (α →𝒄 β)` * `continuous_hom.of_fun` * `continuous_hom.of_mono` * continuous functions: * `id` * `ite` * `const` * `part.bind` * `part.map` * `part.seq` ## References * [Chain-complete posets and directed sets with applications][markowsky1976] * [Recursive definitions of partial functions and their computations][cadiou1972] * [Semantics of Programming Languages: Structures and Techniques][gunter1992] -/ universes u v local attribute [-simp] part.bind_eq_bind part.map_eq_map open_locale classical namespace preorder_hom variables (α : Type*) (β : Type*) {γ : Type*} {φ : Type*} variables [preorder α] [preorder β] [preorder γ] [preorder φ] variables {β γ} variables {α} {α' : Type*} {β' : Type*} [preorder α'] [preorder β'] /-- `part.bind` as a monotone function -/ @[simps] def bind {β γ} (f : α →ₘ part β) (g : α →ₘ β → part γ) : α →ₘ part γ := { to_fun := λ x, f x >>= g x, monotone' := begin intros x y h a, simp only [and_imp, exists_prop, part.bind_eq_bind, part.mem_bind_iff, exists_imp_distrib], intros b hb ha, refine ⟨b, f.monotone h _ hb, g.monotone h _ _ ha⟩, end } end preorder_hom namespace omega_complete_partial_order /-- A chain is a monotone sequence. See the definition on page 114 of [gunter1992]. -/ def chain (α : Type u) [preorder α] := ℕ →ₘ α namespace chain variables {α : Type u} {β : Type v} {γ : Type*} variables [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (chain α) := @infer_instance (has_coe_to_fun $ ℕ →ₘ α) _ instance [inhabited α] : inhabited (chain α) := ⟨ ⟨ λ _, default _, λ _ _ _, le_refl _ ⟩ ⟩ instance : has_mem α (chain α) := ⟨λa (c : ℕ →ₘ α), ∃ i, a = c i⟩ variables (c c' : chain α) variables (f : α →ₘ β) variables (g : β →ₘ γ) instance : has_le (chain α) := { le := λ x y, ∀ i, ∃ j, x i ≤ y j } /-- `map` function for `chain` -/ @[simps {fully_applied := ff}] def map : chain β := f.comp c variables {f} lemma mem_map (x : α) : x ∈ c → f x ∈ chain.map c f := λ ⟨i,h⟩, ⟨i, h.symm ▸ rfl⟩ lemma exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b := λ ⟨i,h⟩, ⟨c i, ⟨i, rfl⟩, h.symm⟩ lemma mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b := ⟨ exists_of_mem_map _, λ h, by { rcases h with ⟨w,h,h'⟩, subst b, apply mem_map c _ h, } ⟩ @[simp] lemma map_id : c.map preorder_hom.id = c := preorder_hom.comp_id _ lemma map_comp : (c.map f).map g = c.map (g.comp f) := rfl @[mono] lemma map_le_map {g : α →ₘ β} (h : f ≤ g) : c.map f ≤ c.map g := λ i, by simp [mem_map_iff]; intros; existsi i; apply h /-- `chain.zip` pairs up the elements of two chains that have the same index -/ @[simps] def zip (c₀ : chain α) (c₁ : chain β) : chain (α × β) := preorder_hom.prod c₀ c₁ end chain end omega_complete_partial_order open omega_complete_partial_order section prio set_option extends_priority 50 /-- An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. See the definition on page 114 of [gunter1992]. -/ class omega_complete_partial_order (α : Type*) extends partial_order α := (ωSup : chain α → α) (le_ωSup : ∀(c:chain α), ∀ i, c i ≤ ωSup c) (ωSup_le : ∀(c:chain α) x, (∀ i, c i ≤ x) → ωSup c ≤ x) end prio namespace omega_complete_partial_order variables {α : Type u} {β : Type v} {γ : Type*} variables [omega_complete_partial_order α] /-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α` using a strictly monotone function `f : β →ₘ α`, a definition of ωSup and a proof that `f` is continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/ @[reducible] protected def lift [partial_order β] (f : β →ₘ α) (ωSup₀ : chain β → β) (h : ∀ x y, f x ≤ f y → x ≤ y) (h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : omega_complete_partial_order β := { ωSup := ωSup₀, ωSup_le := λ c x hx, h _ _ (by rw h'; apply ωSup_le; intro; apply f.monotone (hx i)), le_ωSup := λ c i, h _ _ (by rw h'; apply le_ωSup (c.map f)) } lemma le_ωSup_of_le {c : chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c := le_trans h (le_ωSup c _) lemma ωSup_total {c : chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c := classical.by_cases (assume : ∀ i, c i ≤ x, or.inl (ωSup_le _ _ this)) (assume : ¬ ∀ i, c i ≤ x, have ∃ i, ¬ c i ≤ x, by simp only [not_forall] at this ⊢; assumption, let ⟨i, hx⟩ := this in have x ≤ c i, from (h i).resolve_left hx, or.inr $ le_ωSup_of_le _ this) @[mono] lemma ωSup_le_ωSup_of_le {c₀ c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ := ωSup_le _ _ $ λ i, Exists.rec_on (h i) $ λ j h, le_trans h (le_ωSup _ _) lemma ωSup_le_iff (c : chain α) (x : α) : ωSup c ≤ x ↔ (∀ i, c i ≤ x) := begin split; intros, { transitivity ωSup c, exact le_ωSup _ _, assumption }, exact ωSup_le _ _ ‹_›, end /-- A subset `p : α → Prop` of the type closed under `ωSup` induces an `omega_complete_partial_order` on the subtype `{a : α // p a}`. -/ def subtype {α : Type*} [omega_complete_partial_order α] (p : α → Prop) (hp : ∀ (c : chain α), (∀ i ∈ c, p i) → p (ωSup c)) : omega_complete_partial_order (subtype p) := omega_complete_partial_order.lift (preorder_hom.subtype.val p) (λ c, ⟨ωSup _, hp (c.map (preorder_hom.subtype.val p)) (λ i ⟨n, q⟩, q.symm ▸ (c n).2)⟩) (λ x y h, h) (λ c, rfl) section continuity open chain variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- A monotone function `f : α →ₘ β` is continuous if it distributes over ωSup. In order to distinguish it from the (more commonly used) continuity from topology (see topology/basic.lean), the present definition is often referred to as "Scott-continuity" (referring to Dana Scott). It corresponds to continuity in Scott topological spaces (not defined here). -/ def continuous (f : α →ₘ β) : Prop := ∀ c : chain α, f (ωSup c) = ωSup (c.map f) /-- `continuous' f` asserts that `f` is both monotone and continuous. -/ def continuous' (f : α → β) : Prop := ∃ hf : monotone f, continuous ⟨f, hf⟩ lemma continuous'.to_monotone {f : α → β} (hf : continuous' f) : monotone f := hf.fst lemma continuous.of_bundled (f : α → β) (hf : monotone f) (hf' : continuous ⟨f, hf⟩) : continuous' f := ⟨hf, hf'⟩ lemma continuous.of_bundled' (f : α →ₘ β) (hf' : continuous f) : continuous' f := ⟨f.mono, hf'⟩ lemma continuous'.to_bundled (f : α → β) (hf : continuous' f) : continuous ⟨f, hf.to_monotone⟩ := hf.snd @[simp, norm_cast] lemma continuous'_coe : ∀ {f : α →ₘ β}, continuous' f ↔ continuous f | ⟨f, hf⟩ := ⟨λ ⟨hf', hc⟩, hc, λ hc, ⟨hf, hc⟩⟩ variables (f : α →ₘ β) (g : β →ₘ γ) lemma continuous_id : continuous (@preorder_hom.id α _) := by intro; rw c.map_id; refl lemma continuous_comp (hfc : continuous f) (hgc : continuous g) : continuous (g.comp f):= begin dsimp [continuous] at *, intro, rw [hfc,hgc,chain.map_comp] end lemma id_continuous' : continuous' (@id α) := continuous_id.of_bundled' _ lemma continuous_const (x : β) : continuous (preorder_hom.const α x) := λ c, eq_of_forall_ge_iff $ λ z, by simp [ωSup_le_iff] lemma const_continuous' (x: β) : continuous' (function.const α x) := continuous.of_bundled' (preorder_hom.const α x) (continuous_const x) end continuity end omega_complete_partial_order namespace part variables {α : Type u} {β : Type v} {γ : Type*} open omega_complete_partial_order lemma eq_of_chain {c : chain (part α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := begin cases ha with i ha, replace ha := ha.symm, cases hb with j hb, replace hb := hb.symm, wlog h : i ≤ j := le_total i j using [a b i j, b a j i], rw [eq_some_iff] at ha hb, have := c.monotone h _ ha, apply mem_unique this hb end /-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `part α`. -/ protected noncomputable def ωSup (c : chain (part α)) : part α := if h : ∃a, some a ∈ c then some (classical.some h) else none lemma ωSup_eq_some {c : chain (part α)} {a : α} (h : some a ∈ c) : part.ωSup c = some a := have ∃a, some a ∈ c, from ⟨a, h⟩, have a' : some (classical.some this) ∈ c, from classical.some_spec this, calc part.ωSup c = some (classical.some this) : dif_pos this ... = some a : congr_arg _ (eq_of_chain a' h) lemma ωSup_eq_none {c : chain (part α)} (h : ¬∃a, some a ∈ c) : part.ωSup c = none := dif_neg h lemma mem_chain_of_mem_ωSup {c : chain (part α)} {a : α} (h : a ∈ part.ωSup c) : some a ∈ c := begin simp [part.ωSup] at h, split_ifs at h, { have h' := classical.some_spec h_1, rw ← eq_some_iff at h, rw ← h, exact h' }, { rcases h with ⟨ ⟨ ⟩ ⟩ } end noncomputable instance omega_complete_partial_order : omega_complete_partial_order (part α) := { ωSup := part.ωSup, le_ωSup := λ c i, by { intros x hx, rw ← eq_some_iff at hx ⊢, rw [ωSup_eq_some, ← hx], rw ← hx, exact ⟨i,rfl⟩ }, ωSup_le := by { rintros c x hx a ha, replace ha := mem_chain_of_mem_ωSup ha, cases ha with i ha, apply hx i, rw ← ha, apply mem_some } } section inst lemma mem_ωSup (x : α) (c : chain (part α)) : x ∈ ωSup c ↔ some x ∈ c := begin simp [omega_complete_partial_order.ωSup,part.ωSup], split, { split_ifs, swap, rintro ⟨⟨⟩⟩, intro h', have hh := classical.some_spec h, simp at h', subst x, exact hh }, { intro h, have h' : ∃ (a : α), some a ∈ c := ⟨_,h⟩, rw dif_pos h', have hh := classical.some_spec h', rw eq_of_chain hh h, simp } end end inst end part namespace pi variables {α : Type*} {β : α → Type*} {γ : Type*} open omega_complete_partial_order omega_complete_partial_order.chain instance [∀a, omega_complete_partial_order (β a)] : omega_complete_partial_order (Πa, β a) := { ωSup := λc a, ωSup (c.map (pi.eval_preorder_hom a)), ωSup_le := assume c f hf a, ωSup_le _ _ $ by { rintro i, apply hf }, le_ωSup := assume c i x, le_ωSup_of_le _ $ le_refl _ } namespace omega_complete_partial_order variables [∀ x, omega_complete_partial_order $ β x] variables [omega_complete_partial_order γ] lemma flip₁_continuous' (f : ∀ x : α, γ → β x) (a : α) (hf : continuous' (λ x y, f y x)) : continuous' (f a) := continuous.of_bundled _ (λ x y h, hf.to_monotone h a) (λ c, congr_fun (hf.to_bundled _ c) a) lemma flip₂_continuous' (f : γ → Π x, β x) (hf : ∀ x, continuous' (λ g, f g x)) : continuous' f := continuous.of_bundled _ (λ x y h a, (hf a).to_monotone h) (by intro c; ext a; apply (hf a).to_bundled _ c) end omega_complete_partial_order end pi namespace prod open omega_complete_partial_order variables {α : Type*} {β : Type*} {γ : Type*} variables [omega_complete_partial_order α] variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- The supremum of a chain in the product `ω`-CPO. -/ @[simps] protected def ωSup (c : chain (α × β)) : α × β := (ωSup (c.map preorder_hom.fst), ωSup (c.map preorder_hom.snd)) @[simps ωSup_fst ωSup_snd] instance : omega_complete_partial_order (α × β) := { ωSup := prod.ωSup, ωSup_le := λ c ⟨x,x'⟩ h, ⟨ωSup_le _ _ $ λ i, (h i).1, ωSup_le _ _ $ λ i, (h i).2⟩, le_ωSup := λ c i, ⟨le_ωSup (c.map preorder_hom.fst) i, le_ωSup (c.map preorder_hom.snd) i⟩ } end prod namespace complete_lattice variables (α : Type u) /-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case of arbitrary suprema. -/ @[priority 100] -- see Note [lower instance priority] instance [complete_lattice α] : omega_complete_partial_order α := { ωSup := λc, ⨆ i, c i, ωSup_le := λ ⟨c, _⟩ s hs, by simp only [supr_le_iff, preorder_hom.coe_fun_mk] at ⊢ hs; intros i; apply hs i, le_ωSup := assume ⟨c, _⟩ i, by simp only [preorder_hom.coe_fun_mk]; apply le_supr_of_le i; refl } variables {α} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] open omega_complete_partial_order lemma inf_continuous [is_total β (≤)] (f g : α →ₘ β) (hf : continuous f) (hg : continuous g) : continuous (f ⊓ g) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [inf_le_iff, hf c, hg c, ωSup_le_iff, ←forall_or_distrib_left, ←forall_or_distrib_right, function.comp_app, chain.map_coe, preorder_hom.has_inf_inf_coe], split, { introv h, apply h }, { intros h i j, apply or.imp _ _ (h (max i j)); apply le_trans; mono*; try { exact le_rfl }, { apply le_max_left }, { apply le_max_right }, }, end lemma Sup_continuous (s : set $ α →ₘ β) (hs : ∀ f ∈ s, continuous f) : continuous (Sup s) := begin intro c, apply eq_of_forall_ge_iff, intro z, suffices : (∀ (f ∈ s) n, (f : _) (c n) ≤ z) ↔ (∀ n (f ∈ s), (f : _) (c n) ≤ z), by simpa [ωSup_le_iff, hs _ _ _] { contextual := tt }, exact ⟨λ H n f hf, H f hf n, λ H f hf n, H n f hf⟩ end lemma supr_continuous {ι : Sort*} {f : ι → α →ₘ β} (h : ∀ i, continuous (f i)) : continuous (⨆ i, f i) := Sup_continuous _ $ set.forall_range_iff.2 h theorem Sup_continuous' (s : set (α → β)) (hc : ∀ f ∈ s, continuous' f) : continuous' (Sup s) := begin lift s to set (α →ₘ β) using λ f hf, (hc f hf).to_monotone, simp only [set.ball_image_iff, continuous'_coe] at hc, rw [Sup_image], norm_cast, exact supr_continuous (λ f, supr_continuous (λ hf, hc f hf)), end lemma sup_continuous {f g : α →ₘ β} (hf : continuous f) (hg : continuous g) : continuous (f ⊔ g) := begin rw ← Sup_pair, apply Sup_continuous, rintro f (rfl|rfl|_); assumption end lemma top_continuous : continuous (⊤ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_coe, (∘), function.const, preorder_hom.has_top_top, preorder_hom.const_coe_coe], end lemma bot_continuous : continuous (⊥ : α →ₘ β) := begin rw ← Sup_empty, exact Sup_continuous _ (λ f hf, hf.elim), end end complete_lattice namespace omega_complete_partial_order variables {α : Type u} {α' : Type*} {β : Type v} {β' : Type*} {γ : Type*} {φ : Type*} variables [omega_complete_partial_order α] [omega_complete_partial_order β] variables [omega_complete_partial_order γ] [omega_complete_partial_order φ] variables [omega_complete_partial_order α'] [omega_complete_partial_order β'] namespace preorder_hom /-- The `ωSup` operator for monotone functions. -/ @[simps] protected def ωSup (c : chain (α →ₘ β)) : α →ₘ β := { to_fun := λ a, ωSup (c.map (preorder_hom.apply a)), monotone' := λ x y h, ωSup_le_ωSup_of_le (chain.map_le_map _ $ λ a, a.monotone h) } @[simps ωSup_coe] instance omega_complete_partial_order : omega_complete_partial_order (α →ₘ β) := omega_complete_partial_order.lift preorder_hom.coe_fn_hom preorder_hom.ωSup (λ x y h, h) (λ c, rfl) end preorder_hom section variables (α β) /-- A monotone function on `ω`-continuous partial orders is said to be continuous if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`. This is just the bundled version of `preorder_hom.continuous`. -/ structure continuous_hom extends preorder_hom α β := (cont : continuous (preorder_hom.mk to_fun monotone')) attribute [nolint doc_blame] continuous_hom.to_preorder_hom infixr ` →𝒄 `:25 := continuous_hom -- Input: \r\MIc instance : has_coe_to_fun (α →𝒄 β) := { F := λ _, α → β, coe := λ f, f.to_preorder_hom.to_fun } instance : has_coe (α →𝒄 β) (α →ₘ β) := { coe := continuous_hom.to_preorder_hom } instance : partial_order (α →𝒄 β) := partial_order.lift (λ f, f.to_preorder_hom.to_fun) $ by rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ h; congr; exact h /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def continuous_hom.simps.apply (h : α →𝒄 β) : α → β := h initialize_simps_projections continuous_hom (to_preorder_hom_to_fun → apply, -to_preorder_hom) end namespace continuous_hom theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →𝒄 β, h x) h theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h protected lemma monotone (f : α →𝒄 β) : monotone f := f.monotone' @[mono] lemma apply_mono {f g : α →𝒄 β} {x y : α} (h₁ : f ≤ g) (h₂ : x ≤ y) : f x ≤ g y := preorder_hom.apply_mono (show (f : α →ₘ β) ≤ g, from h₁) h₂ lemma ite_continuous' {p : Prop} [hp : decidable p] (f g : α → β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, if p then f x else g x) := by split_ifs; simp * lemma ωSup_bind {β γ : Type v} (c : chain α) (f : α →ₘ part β) (g : α →ₘ β → part γ) : ωSup (c.map (f.bind g)) = ωSup (c.map f) >>= ωSup (c.map g) := begin apply eq_of_forall_ge_iff, intro x, simp only [ωSup_le_iff, part.bind_le, chain.mem_map_iff, and_imp, preorder_hom.bind_coe, exists_imp_distrib], split; intro h''', { intros b hb, apply ωSup_le _ _ _, rintros i y hy, simp only [part.mem_ωSup] at hb, rcases hb with ⟨j,hb⟩, replace hb := hb.symm, simp only [part.eq_some_iff, chain.map_coe, function.comp_app, preorder_hom.apply_coe] at hy hb, replace hb : b ∈ f (c (max i j)) := f.mono (c.mono (le_max_right i j)) _ hb, replace hy : y ∈ g (c (max i j)) b := g.mono (c.mono (le_max_left i j)) _ _ hy, apply h''' (max i j), simp only [exists_prop, part.bind_eq_bind, part.mem_bind_iff, chain.map_coe, function.comp_app, preorder_hom.bind_coe], exact ⟨_,hb,hy⟩, }, { intros i, intros y hy, simp only [exists_prop, part.bind_eq_bind, part.mem_bind_iff, chain.map_coe, function.comp_app, preorder_hom.bind_coe] at hy, rcases hy with ⟨b,hb₀,hb₁⟩, apply h''' b _, { apply le_ωSup (c.map g) _ _ _ hb₁ }, { apply le_ωSup (c.map f) i _ hb₀ } }, end lemma bind_continuous' {β γ : Type v} (f : α → part β) (g : α → β → part γ) : continuous' f → continuous' g → continuous' (λ x, f x >>= g x) | ⟨hf,hf'⟩ ⟨hg,hg'⟩ := continuous.of_bundled' (preorder_hom.bind ⟨f,hf⟩ ⟨g,hg⟩) (by intro c; rw [ωSup_bind, ← hf', ← hg']; refl) lemma map_continuous' {β γ : Type v} (f : β → γ) (g : α → part β) (hg : continuous' g) : continuous' (λ x, f <$> g x) := by simp only [map_eq_bind_pure_comp]; apply bind_continuous' _ _ hg; apply const_continuous' lemma seq_continuous' {β γ : Type v} (f : α → part (β → γ)) (g : α → part β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, f x <*> g x) := by simp only [seq_eq_bind_map]; apply bind_continuous' _ _ hf; apply pi.omega_complete_partial_order.flip₂_continuous'; intro; apply map_continuous' _ _ hg lemma continuous (F : α →𝒄 β) (C : chain α) : F (ωSup C) = ωSup (C.map F) := continuous_hom.cont _ _ /-- Construct a continuous function from a bare function, a continuous function, and a proof that they are equal. -/ @[simps, reducible] def of_fun (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β := by refine {to_preorder_hom := {to_fun := f, ..}, ..}; subst h; rcases g with ⟨⟨⟩⟩; assumption /-- Construct a continuous function from a monotone function with a proof of continuity. -/ @[simps, reducible] def of_mono (f : α →ₘ β) (h : ∀ c : chain α, f (ωSup c) = ωSup (c.map f)) : α →𝒄 β := { to_fun := f, monotone' := f.monotone, cont := h } /-- The identity as a continuous function. -/ @[simps] def id : α →𝒄 α := of_mono preorder_hom.id continuous_id /-- The composition of continuous functions. -/ @[simps] def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ := of_mono (preorder_hom.comp (↑f) (↑g)) (continuous_comp _ _ g.cont f.cont) @[ext] protected lemma ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr; ext; apply h protected lemma coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g := continuous_hom.ext _ _ $ _root_.congr_fun h @[simp] lemma comp_id (f : β →𝒄 γ) : f.comp id = f := by ext; refl @[simp] lemma id_comp (f : β →𝒄 γ) : id.comp f = f := by ext; refl @[simp] lemma comp_assoc (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h := by ext; refl @[simp] lemma coe_apply (a : α) (f : α →𝒄 β) : (f : α →ₘ β) a = f a := rfl /-- `function.const` is a continuous function. -/ def const (x : β) : α →𝒄 β := of_mono (preorder_hom.const _ x) (continuous_const x) @[simp] theorem const_apply (f : β) (a : α) : const f a = f := rfl instance [inhabited β] : inhabited (α →𝒄 β) := ⟨ const (default β) ⟩ namespace prod /-- The application of continuous functions as a monotone function. (It would make sense to make it a continuous function, but we are currently constructing a `omega_complete_partial_order` instance for `α →𝒄 β`, and we cannot use it as the domain or image of a continuous function before we do.) -/ @[simps] def apply : (α →𝒄 β) × α →ₘ β := { to_fun := λ f, f.1 f.2, monotone' := λ x y h, by dsimp; transitivity y.fst x.snd; [apply h.1, apply y.1.monotone h.2] } end prod /-- The map from continuous functions to monotone functions is itself a monotone function. -/ @[simps] def to_mono : (α →𝒄 β) →ₘ (α →ₘ β) := { to_fun := λ f, f, monotone' := λ x y h, h } /-- When proving that a chain of applications is below a bound `z`, it suffices to consider the functions and values being selected from the same index in the chains. This lemma is more specific than necessary, i.e. `c₀` only needs to be a chain of monotone functions, but it is only used with continuous functions. -/ @[simp] lemma forall_forall_merge (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (i j : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := begin split; introv h, { apply h }, { apply le_trans _ (h (max i j)), transitivity c₀ i (c₁ (max i j)), { apply (c₀ i).monotone, apply c₁.monotone, apply le_max_right }, { apply c₀.monotone, apply le_max_left } } end @[simp] lemma forall_forall_merge' (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (j i : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := by rw [forall_swap,forall_forall_merge] /-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum of the functions in the `ω`-chain. -/ @[simps] protected def ωSup (c : chain (α →𝒄 β)) : α →𝒄 β := continuous_hom.of_mono (ωSup $ c.map to_mono) begin intro c', apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c _).continuous, chain.map_coe, preorder_hom.apply_coe, to_mono_coe, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_coe, forall_forall_merge, forall_forall_merge', (∘), function.eval], end @[simps ωSup] instance : omega_complete_partial_order (α →𝒄 β) := omega_complete_partial_order.lift continuous_hom.to_mono continuous_hom.ωSup (λ x y h, h) (λ c, rfl) lemma ωSup_def (c : chain (α →𝒄 β)) (x : α) : ωSup c x = continuous_hom.ωSup c x := rfl lemma ωSup_ωSup (c₀ : chain (α →𝒄 β)) (c₁ : chain α) : ωSup c₀ (ωSup c₁) = ωSup (continuous_hom.prod.apply.comp $ c₀.zip c₁) := begin apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c₀ _).continuous, chain.map_coe, to_mono_coe, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_coe, ωSup_def, forall_forall_merge, chain.zip_coe, preorder_hom.prod_map_coe, preorder_hom.diag_coe, prod.map_mk, preorder_hom.apply_coe, function.comp_app, prod.apply_coe, preorder_hom.comp_coe, ωSup_apply, function.eval], end /-- A family of continuous functions yields a continuous family of functions. -/ @[simps] def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ := { to_fun := λ x y, f y x, monotone' := λ x y h a, (f a).monotone h, cont := by intro; ext; change f x _ = _; rw [(f x).continuous ]; refl, } /-- `part.bind` as a continuous function. -/ @[simps { rhs_md := reducible }] noncomputable def bind {β γ : Type v} (f : α →𝒄 part β) (g : α →𝒄 β → part γ) : α →𝒄 part γ := of_mono (preorder_hom.bind (↑f) (↑g)) $ λ c, begin rw [preorder_hom.bind, ← preorder_hom.bind, ωSup_bind, ← f.continuous, ← g.continuous], refl end /-- `part.map` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 part β) : α →𝒄 part γ := of_fun (λ x, f <$> g x) (bind g (const (pure ∘ f))) $ by ext; simp only [map_eq_bind_pure_comp, bind_apply, preorder_hom.bind_coe, const_apply, preorder_hom.const_coe_coe, coe_apply] /-- `part.seq` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def seq {β γ : Type v} (f : α →𝒄 part (β → γ)) (g : α →𝒄 part β) : α →𝒄 part γ := of_fun (λ x, f x <*> g x) (bind f $ (flip $ _root_.flip map g)) (by ext; simp only [seq_eq_bind_map, flip, part.bind_eq_bind, map_apply, part.mem_bind_iff, bind_apply, preorder_hom.bind_coe, coe_apply, flip_apply]; refl) end continuous_hom end omega_complete_partial_order
32dc5b2df54a26f750bc3a5d917ff9a0138ca4f3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/subst.lean
8555968b7ed36b6de150a9948996ed2dd8aacbea
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,263
lean
universe u def f1 (n m : Nat) (x : Fin n) (h : n = m) : Fin m := h ▸ x def f2 (n m : Nat) (x : Fin n) (h : m = n) : Fin m := h ▸ x theorem ex1 {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ theorem ex2 {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl theorem ex3 {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ theorem ex3b {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂.symm ▸ h₁ theorem ex3c {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂.symm.symm ▸ h₁ theorem ex4 {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁ ▸ h₂ theorem ex5 {p : Prop} (h : p = True) : p := h ▸ trivial theorem ex6 {p : Prop} (h : p = False) : ¬p := fun hp => h ▸ hp theorem ex7 {α} {a b c d : α} (h₁ : a = c) (h₂ : b = d) (h₃ : c ≠ d) : a ≠ b := h₁ ▸ h₂ ▸ h₃ theorem ex8 (n m k : Nat) (h : Nat.succ n + m = Nat.succ n + k) : Nat.succ (n + m) = Nat.succ (n + k) := Nat.succ_add .. ▸ Nat.succ_add .. ▸ h theorem ex9 (a b : Nat) (h₁ : a = a + b) (h₂ : a = b) : a = b + a := h₂ ▸ h₁ theorem ex10 (a b : Nat) (h : a = b) : b = a := h ▸ rfl def ex11 {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁ ▸ h₂⟩ theorem ex12 {α : Type u} {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : ∀ (i : Nat) (hi : i < n), a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) def toArrayLit {α : Type u} (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray $ Array.toListLitAux a n hsz n (hsz ▸ Nat.le_refl _) [] partial def isEqvAux {α} (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩ let bidx : Fin b.size := ⟨i, hsz ▸ h⟩ match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true
f200f12ffe6a4e5341af0e7642bb31f5f4dd2716
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/analysis/hofer.lean
79bfd336822ea033eb8303438c0414ccef284989
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
4,851
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import analysis.specific_limits /-! # Hofer's lemma This is an elementary lemma about complete metric spaces. It is motivated by an application to the bubbling-off analysis for holomorphic curves in symplectic topology. We are *very* far away from having these applications, but the proof here is a nice example of a proof needing to construct a sequence by induction in the middle of the proof. ## References: * H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres* -/ open_locale classical topological_space big_operators open filter finset local notation `d` := dist @[nolint ge_or_gt] -- see Note [nolint_ge] lemma hofer {X: Type*} [metric_space X] [complete_space X] (x : X) (ε : ℝ) (ε_pos : 0 < ε) {ϕ : X → ℝ} (cont : continuous ϕ) (nonneg : ∀ y, 0 ≤ ϕ y) : ∃ (ε' > 0) (x' : X), ε' ≤ ε ∧ d x' x ≤ 2*ε ∧ ε * ϕ(x) ≤ ε' * ϕ x' ∧ ∀ y, d x' y ≤ ε' → ϕ y ≤ 2*ϕ x' := begin by_contradiction H, have reformulation : ∀ x' (k : ℕ), ε * ϕ x ≤ ε / 2 ^ k * ϕ x' ↔ 2^k * ϕ x ≤ ϕ x', { intros x' k, rw [div_mul_eq_mul_div, le_div_iff, mul_assoc, mul_le_mul_left ε_pos, mul_comm], exact pow_pos (by norm_num) k, }, -- Now let's pull the existential quantifiers in front replace H : ∀ k : ℕ, ∀ x', ∃ y, d x' x ≤ 2 * ε ∧ 2^k * ϕ x ≤ ϕ x' → d x' y ≤ ε/2^k ∧ 2 * ϕ x' < ϕ y, { intros k x', by_cases h' : d x' x ≤ 2 * ε ∧ 2^k * ϕ x ≤ ϕ x', { contrapose H, rw not_not, use ε/2^k, suffices : ∃ x', d x' x ≤ 2 * ε ∧ ε * ϕ x ≤ ε / 2 ^ k * ϕ x' ∧ ∀ (y : X), d x' y ≤ ε / 2 ^ k → ϕ y ≤ 2 * ϕ x', by simpa [ε_pos, two_pos, one_le_two], use x', simpa [h'.left, reformulation, h'.right, h'] using H }, { use x } }, clear reformulation, choose F hF using H, -- Use the axiom of choice -- Now define u by induction starting at x, with u_{n+1} = F(n, u_n) let u : ℕ → X := λ n, nat.rec_on n x F, -- The properties of F translate to properties of u have hu : ∀ n, d (u n) x ≤ 2 * ε ∧ 2^n * ϕ x ≤ ϕ (u n) → d (u n) (u $ n + 1) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u $ n + 1), { intro n, exact hF n (u n) }, clear hF, -- Key properties of u, to be proven by induction have key : ∀ n, d (u n) (u (n + 1)) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u (n + 1)), { intro n, induction n using nat.case_strong_induction_on with n IH, { specialize hu 0, simp [show u 0 = x, from rfl, le_refl] at *, exact hu (by linarith) }, have A : d (u (n+1)) x ≤ 2 * ε, { rw [dist_comm], let r := range (n+1), -- range (n+1) = {0, ..., n} calc d (u 0) (u (n + 1)) ≤ ∑ i in r, d (u i) (u $ i+1) : dist_le_range_sum_dist u (n + 1) ... ≤ ∑ i in r, ε/2^i : sum_le_sum (λ i i_in, (IH i $ nat.lt_succ_iff.mp $ finset.mem_range.mp i_in).1) ... = ∑ i in r, (1/2)^i*ε : by { congr, ext i, field_simp } ... = (∑ i in r, (1/2)^i)*ε : finset.sum_mul.symm ... ≤ 2*ε : mul_le_mul_of_nonneg_right (sum_geometric_two_le _) (le_of_lt ε_pos), }, have B : 2^(n+1) * ϕ x ≤ ϕ (u (n + 1)), { apply le_of_lt, exact geom_lt (by norm_num) (λ m hm, (IH _ hm).2), }, exact hu (n+1) ⟨A, B⟩, }, cases forall_and_distrib.mp key with key₁ key₂, clear hu key, -- Hence u is Cauchy have cauchy_u : cauchy_seq u, { apply cauchy_seq_of_le_geometric _ ε (by norm_num : 1/(2:ℝ) < 1), intro n, convert key₁ n, simp }, -- So u converges to some y obtain ⟨y, limy⟩ : ∃ y, tendsto u at_top (𝓝 y), from complete_space.complete cauchy_u, -- And ϕ ∘ u goes to +∞ have lim_top : tendsto (ϕ ∘ u) at_top at_top, { let v := λ n, (ϕ ∘ u) (n+1), suffices : tendsto v at_top at_top, by rwa tendsto_add_at_top_iff_nat at this, have hv₀ : 0 < v 0, { have : 0 ≤ ϕ (u 0) := nonneg x, calc 0 ≤ 2 * ϕ (u 0) : by linarith ... < ϕ (u (0 + 1)) : key₂ 0 }, apply tendsto_at_top_of_geom_lt hv₀ (by norm_num : (1 : ℝ) < 2), exact λ n, key₂ (n+1) }, -- But ϕ ∘ u also needs to go to ϕ(y) have lim : tendsto (ϕ ∘ u) at_top (𝓝 (ϕ y)), from tendsto.comp cont.continuous_at limy, -- So we have our contradiction! exact not_tendsto_at_top_of_tendsto_nhds lim lim_top, end
450b84af74dbbaee9340e7532b7c9f538205695b
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/pnat/factors.lean
4d2a3b25016cb428ca51cb38d37d6d2a1a1e3a88
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
13,991
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland -/ import tactic.basic import data.pnat.basic data.nat.prime data.multiset data.int.basic data.int.gcd algebra.group algebra.group_power algebra.ordered_ring /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : lattice.distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : lattice.semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≤ v → u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p :: 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_inj : function.injective (coe : prime_multiset → multiset ℕ) := multiset.injective_map nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = (p : ℕ) :: 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_inj : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.injective_map nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = (p : ℕ+) :: 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := (v.to_pnat_multiset.prod_hom coe).symm, rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := by { change multiset.prod ((p : ℕ+) :: 0) = (p : ℕ+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset → multiset ℕ+)], rw [multiset.prod_add] } theorem prod_smul (d : ℕ) (u : prime_multiset) : (add_monoid.smul d u).prod = u.prod ^ d := by { induction d with d ih, refl, rw[succ_smul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_inj, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with l, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = add_monoid.smul m (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd_intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply lattice.le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact lattice.inf_le_left, exact lattice.inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact lattice.le_sup_left, exact lattice.le_sup_right}, { apply lattice.sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] }, { have : ∀ (m : ℕ), add_monoid.smul m (p::0) = multiset.repeat p m := λ m, by {induction m with m ih, { refl }, rw [succ_smul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
e770ff01b69e535a81dbbc568268dc9bace4ea8b
92b50235facfbc08dfe7f334827d47281471333b
/library/data/int/gcd.lean
22527bee743754f13613ec10b11ddfac929ff290
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
14,196
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Definitions and properties of gcd, lcm, and coprime. -/ import .div data.nat.gcd open eq.ops namespace int /- gcd -/ definition gcd (a b : ℤ) : ℤ := of_nat (nat.gcd (nat_abs a) (nat_abs b)) theorem gcd_nonneg (a b : ℤ) : gcd a b ≥ 0 := of_nat_nonneg (nat.gcd (nat_abs a) (nat_abs b)) theorem gcd.comm (a b : ℤ) : gcd a b = gcd b a := by rewrite [↑gcd, nat.gcd.comm] theorem gcd_zero_right (a : ℤ) : gcd a 0 = abs a := by krewrite [↑gcd, nat.gcd_zero_right, of_nat_nat_abs] theorem gcd_zero_left (a : ℤ) : gcd 0 a = abs a := by rewrite [gcd.comm, gcd_zero_right] theorem gcd_one_right (a : ℤ) : gcd a 1 = 1 := by krewrite [↑gcd, nat.gcd_one_right] theorem gcd_one_left (a : ℤ) : gcd 1 a = 1 := by rewrite [gcd.comm, gcd_one_right] theorem gcd_abs_left (a b : ℤ) : gcd (abs a) b = gcd a b := by rewrite [↑gcd, *nat_abs_abs] theorem gcd_abs_right (a b : ℤ) : gcd (abs a) b = gcd a b := by rewrite [↑gcd, *nat_abs_abs] theorem gcd_abs_abs (a b : ℤ) : gcd (abs a) (abs b) = gcd a b := by rewrite [↑gcd, *nat_abs_abs] theorem gcd_of_ne_zero (a : ℤ) {b : ℤ} (H : b ≠ 0) : gcd a b = gcd b (abs a mod abs b) := have H1 : nat_abs b ≠ nat.zero, from assume H', H (nat_abs_eq_zero H'), have H2 : (#nat nat_abs b > nat.zero), from nat.pos_of_ne_zero H1, assert H3 : nat.gcd (nat_abs a) (nat_abs b) = (#nat nat.gcd (nat_abs b) (nat_abs a mod nat_abs b)), from @nat.gcd_of_pos (nat_abs a) (nat_abs b) H2, calc gcd a b = nat.gcd (nat_abs b) (#nat nat_abs a mod nat_abs b) : by rewrite [↑gcd, H3] ... = gcd (abs b) (abs a mod abs b) : by rewrite [↑gcd, -*of_nat_nat_abs, of_nat_mod] ... = gcd b (abs a mod abs b) : by rewrite [↑gcd, *nat_abs_abs] theorem gcd_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : gcd a b = gcd b (abs a mod b) := by rewrite [!gcd_of_ne_zero (ne_of_gt H), abs_of_pos H] theorem gcd_of_nonneg_of_pos {a b : ℤ} (H1 : a ≥ 0) (H2 : b > 0) : gcd a b = gcd b (a mod b) := by rewrite [!gcd_of_pos H2, abs_of_nonneg H1] theorem gcd_self (a : ℤ) : gcd a a = abs a := by rewrite [↑gcd, nat.gcd_self, of_nat_nat_abs] theorem gcd_dvd_left (a b : ℤ) : gcd a b ∣ a := have H : gcd a b ∣ abs a, by rewrite [↑gcd, -of_nat_nat_abs, of_nat_dvd_of_nat]; apply nat.gcd_dvd_left, iff.mp !dvd_abs_iff H theorem gcd_dvd_right (a b : ℤ) : gcd a b ∣ b := by rewrite gcd.comm; apply gcd_dvd_left theorem dvd_gcd {a b c : ℤ} : a ∣ b → a ∣ c → a ∣ gcd b c := begin rewrite [↑gcd, -*(abs_dvd_iff a), -(dvd_abs_iff _ b), -(dvd_abs_iff _ c), -*of_nat_nat_abs], rewrite [*of_nat_dvd_of_nat] , apply nat.dvd_gcd end theorem gcd.assoc (a b c : ℤ) : gcd (gcd a b) c = gcd a (gcd b c) := dvd.antisymm !gcd_nonneg !gcd_nonneg (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_left) (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right)) (dvd_gcd (dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left)) (dvd.trans !gcd_dvd_right !gcd_dvd_right)) theorem gcd_mul_left (a b c : ℤ) : gcd (a * b) (a * c) = abs a * gcd b c := by rewrite [↑gcd, *nat_abs_mul, nat.gcd_mul_left, of_nat_mul, of_nat_nat_abs] theorem gcd_mul_right (a b c : ℤ) : gcd (a * b) (c * b) = gcd a c * abs b := by rewrite [mul.comm a, mul.comm c, mul.comm (gcd a c), gcd_mul_left] theorem gcd_pos_of_ne_zero_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : gcd a b > 0 := have H1 : gcd a b ≠ 0, from assume H2 : gcd a b = 0, have H3: 0 ∣ a, from H2 ▸ gcd_dvd_left a b, show false, from H (eq_zero_of_zero_dvd H3), lt_of_le_of_ne (gcd_nonneg a b) (ne.symm H1) theorem gcd_pos_of_ne_zero_right (a : ℤ) {b : ℤ} (H : b ≠ 0) : gcd a b > 0 := by rewrite gcd.comm; apply !gcd_pos_of_ne_zero_left H theorem eq_zero_of_gcd_eq_zero_left {a b : ℤ} (H : gcd a b = 0) : a = 0 := decidable.by_contradiction (assume H1 : a ≠ 0, have H2 : gcd a b > 0, from !gcd_pos_of_ne_zero_left H1, ne_of_lt H2 H⁻¹) theorem eq_zero_of_gcd_eq_zero_right {a b : ℤ} (H : gcd a b = 0) : b = 0 := by rewrite gcd.comm at H; apply !eq_zero_of_gcd_eq_zero_left H theorem gcd_div {a b c : ℤ} (H1 : c ∣ a) (H2 : c ∣ b) : gcd (a div c) (b div c) = gcd a b div (abs c) := decidable.by_cases (assume H3 : c = 0, calc gcd (a div c) (b div c) = gcd 0 0 : by subst c; rewrite *div_zero ... = 0 : gcd_zero_left ... = gcd a b div 0 : div_zero ... = gcd a b div (abs c) : by subst c) (assume H3 : c ≠ 0, have H4 : abs c ≠ 0, from assume H', H3 (eq_zero_of_abs_eq_zero H'), eq.symm (div_eq_of_eq_mul_left H4 (eq.symm (calc gcd (a div c) (b div c) * abs c = gcd (a div c * c) (b div c * c) : gcd_mul_right ... = gcd a (b div c * c) : div_mul_cancel H1 ... = gcd a b : div_mul_cancel H2)))) theorem gcd_dvd_gcd_mul_left (a b c : ℤ) : gcd a b ∣ gcd (c * a) b := dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right theorem gcd_dvd_gcd_mul_right (a b c : ℤ) : gcd a b ∣ gcd (a * c) b := !mul.comm ▸ !gcd_dvd_gcd_mul_left theorem div_gcd_eq_div_gcd_of_nonneg {a₁ b₁ a₂ b₂ : ℤ} (H : a₁ * b₂ = a₂ * b₁) (H1 : b₁ ≠ 0) (H2 : b₂ ≠ 0) (H3 : a₁ ≥ 0) (H4 : a₂ ≥ 0) : a₁ div (gcd a₁ b₁) = a₂ div (gcd a₂ b₂) := begin apply div_eq_div_of_dvd_of_dvd, repeat (apply gcd_dvd_left), intro H', apply H1, apply eq_zero_of_gcd_eq_zero_right H', intro H', apply H2, apply eq_zero_of_gcd_eq_zero_right H', rewrite [-abs_of_nonneg H3 at {1}, -abs_of_nonneg H4 at {2}], rewrite [-gcd_mul_left, -gcd_mul_right, H, mul.comm b₁] end theorem div_gcd_eq_div_gcd {a₁ b₁ a₂ b₂ : ℤ} (H : a₁ * b₂ = a₂ * b₁) (H1 : b₁ > 0) (H2 : b₂ > 0) : a₁ div (gcd a₁ b₁) = a₂ div (gcd a₂ b₂) := or.elim (le_or_gt 0 a₁) (assume H3 : a₁ ≥ 0, have H4 : a₂ * b₁ ≥ 0, by rewrite -H; apply mul_nonneg H3 (le_of_lt H2), have H5 : a₂ ≥ 0, from nonneg_of_mul_nonneg_right H4 H1, div_gcd_eq_div_gcd_of_nonneg H (ne_of_gt H1) (ne_of_gt H2) H3 H5) (assume H3 : a₁ < 0, have H4 : a₂ * b₁ < 0, by rewrite -H; apply mul_neg_of_neg_of_pos H3 H2, assert H5 : a₂ < 0, from neg_of_mul_neg_right H4 (le_of_lt H1), assert H6 : abs a₁ div (gcd (abs a₁) (abs b₁)) = abs a₂ div (gcd (abs a₂) (abs b₂)), begin apply div_gcd_eq_div_gcd_of_nonneg, rewrite [abs_of_pos H1, abs_of_pos H2, abs_of_neg H3, abs_of_neg H5], rewrite [-*neg_mul_eq_neg_mul, H], apply ne_of_gt (abs_pos_of_pos H1), apply ne_of_gt (abs_pos_of_pos H2), repeat (apply abs_nonneg) end, have H7 : -a₁ div (gcd a₁ b₁) = -a₂ div (gcd a₂ b₂), begin rewrite [-abs_of_neg H3, -abs_of_neg H5, -gcd_abs_abs a₁], rewrite [-gcd_abs_abs a₂ b₂], exact H6 end, calc a₁ div (gcd a₁ b₁) = -(-a₁ div (gcd a₁ b₁)) : by rewrite [neg_div_of_dvd !gcd_dvd_left, neg_neg] ... = -(-a₂ div (gcd a₂ b₂)) : H7 ... = a₂ div (gcd a₂ b₂) : by rewrite [neg_div_of_dvd !gcd_dvd_left, neg_neg]) /- lcm -/ definition lcm (a b : ℤ) : ℤ := of_nat (nat.lcm (nat_abs a) (nat_abs b)) theorem lcm_nonneg (a b : ℤ) : lcm a b ≥ 0 := of_nat_nonneg (nat.lcm (nat_abs a) (nat_abs b)) theorem lcm.comm (a b : ℤ) : lcm a b = lcm b a := by rewrite [↑lcm, nat.lcm.comm] theorem lcm_zero_left (a : ℤ) : lcm 0 a = 0 := by krewrite [↑lcm, nat.lcm_zero_left] theorem lcm_zero_right (a : ℤ) : lcm a 0 = 0 := !lcm.comm ▸ !lcm_zero_left theorem lcm_one_left (a : ℤ) : lcm 1 a = abs a := by krewrite [↑lcm, nat.lcm_one_left, of_nat_nat_abs] theorem lcm_one_right (a : ℤ) : lcm a 1 = abs a := !lcm.comm ▸ !lcm_one_left theorem lcm_abs_left (a b : ℤ) : lcm (abs a) b = lcm a b := by rewrite [↑lcm, *nat_abs_abs] theorem lcm_abs_right (a b : ℤ) : lcm (abs a) b = lcm a b := by rewrite [↑lcm, *nat_abs_abs] theorem lcm_abs_abs (a b : ℤ) : lcm (abs a) (abs b) = lcm a b := by rewrite [↑lcm, *nat_abs_abs] theorem lcm_self (a : ℤ) : lcm a a = abs a := by krewrite [↑lcm, nat.lcm_self, of_nat_nat_abs] theorem dvd_lcm_left (a b : ℤ) : a ∣ lcm a b := by rewrite [↑lcm, -abs_dvd_iff, -of_nat_nat_abs, of_nat_dvd_of_nat]; apply nat.dvd_lcm_left theorem dvd_lcm_right (a b : ℤ) : b ∣ lcm a b := !lcm.comm ▸ !dvd_lcm_left theorem gcd_mul_lcm (a b : ℤ) : gcd a b * lcm a b = abs (a * b) := begin rewrite [↑gcd, ↑lcm, -of_nat_nat_abs, -of_nat_mul, of_nat_eq_of_nat, nat_abs_mul], apply nat.gcd_mul_lcm end theorem lcm_dvd {a b c : ℤ} : a ∣ c → b ∣ c → lcm a b ∣ c := begin rewrite [↑lcm, -(abs_dvd_iff a), -(abs_dvd_iff b), -*(dvd_abs_iff _ c), -*of_nat_nat_abs], rewrite [*of_nat_dvd_of_nat] , apply nat.lcm_dvd end theorem lcm_assoc (a b c : ℤ) : lcm (lcm a b) c = lcm a (lcm b c) := dvd.antisymm !lcm_nonneg !lcm_nonneg (lcm_dvd (lcm_dvd !dvd_lcm_left (dvd.trans !dvd_lcm_left !dvd_lcm_right)) (dvd.trans !dvd_lcm_right !dvd_lcm_right)) (lcm_dvd (dvd.trans !dvd_lcm_left !dvd_lcm_left) (lcm_dvd (dvd.trans !dvd_lcm_right !dvd_lcm_left) !dvd_lcm_right)) /- coprime -/ abbreviation coprime (a b : ℤ) : Prop := gcd a b = 1 theorem coprime_swap {a b : ℤ} (H : coprime b a) : coprime a b := !gcd.comm ▸ H theorem dvd_of_coprime_of_dvd_mul_right {a b c : ℤ} (H1 : coprime c b) (H2 : c ∣ a * b) : c ∣ a := assert H3 : gcd (a * c) (a * b) = abs a, from calc gcd (a * c) (a * b) = abs a * gcd c b : gcd_mul_left ... = abs a * 1 : H1 ... = abs a : mul_one, assert H4 : (c ∣ gcd (a * c) (a * b)), from dvd_gcd !dvd_mul_left H2, by rewrite [-dvd_abs_iff, -H3]; apply H4 theorem dvd_of_coprime_of_dvd_mul_left {a b c : ℤ} (H1 : coprime c a) (H2 : c ∣ a * b) : c ∣ b := dvd_of_coprime_of_dvd_mul_right H1 (!mul.comm ▸ H2) theorem gcd_mul_left_cancel_of_coprime {c : ℤ} (a : ℤ) {b : ℤ} (H : coprime c b) : gcd (c * a) b = gcd a b := begin revert H, rewrite [↑coprime, ↑gcd, *of_nat_eq_of_nat, nat_abs_mul], apply nat.gcd_mul_left_cancel_of_coprime end theorem gcd_mul_right_cancel_of_coprime (a : ℤ) {c b : ℤ} (H : coprime c b) : gcd (a * c) b = gcd a b := !mul.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_left_cancel_of_coprime_right {c a : ℤ} (b : ℤ) (H : coprime c a) : gcd a (c * b) = gcd a b := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_right_cancel_of_coprime_right {c a : ℤ} (b : ℤ) (H : coprime c a) : gcd a (b * c) = gcd a b := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_right_cancel_of_coprime H theorem coprime_div_gcd_div_gcd {a b : ℤ} (H : gcd a b ≠ 0) : coprime (a div gcd a b) (b div gcd a b) := calc gcd (a div gcd a b) (b div gcd a b) = gcd a b div abs (gcd a b) : gcd_div !gcd_dvd_left !gcd_dvd_right ... = 1 : by rewrite [abs_of_nonneg !gcd_nonneg, div_self H] theorem exists_coprime {a b : ℤ} (H : gcd a b ≠ 0) : exists a' b', coprime a' b' ∧ a = a' * gcd a b ∧ b = b' * gcd a b := have H1 : a = (a div gcd a b) * gcd a b, from (div_mul_cancel !gcd_dvd_left)⁻¹, have H2 : b = (b div gcd a b) * gcd a b, from (div_mul_cancel !gcd_dvd_right)⁻¹, exists.intro _ (exists.intro _ (and.intro (coprime_div_gcd_div_gcd H) (and.intro H1 H2))) theorem coprime_mul {a b c : ℤ} (H1 : coprime a c) (H2 : coprime b c) : coprime (a * b) c := calc gcd (a * b) c = gcd b c : !gcd_mul_left_cancel_of_coprime H1 ... = 1 : H2 theorem coprime_mul_right {c a b : ℤ} (H1 : coprime c a) (H2 : coprime c b) : coprime c (a * b) := coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2)) theorem coprime_of_coprime_mul_left {c a b : ℤ} (H : coprime (c * a) b) : coprime a b := have H1 : (gcd a b ∣ gcd (c * a) b), from !gcd_dvd_gcd_mul_left, eq_one_of_dvd_one !gcd_nonneg (H ▸ H1) theorem coprime_of_coprime_mul_right {c a b : ℤ} (H : coprime (a * c) b) : coprime a b := coprime_of_coprime_mul_left (!mul.comm ▸ H) theorem coprime_of_coprime_mul_left_right {c a b : ℤ} (H : coprime a (c * b)) : coprime a b := coprime_swap (coprime_of_coprime_mul_left (coprime_swap H)) theorem coprime_of_coprime_mul_right_right {c a b : ℤ} (H : coprime a (b * c)) : coprime a b := coprime_of_coprime_mul_left_right (!mul.comm ▸ H) theorem exists_eq_prod_and_dvd_and_dvd {a b c} (H : c ∣ a * b) : ∃ a' b', c = a' * b' ∧ a' ∣ a ∧ b' ∣ b := decidable.by_cases (assume H1 : gcd c a = 0, have H2 : c = 0, from eq_zero_of_gcd_eq_zero_left H1, have H3 : a = 0, from eq_zero_of_gcd_eq_zero_right H1, have H4 : c = 0 * b, from H2 ⬝ !zero_mul⁻¹, have H5 : 0 ∣ a, from H3⁻¹ ▸ !dvd.refl, have H6 : b ∣ b, from !dvd.refl, exists.intro _ (exists.intro _ (and.intro H4 (and.intro H5 H6)))) (assume H1 : gcd c a ≠ 0, have H2 : gcd c a ∣ c, from !gcd_dvd_left, have H3 : c div gcd c a ∣ (a * b) div gcd c a, from div_dvd_div H2 H, have H4 : (a * b) div gcd c a = (a div gcd c a) * b, from calc a * b div gcd c a = b * a div gcd c a : mul.comm ... = b * (a div gcd c a) : !mul_div_assoc !gcd_dvd_right ... = a div gcd c a * b : mul.comm, have H5 : c div gcd c a ∣ (a div gcd c a) * b, from H4 ▸ H3, have H6 : coprime (c div gcd c a) (a div gcd c a), from coprime_div_gcd_div_gcd H1, have H7 : c div gcd c a ∣ b, from dvd_of_coprime_of_dvd_mul_left H6 H5, have H8 : c = gcd c a * (c div gcd c a), from (mul_div_cancel' H2)⁻¹, exists.intro _ (exists.intro _ (and.intro H8 (and.intro !gcd_dvd_right H7)))) end int
fd4af4cf891d9b96012f5b69a8532de9f201c464
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/tactic.lean
aacd5bb99bcf70ede3c1b662bd2042abb5da7a1b
[ "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
40,089
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { interaction_monad.monad with failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _ } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨has_map.map to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := take state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : tactic α) : tactic α := λ s, timeit desc (t s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. -/ meta constant whnf (e : expr) (md := semireducible) : tactic expr /- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /- zeta reduction -/ meta constant zeta : expr → tactic expr /- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals. If `report_errors` is ff, then errors are reported using position information from q. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) : tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/ meta constant assert_core : name → expr → tactic unit /- (assertv_core H T P), change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/ meta constant define_core : name → expr → tactic unit /- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /-- Configuration options for the `apply` tactic. -/ structure apply_cfg := (md := semireducible) (approx := tt) (all := ff) (use_instances := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If cfg.approx is `tt`, then fallback to first-order unification, and approximate context during unification. If cfg.all is `tt`, then all unassigned meta-variables are added as new goals. If cfg.use_instances is `tt`, then use type class resolution to instantiate unassigned meta-variables. It returns a list of all introduced meta variables, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr))) /- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool open list nat meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (step t s)).clamp_pos line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : tactic unit := assert_core h t >> swap >> intro h >> swap /- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic unit := assertv_core h t v >> intro h >> return () /- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : tactic unit := define_core h t >> swap >> intro h >> swap /- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic unit := definev_core h t v >> intro h >> return () /- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic unit := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic unit := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ rs ++ gs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply (e : expr) : tactic unit := apply_core e >> return () meta def fapply (e : expr) : tactic unit := apply_core e {all := tt} >> return () /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) : tactic unit := mk_const c >>= apply meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", match H with | some n := intro n | none := intro1 end meta def by_cases (e : expr) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), em ← mk_app `decidable.em [e, inst], destruct em private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit := if e.is_local_constant then cases_core e ids md >> return () else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, (step (cases_core h ids md); intron n) meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ to_string i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_cmd do let l := level.param `l, let Ty : pexpr := expr.sort l, type ← to_expr ``(Π (α : %%Ty), α → α), val ← to_expr ``(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a := rfl /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def unsafe_monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined}
7167b88451b39f28f05659b4977365e1ac4f147a
63abd62053d479eae5abf4951554e1064a4c45b4
/src/testing/slim_check/sampleable.lean
925e622fe5c6628ef24bbdffdb778ba57e99a529
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
31,317
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import data.lazy_list.basic import data.tree import data.int.basic import control.bifunctor import tactic.linarith import testing.slim_check.gen /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v w namespace slim_check variables (α : Type u) local infix ` ≺ `:50 := has_well_founded.r /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ @[reducible] def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x } /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable := [wf : has_sizeof α] (sample [] : gen α) (shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil) attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof attribute [instance, priority 200] sampleable.wf /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [functor F] := [wf : Π α [has_sizeof α], has_sizeof (F α)] (sample [] : ∀ {α}, gen α → gen (F α)) (shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α)) (p_repr : ∀ α, has_repr α → has_repr (F α)) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] := [wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)] (sample [] : ∀ {α β}, gen α → gen β → gen (F α β)) (shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β)) (p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β)) export sampleable (sample shrink) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ meta def sampleable.mk_trivial_interp : tactic unit := tactic.refine ``(id) /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) := (proxy_repr : Type v) [wf : has_sizeof proxy_repr] (interp [] : proxy_repr → α . sampleable.mk_trivial_interp) [p_repr : has_repr proxy_repr] (sample [] : gen proxy_repr) (shrink : shrink_fn proxy_repr) attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf open nat lazy_list section prio open sampleable_ext set_option default_priority 50 instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α := { proxy_repr := α, sample := sampleable.sample α, shrink := shrink } instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := { wf := _, sample := sampleable_functor.sample F (sampleable.sample α), shrink := sampleable_functor.shrink α sampleable.shrink } instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := { wf := _, sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β), shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink } set_option default_priority 100 instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := { wf := _, proxy_repr := F (proxy_repr α), interp := functor.map (interp _), sample := sampleable_functor.sample F (sampleable_ext.sample α), shrink := sampleable_functor.shrink _ sampleable_ext.shrink, p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr } instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := { wf := _, proxy_repr := F (proxy_repr α) (proxy_repr β), interp := bifunctor.bimap (interp _) (interp _), sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β), shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink, p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr } end prio /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k → list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k } | n hn ls := if h : n ≤ 1 then ls.reverse else have h₂ : 0 < n, by linarith, have 1 * n / 2 < n, from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂), have n / 2 < n, by simpa, let m := n / 2 in have h₀ : m ≤ k, from le_trans (le_of_lt this) hn, have h₃ : 0 < m, by simp only [m, lt_iff_add_one_le, zero_add]; rw [le_div_iff_mul_le]; linarith, have h₁ : k - m < k, from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃, nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls) /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } := if h : n > 0 then have ∀ k, 1 < k → n / k < n, from λ k hk, nat.div_lt_of_lt_mul (suffices 1 * n < k * n, by simpa, nat.mul_lt_mul_of_pos_right hk h), ⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n (le_refl _) [] else [] open gen /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := { wf := ⟨ sizeof ∘ g ⟩, sample := f <$> sample α, shrink := λ x, have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x), by introv h'; solve_by_elim [lt_of_le_of_lt], subtype.map f this <$> shrink (g x) } instance nat.sampleable : sampleable ℕ := { sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))), (3, coe <$> choose_any (fin $ succ sz))] dec_trivial, shrink := λ x, lazy_list.of_list $ nat.shrink x } /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → option α := well_founded.fix has_well_founded.wf $ λ x f_rec, do trace sformat!"{x} : {(shrink x).to_list}" $ pure (), y ← (shrink x).find (λ a, p a), f_rec y y.property <|> some y.val . instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val $ λ i, (mod_le _ _ : i % n ≤ i) @[priority 100] instance fin.sampleable' {n} : sampleable (fin (succ n)) := sampleable.lift ℕ fin.of_nat subtype.val $ λ i, (mod_le _ _ : i % succ n ≤ i) instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a, by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, nat.sub_zero, succ_sub_succ_eq_sub] /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩ local attribute [instance, priority 2000] int.has_sizeof instance int.sampleable : sampleable ℤ := { wf := _, sample := sized $ λ sz, freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)), (3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))] dec_trivial, shrink := λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $ λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] } instance bool.sampleable : sampleable bool := { wf := ⟨ λ b, if b then 1 else 0 ⟩, sample := do { x ← choose_any bool, return x }, shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩ else lazy_list.nil } /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α β} [has_sizeof α] [has_sizeof β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) | ⟨x₀,x₁⟩ := let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_a x₀).map $ subtype.map (λ a, (a, x₁)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h), xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_b x₁).map $ subtype.map (λ a, (x₀, a)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in xs₀.append xs₁ instance prod.sampleable : sampleable_bifunctor.{u v} prod := { wf := _, sample := λ α β sama samb, do { ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)), ⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)), pure (x,y) }, shrink := @prod.shrink, p_repr := @prod.has_repr } instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) := sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_refl _ /-- shrinking function for sum types -/ def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) | (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim | (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim instance sum.sampleable : sampleable_bifunctor.{u v} sum := { wf := _, sample := λ (α : Type u) (β : Type v) sam_α sam_β, (@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|> @uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β), shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β, p_repr := @sum.has_repr } instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $ begin intro i, rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf; dsimp [rat.mk_pnat], mono*, { rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs], apply int.abs_div_le_abs }, { change _ - 1 ≤ y-1, apply nat.sub_le_sub_right, apply nat.div_le_of_le_mul, suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa }, apply nat.mul_le_mul_right, apply gcd_pos_of_pos_right _ hy } end /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : nat) (characters : string) : sampleable char := { sample := do { x ← choose_nat 0 length dec_trivial, if x.val = 0 then do n ← sample ℕ, pure $ char.of_nat n else do i ← choose_nat 0 (characters.length - 1) dec_trivial, pure (characters.mk_iterator.nextn i).curr }, shrink := λ _, lazy_list.nil } instance char.sampleable : sampleable char := sampleable_char 3 " 0123abcABC:,;`\\/" variables {α} section list_shrink variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x }) lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k} (hk : 0 < k) (hk' : k < xs.length) : sizeof (list.drop k xs) < sizeof xs := begin induction xs with x xs generalizing k, { cases hk' }, cases k, { cases hk }, have : sizeof xs < sizeof (x :: xs), { unfold_wf, linarith }, cases k, { simp only [this, list.drop] }, { simp only [list.drop], transitivity, { solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] }, { assumption } } end lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := by unfold_wf; assumption lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := by unfold_wf; assumption lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := begin induction xs, { apply h }, { unfold_wf, simp only [list.sizeof, add_lt_add_iff_left], exact xs_ih } end lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs := by cases xs; unfold_wf; [refl, linarith] /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n, n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs } | xs n hn := if hkn : k > n then lazy_list.nil else if hkn' : k = n then have 1 < xs.sizeof, by { subst_vars, cases xs, { contradiction }, unfold_wf, apply lt_of_lt_of_le, show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith }, { mono, apply list.one_le_sizeof, } }, lazy_list.singleton ⟨[], this ⟩ else have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn', match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with | ⟨xs₁,xs₂⟩, h := have h₄ : xs₁ = xs.take k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have h₃ : xs₂ = xs.drop k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have sizeof xs₂ < sizeof xs, by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length], have h₁ : n - k = xs₂.length, by simp only [h₃, ←hn, list.length_drop], have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs, by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄]; solve_by_elim [list.sizeof_append_lt_left], lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁ end /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one : shrink_fn (list α) | [] := lazy_list.nil | (x :: xs) := lazy_list.append (subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x) (subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs) /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with (xs : list α) : lazy_list { ys : list α // sizeof_lt ys xs } := let n := xs.length in lazy_list.append ((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k, if hk : 0 < k then list.shrink_removes k hk xs n rfl else lazy_list.nil )) (list.shrink_one shr _) end list_shrink instance list.sampleable : sampleable_functor list.{u} := { wf := _, sample := λ α sam_α, list_of sam_α, shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α, p_repr := @list.has_repr } instance prop.sampleable_ext : sampleable_ext Prop := { proxy_repr := bool, interp := coe, sample := choose_any bool, shrink := λ _, lazy_list.nil } /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type*) := α instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) := ⟨ (default α : α) ⟩ /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α} (x : no_shrink α) : α := x instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) := { sample := no_shrink.mk <$> sample α } instance string.sampleable : sampleable string := { sample := do { x ← list_of (sample char), pure x.as_string }, .. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_refl _ } /-- implementation of `sampleable (tree α)` -/ def tree.sample (sample : gen α) : ℕ → gen (tree α) | n := if h : n > 0 then have n / 2 < n, from div_lt_self h (by norm_num), tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2) else pure tree.nil /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type*} [has_sizeof α] (t : α) (sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) : shrink_fn { t' : α // sizeof_lt t' t } | ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' }, ⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht' lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t := by cases t; unfold_wf; linarith instance : functor tree := { map := @tree.map } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) : shrink_fn α := well_founded.fix (sizeof_measure_wf _) $ λ t f_rec, lazy_list.join (lazy_list.of_list $ shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _) lemma rec_shrink_with_eq [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) := begin conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], }, congr, ext ⟨y, h⟩, refl end /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with $ λ t, match t with | tree.nil := λ f_rec, [] | (tree.node x t₀ t₁) := λ f_rec, have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁), by clear _match; have := tree.one_le_sizeof t₀; dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *; unfold_wf; linarith, have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, [lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩], (prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map $ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁, by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩] end instance sampleable_tree : sampleable_functor tree := { wf := _, sample := λ α sam_α, sized $ tree.sample sam_α, shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α, p_repr := @tree.has_repr } /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type*) := α /-- Add the `small` type tag -/ def small.mk {α} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type*) := α /-- Add the `large` type tag -/ def large.mk {α} (x : α) : large α := x instance small.functor : functor small := id.monad.to_functor instance large.functor : functor large := id.monad.to_functor instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default α : α) ⟩ instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default α : α) ⟩ instance small.sampleable_functor : sampleable_functor small := { wf := _, sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance large.sampleable_functor : sampleable_functor large := { wf := _, sample := λ α samp, gen.resize (λ n, n * 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance ulift.sampleable_functor : sampleable_functor ulift.{u v} := { wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩, sample := λ α samp, uliftable.up_map ulift.up $ samp, shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)), p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ } /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } := { sample := do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial, pure ⟨x, h.2⟩}, shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $ λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x } instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y, by norm_num⟩ }, shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) }, subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, nat.add_lt_of_lt_sub_left h'⟩) <$> shrink (y - x) } -- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y+1, by linarith⟩ }, shrink := λ x, shrink _ } /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { x : α // x ≤ y } := { sample := do { x ← sample α, pure ⟨y - abs x, sub_le_self _ (abs_nonneg _) ⟩ }, shrink := λ _, lazy_list.nil } instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { y : α // x ≤ y } := { sample := do { y ← sample α, pure ⟨x + abs y, by norm_num [abs_nonneg]⟩ }, shrink := λ _, lazy_list.nil } /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs) (λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring) instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs) (λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring) instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $ by linarith [int.coe_nat_nonneg n]⟩) (λ ⟨i, h⟩, (y - i - 1).nat_abs) (λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring) instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs) (λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring) /-! ### Subtypes of any `list` -/ instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } := { sample := permutation_of xs, shrink := λ _, lazy_list.nil } instance perm'.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm ys xs } := { sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs, shrink := λ _, lazy_list.nil } setup_tactic_parser open tactic /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do xs ← io.run_rand $ uliftable.down $ do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up, pure ⟨xs.map repr⟩ }, xs.mmap' io.put_str_ln /-- Create a `gen α` expression from the argument of `#sample` -/ meta def mk_generator (e : expr) : tactic (expr × expr) := do t ← infer_type e, match t with | `(gen %%t) := do repr_inst ← mk_app ``has_repr [t] >>= mk_instance, pure (repr_inst, e) | _ := do samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance, repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst], gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst], pure (repr_inst, gen) end /-- `#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random values of type `my_type` of using an increasing size parameter. ```lean #sample nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample list int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ @[user_command] meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit := do e ← texpr, of_tactic $ do e ← i_to_expr e, (repr_inst, gen) ← mk_generator e, print_samples ← mk_mapp ``print_samples [none, repr_inst, gen], sample ← eval_expr (io unit) print_samples, unsafe_run_io sample end slim_check
c8a296fde366085507cafd332f0cbcc395f6d0dc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/continuous_map_auto.lean
29aa5b7573a0f2fd2a0d5b406db98942f7192235
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,922
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.subset_properties import Mathlib.topology.tactic import Mathlib.PostPort universes u_1 u_2 l u_3 namespace Mathlib /-! # Continuous bundled map In this file we define the type `continuous_map` of continuous bundled maps. -/ /-- Bundled continuous maps. -/ structure continuous_map (α : Type u_1) (β : Type u_2) [topological_space α] [topological_space β] where to_fun : α → β continuous_to_fun : autoParam (continuous to_fun) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "continuity'") []) namespace continuous_map protected instance has_coe_to_fun {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] : has_coe_to_fun (continuous_map α β) := has_coe_to_fun.mk (fun (x : continuous_map α β) => α → β) continuous_map.to_fun protected theorem continuous {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : continuous_map α β) : continuous ⇑f := continuous_map.continuous_to_fun f theorem coe_continuous {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : continuous_map α β} : continuous ⇑f := continuous_map.continuous_to_fun f theorem ext {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : continuous_map α β} {g : continuous_map α β} (H : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g := sorry protected instance inhabited {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Inhabited β] : Inhabited (continuous_map α β) := { default := mk fun (_x : α) => Inhabited.default } theorem coe_inj {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : continuous_map α β} {g : continuous_map α β} (h : ⇑f = ⇑g) : f = g := sorry /-- The identity as a continuous map. -/ def id {α : Type u_1} [topological_space α] : continuous_map α α := mk id /-- The composition of continuous maps, as a continuous map. -/ def comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (f : continuous_map β γ) (g : continuous_map α β) : continuous_map α γ := mk (⇑f ∘ ⇑g) /-- Constant map as a continuous map -/ def const {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (b : β) : continuous_map α β := mk fun (x : α) => b end Mathlib
1943fb60d46c9d33109c285d9937c993585bb845
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/tactic1.lean
df08958608f7e01e045aec8eb3f62b00866be18f
[ "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
832
lean
new_frontend theorem ex1 (x : Nat) (y : { v // v > x }) (z : Nat) : Nat := by { clear y x; exact z } theorem ex2 (x : Nat) (y : { v // v > x }) (z : Nat) : Nat := by { clear x y; exact z } theorem ex3 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by { have y = z from h₂.symm; apply Eq.trans; exact h₁; assumption } theorem ex4 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by { let h₃ : y = z := h₂.symm; apply Eq.trans; exact h₁; exact h₃ } theorem ex5 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by { let! h₃ : y = z := h₂.symm; apply Eq.trans; exact h₁; exact h₃ } theorem ex6 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : id (x + 0 = z) := by { show x = z; let! h₃ : y = z := h₂.symm; apply Eq.trans; exact h₁; exact h₃ }
1f5fbd663218a46337badf35bf693988cbe3514d
7a097aab717143b13a4a4f8824fe9cfe670a7883
/src/smt2/tactic.lean
4488c7b1d07aaa25497e41f4decfe89018333631
[ "Apache-2.0" ]
permissive
digama0/smt2_interface
6b3bbc12cb90bd4bc70b07ca86918c1e9ff4ed97
cf516ae4142f33adcf4b272758d63fee37ec9f7d
refs/heads/master
1,611,266,770,453
1,498,177,713,000
1,498,177,713,000
95,167,865
0
0
null
1,498,177,813,000
1,498,177,813,000
null
UTF-8
Lean
false
false
1,252
lean
import system.io import .builder import .syntax import .solvers.z3 inductive smt2.response | sat | unsat | unknown | other : string → smt2.response meta def parse_smt2_result (str : string) : smt2.response := if str = "sat\n" then smt2.response.sat else if str = "unsat\n" then smt2.response.unsat else if str = "unknown\n" then smt2.response.unknown else smt2.response.other str meta def cmds_to_string (cmds : list smt2.cmd) : string := to_string $ format.join $ list.intersperse "\n" $ list.map (λ c, to_fmt c) cmds.reverse meta def smt2 [io.interface] (build : smt2.builder unit) (log_query : option string := none) : io smt2.response := do z3 ← z3_instance.start, -- maybe we should have a primitive to go from fmt to char buffer let ((exc : except string unit), cmds) := build.run, match (exc : except string unit) with | (except.error e) := io.fail $ "builder failed with: " ++ e -- TODO: better message | (except.ok v) := do let query := cmds_to_string cmds, match log_query with | none := return () | some fn := do file ← io.mk_file_handle fn io.mode.write, io.fs.write file (query.to_list.to_buffer) end, res ← z3.raw query, return $ parse_smt2_result res end
362addf31ee76929d3275ea3ab889abee23e0fa1
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/free_ring.lean
873a54b977e013e314534d91c50e8f8b6caa5ced
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,912
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import group_theory.free_abelian_group universes u v def free_ring (α : Type u) : Type u := free_abelian_group $ free_monoid α namespace free_ring variables (α : Type u) instance : ring (free_ring α) := free_abelian_group.ring _ instance : inhabited (free_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_ring α := free_abelian_group.of [x] @[elab_as_eliminator] protected lemma induction_on {C : free_ring α → Prop} (z : free_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_ring α) ▸ ha _ _ hn1 h1) (λ m, list.rec_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [ring β] (f : α → β) def lift : free_ring α → β := free_abelian_group.lift $ λ L, (list.map f L).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ one_mul _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros L2, conv_lhs { dsimp only [free_abelian_group.mul_def] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros L1, iterate 3 { rw free_abelian_group.lift.of }, show list.prod (list.map f (_ ++ _)) = _, rw [list.map_append, list.prod_append] }, { intros L1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros L2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end instance : is_ring_hom (lift f) := { map_one := lift_one f, map_mul := lift_mul f, map_add := lift_add f } @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := is_semiring_hom.map_pow _ x n @[simp] lemma lift_comp_of (f : free_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) def map : free_ring α → free_ring β := lift $ of ∘ f @[simp] lemma map_zero : map f 0 = 0 := rfl @[simp] lemma map_one : map f 1 = 1 := rfl @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ @[simp] lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ @[simp] lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ @[simp] lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ @[simp] lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ @[simp] lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ end free_ring
2e298517919abcec3a34d1637543f6c377da9150
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/module.lean
8113066233ff9134c7e29a180378627fd7ed77a1
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
2,775
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad Modules and vector spaces over a ring. (We use "left_module," which is more precise, because "module" is a keyword.) -/ import algebra.field structure has_scalar [class] (F V : Type) := (smul : F → V → V) infixl ` • `:73 := has_scalar.smul /- modules over a ring -/ structure left_module [class] (R M : Type) [ringR : ring R] extends has_scalar R M, add_comm_group M := (smul_left_distrib : ∀ (r : R) (x y : M), smul r (add x y) = (add (smul r x) (smul r y))) (smul_right_distrib : ∀ (r s : R) (x : M), smul (ring.add r s) x = (add (smul r x) (smul s x))) (mul_smul : ∀ r s x, smul (mul r s) x = smul r (smul s x)) (one_smul : ∀ x, smul one x = x) section left_module variables {R M : Type} variable [ringR : ring R] variable [moduleRM : left_module R M] include ringR moduleRM -- Note: the anonymous include does not work in the propositions below. proposition smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := left_module.smul_left_distrib ringR a u v proposition smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := left_module.smul_right_distrib ringR a b u proposition mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := left_module.mul_smul ringR a b u proposition one_smul (u : M) : (1 : R) • u = u := left_module.one_smul ringR u proposition zero_smul (u : M) : (0 : R) • u = 0 := sorry /- have (0 : R) • u + 0 • u = 0 • u + 0, by rewrite [-smul_right_distrib, *add_zero], !add.left_cancel this -/ proposition smul_zero (a : R) : a • (0 : M) = 0 := sorry /- have a • (0:M) + a • 0 = a • 0 + 0, by rewrite [-smul_left_distrib, *add_zero], !add.left_cancel this -/ proposition neg_smul (a : R) (u : M) : (-a) • u = - (a • u) := sorry -- eq_neg_of_add_eq_zero (by rewrite [-smul_right_distrib, add.left_inv, zero_smul]) proposition neg_one_smul (u : M) : -(1 : R) • u = -u := sorry -- by rewrite [neg_smul, one_smul] proposition smul_neg (a : R) (u : M) : a • (-u) = -(a • u) := sorry -- by rewrite [-neg_one_smul, -mul_smul, mul_neg_one_eq_neg, neg_smul] proposition smul_sub_left_distrib (a : R) (u v : M) : a • (u - v) = a • u - a • v := sorry -- by rewrite [sub_eq_add_neg, smul_left_distrib, smul_neg] proposition sub_smul_right_distrib (a b : R) (v : M) : (a - b) • v = a • v - b • v := sorry -- by rewrite [sub_eq_add_neg, smul_right_distrib, neg_smul] end left_module /- vector spaces -/ structure vector_space [class] (F V : Type) [fieldF : field F] extends left_module F V
43c0dfa4769fd5190deb517ed4ab6eae688f0841
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/norm.lean
1ca1325c694eab8773f0c1db0671e3f4ade9c2c5
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,638
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.primitive_element import linear_algebra.matrix.charpoly.coeff import linear_algebra.determinant import ring_theory.power_basis /-! # Norm for (finite) ring extensions Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`, the determinant of the linear map given by multiplying by `s` gives information about the roots of the minimal polynomial of `s` over `R`. ## Implementation notes Typically, the norm is defined specifically for finite field extensions. The current definition is as general as possible and the assumption that we have fields or that the extension is finite is added to the lemmas as needed. We only define the norm for left multiplication (`algebra.left_mul_matrix`, i.e. `algebra.lmul_left`). For now, the definitions assume `S` is commutative, so the choice doesn't matter anyway. See also `algebra.trace`, which is defined similarly as the trace of `algebra.left_mul_matrix`. ## References * https://en.wikipedia.org/wiki/Field_norm -/ universes u v w variables {R S T : Type*} [comm_ring R] [is_domain R] [comm_ring S] variables [algebra R S] variables {K L F : Type*} [field K] [field L] [field F] variables [algebra K L] [algebra L F] [algebra K F] variables {ι : Type w} [fintype ι] open finite_dimensional open linear_map open matrix open_locale big_operators open_locale matrix namespace algebra variables (R) /-- The norm of an element `s` of an `R`-algebra is the determinant of `(*) s`. -/ noncomputable def norm : S →* R := linear_map.det.comp (lmul R S).to_ring_hom.to_monoid_hom lemma norm_apply (x : S) : norm R x = linear_map.det (lmul R S x) := rfl lemma norm_eq_one_of_not_exists_basis (h : ¬ ∃ (s : finset S), nonempty (basis s R S)) (x : S) : norm R x = 1 := by { rw [norm_apply, linear_map.det], split_ifs with h, refl } variables {R} -- Can't be a `simp` lemma because it depends on a choice of basis lemma norm_eq_matrix_det [decidable_eq ι] (b : basis ι R S) (s : S) : norm R s = matrix.det (algebra.left_mul_matrix b s) := by rw [norm_apply, ← linear_map.det_to_matrix b, to_matrix_lmul_eq] /-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. -/ lemma norm_algebra_map_of_basis (b : basis ι R S) (x : R) : norm R (algebra_map R S x) = x ^ fintype.card ι := begin haveI := classical.dec_eq ι, rw [norm_apply, ← det_to_matrix b, lmul_algebra_map], convert @det_diagonal _ _ _ _ _ (λ (i : ι), x), { ext i j, rw [to_matrix_lsmul, matrix.diagonal] }, { rw [finset.prod_const, finset.card_univ] } end /-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. (If `L` is not finite-dimensional over `K`, then `norm = 1 = x ^ 0 = x ^ (finrank L K)`.) -/ @[simp] lemma norm_algebra_map (x : K) : norm K (algebra_map K L x) = x ^ finrank K L := begin by_cases H : ∃ (s : finset L), nonempty (basis s K L), { rw [norm_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] }, { rw [norm_eq_one_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis, pow_zero], rintros ⟨s, ⟨b⟩⟩, exact H ⟨s, ⟨b⟩⟩ }, end section eq_prod_roots lemma norm_gen_eq_prod_roots [algebra K S] (pb : power_basis K S) (hf : (minpoly K pb.gen).splits (algebra_map K F)) : algebra_map K F (norm K pb.gen) = ((minpoly K pb.gen).map (algebra_map K F)).roots.prod := begin -- Write the LHS as the 0'th coefficient of `minpoly K pb.gen` rw [norm_eq_matrix_det pb.basis, det_eq_sign_charpoly_coeff, charpoly_left_mul_matrix, ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one, ← polynomial.coeff_map, fintype.card_fin], -- Rewrite `minpoly K pb.gen` as a product over the roots. conv_lhs { rw polynomial.eq_prod_roots_of_splits hf }, rw [polynomial.coeff_C_mul, polynomial.coeff_zero_multiset_prod, multiset.map_map, (minpoly.monic pb.is_integral_gen).leading_coeff, ring_hom.map_one, one_mul], -- Incorporate the `-1` from the `charpoly` back into the product. rw [← multiset.prod_repeat (-1 : F), ← pb.nat_degree_minpoly, polynomial.nat_degree_eq_card_roots hf, ← multiset.map_const, ← multiset.prod_map_mul], -- And conclude that both sides are the same. congr, convert multiset.map_id _, ext f, simp end end eq_prod_roots section eq_zero_iff lemma norm_eq_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} : algebra.norm R x = 0 ↔ x = 0 := begin have hι : nonempty ι := b.index_nonempty, letI := classical.dec_eq ι, rw algebra.norm_eq_matrix_det b, split, { rw ← matrix.exists_mul_vec_eq_zero_iff, rintros ⟨v, v_ne, hv⟩, rw [← b.equiv_fun.apply_symm_apply v, b.equiv_fun_symm_apply, b.equiv_fun_apply, algebra.left_mul_matrix_mul_vec_repr] at hv, refine (mul_eq_zero.mp (b.ext_elem $ λ i, _)).resolve_right (show ∑ i, v i • b i ≠ 0, from _), { simpa only [linear_equiv.map_zero, pi.zero_apply] using congr_fun hv i }, { contrapose! v_ne with sum_eq, apply b.equiv_fun.symm.injective, rw [b.equiv_fun_symm_apply, sum_eq, linear_equiv.map_zero] } }, { rintro rfl, rw [alg_hom.map_zero, matrix.det_zero hι] }, end lemma norm_ne_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} : algebra.norm R x ≠ 0 ↔ x ≠ 0 := not_iff_not.mpr (algebra.norm_eq_zero_iff_of_basis b) /-- See also `algebra.norm_eq_zero_iff'` if you already have rewritten with `algebra.norm_apply`. -/ @[simp] lemma norm_eq_zero_iff [finite_dimensional K L] {x : L} : algebra.norm K x = 0 ↔ x = 0 := algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L) /-- This is `algebra.norm_eq_zero_iff` composed with `algebra.norm_apply`. -/ @[simp] lemma norm_eq_zero_iff' [finite_dimensional K L] {x : L} : linear_map.det (algebra.lmul K L x) = 0 ↔ x = 0 := algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L) end eq_zero_iff open intermediate_field variable (K) lemma norm_eq_norm_adjoin [finite_dimensional K L] [is_separable K L] (x : L) : norm K x = norm K (adjoin_simple.gen K x) ^ finrank K⟮x⟯ L := begin letI := is_separable_tower_top_of_is_separable K K⟮x⟯ L, let pbL := field.power_basis_of_finite_of_separable K⟮x⟯ L, let pbx := intermediate_field.adjoin.power_basis (is_separable.is_integral K x), rw [← adjoin_simple.algebra_map_gen K x, norm_eq_matrix_det (pbx.basis.smul pbL.basis) _, smul_left_mul_matrix_algebra_map, det_block_diagonal, norm_eq_matrix_det pbx.basis], simp only [finset.card_fin, finset.prod_const, adjoin.power_basis_basis], congr, rw [← power_basis.finrank, adjoin_simple.algebra_map_gen K x], end section eq_prod_embeddings variable {K} open intermediate_field intermediate_field.adjoin_simple polynomial variables (E : Type*) [field E] [algebra K E] [is_scalar_tower K L F] lemma norm_eq_prod_embeddings_gen (pb : power_basis K L) (hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) : algebra_map K E (norm K pb.gen) = (@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ, σ pb.gen) := begin letI := classical.dec_eq E, rw [norm_gen_eq_prod_roots pb hE, fintype.prod_equiv pb.lift_equiv', finset.prod_mem_multiset, finset.prod_eq_multiset_prod, multiset.to_finset_val, multiset.erase_dup_eq_self.mpr (nodup_roots ((separable_map _).mpr hfx)), multiset.map_id], { intro x, refl }, { intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] } end variable (F) lemma prod_embeddings_eq_finrank_pow [is_alg_closed E] [is_separable K F] [finite_dimensional K F] (pb : power_basis K L) : ∏ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) = ((@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ : L →ₐ[K] E, σ pb.gen)) ^ finrank L F := begin haveI : finite_dimensional L F := finite_dimensional.right K L F, haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F, letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb, letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) := _, rw [fintype.prod_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen), ← finset.univ_sigma_univ, finset.prod_sigma, ← finset.prod_pow], refine finset.prod_congr rfl (λ σ _, _), { letI : algebra L E := σ.to_ring_hom.to_algebra, simp only [finset.prod_const, finset.card_univ], congr, rw alg_hom.card L F E }, { intros σ, simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply, is_scalar_tower.coe_to_alg_hom'] } end variable (K) /-- For `L/K` a finite separable extension of fields and `E` an algebraically closed extension of `K`, the norm (down to `K`) of an element `x` of `L` is equal to the product of the images of `x` over all the `K`-embeddings `σ` of `L` into `E`. -/ lemma norm_eq_prod_embeddings [finite_dimensional K L] [is_separable K L] [is_alg_closed E] {x : L} : algebra_map K E (norm K x) = ∏ σ : L →ₐ[K] E, σ x := begin have hx := is_separable.is_integral K x, rw [norm_eq_norm_adjoin K x, ring_hom.map_pow, ← adjoin.power_basis_gen hx, norm_eq_prod_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _)], { exact (prod_embeddings_eq_finrank_pow L E (adjoin.power_basis hx)).symm }, { haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L, exact is_separable.separable K _ } end end eq_prod_embeddings end algebra
7bd102c760ccf362ec963306fffbdaf2f6d5f5d5
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/real/cau_seq.lean
fcc83b70119212d036383b6e20d4ed4ce89e0415
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
19,964
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro A basic theory of Cauchy sequences, used in the construction of the reals. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. -/ import data.rat algebra.ordered_field class is_absolute_value {α} [discrete_linear_ordered_field α] {β} [ring β] (f : β → α) : Prop := (abv_nonneg : ∀ x, 0 ≤ f x) (abv_eq_zero : ∀ {x}, f x = 0 ↔ x = 0) (abv_add : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 := (domain.mul_left_inj $ mt (abv_eq_zero abv).1 h).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_one {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] : abv 1 = 1 := abv_one' abv one_ne_zero theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : β) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] theorem abv_inv {β : Type*} [discrete_field β] (abv : β → α) [is_absolute_value abv] (a : β) : abv a⁻¹ = (abv a)⁻¹ := classical.by_cases (λ h : a = 0, by simp [h, abv_zero abv]) (λ h, (domain.mul_left_inj (mt (abv_eq_zero abv).1 h)).1 $ by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv]) theorem abv_div {β : Type*} [discrete_field β] (abv : β → α) [is_absolute_value abv] (a b : β) : abv (a / b) = abv a / abv b := by rw [division_def, abv_mul abv, abv_inv abv]; refl lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : β) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ end is_absolute_value instance abs_is_absolute_value {α} [discrete_linear_ordered_field α] : is_absolute_value (abs : α → α) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) (K₁0 : 0 < K₁) (K₂0 : 0 < K₂) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 := lt_of_lt_of_le K₁0 (le_max_left _ K₂), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_max_left _ K₂), replace hb₂ := lt_of_lt_of_le hb₂ (le_max_right K₁ _), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {β : Type*} [discrete_field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end def is_cau_seq {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] (f : ℕ → β) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} theorem cauchy₂ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq def cau_seq {α : Type*} [discrete_linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [discrete_linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq β abv) : ∀ {ε}, ε > 0 → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 theorem cauchy₂ (f : cau_seq β abv) {ε:α} : ε > 0 → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ theorem cauchy₃ (f : cau_seq β abv) {ε:α} : ε > 0 → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := (finset.range (i+1)).sum (λ j, abv (f j)), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0 F0 G0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..}; { intros, apply ext, simp [mul_add, mul_assoc, add_mul] } instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } theorem const_sub (x y : β) : const (x - y) = const x - const y := by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg] @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl def lim_zero (f : cau_seq β abv) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := add_lim_zero hf (neg_lim_zero hg) theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa using add_lim_zero fg gh⟩⟩ theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε:α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ end ring section discrete_field variables {β : Type*} [discrete_field β] {abv : β → α} [is_absolute_value abv] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ def inv (f) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ end discrete_field section abs local notation `const` := const abs def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := by simpa using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := by simpa using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_equiv {x y : α} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
4747988f40e4077b95c2760c835a0f67adc206ae
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/def5.lean
2ceb22b4eda6ca79f8c8cb1aafaae98f166b6bf3
[ "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
185
lean
def fib : Nat → Nat | 0 => 1 | 1 => 1 | n+2 => fib n + fib (n+1) example : fib 0 = 1 := rfl example : fib 1 = 1 := rfl example (n : Nat) : fib (n+2) = fib n + fib (n+1) := rfl
1d0e74c5bab866bbaff4504fec384b616182ea62
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/assert_tac1.lean
72ea4b82a5411a221df3f05ddf8cb94117b7dcc1
[ "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
490
lean
open tactic definition tst1 (a : nat) : a = a := by do define `x (expr.const `nat []), trace_state, a ← get_local `a, exact a, x ← get_local `x, mk_app `eq.refl [x] >>= exact print tst1 definition tst2 (a : nat) : a = a := by do define `x (expr.const `nat []), a ← get_local `a, exact a, trace "------------", trace_state, get_local `x >>= revert, intro `y, trace_state, y ← get_local `y, mk_app `eq.refl [y] >>= exact print tst2
1dd7196159f3156ebf3f5f9af73c621e61e3c6c0
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/theories/measure_theory/sigma_algebra.lean
79b3e4f8d3e465b08aa2ffa0ea7391b95987f38e
[ "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
9,343
lean
/- Copyright (c) 2016 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad Sigma algebras. -/ import data.set data.nat theories.topology.basic open eq.ops set nat structure sigma_algebra [class] (X : Type) := (sets : set (set X)) (univ_mem_sets : univ ∈ sets) (comp_mem_sets : ∀ {s : set X}, s ∈ sets → (-s ∈ sets)) (cUnion_mem_sets : ∀ {s : ℕ → set X}, (∀ i, s i ∈ sets) → (⋃ i, s i) ∈ sets) /- Closure properties -/ namespace measure_theory open sigma_algebra variables {X : Type} [sigma_algebra X] definition measurable (t : set X) : Prop := t ∈ sets X theorem measurable_univ : measurable (@univ X) := univ_mem_sets X theorem measurable_compl {s : set X} (H : measurable s) : measurable (-s) := comp_mem_sets H theorem measurable_of_measurable_compl {s : set X} (H : measurable (-s)) : measurable s := !compl_compl ▸ measurable_compl H theorem measurable_empty : measurable (∅ : set X) := compl_univ ▸ measurable_compl measurable_univ theorem measurable_cUnion {s : ℕ → set X} (H : ∀ i, measurable (s i)) : measurable (⋃ i, s i) := cUnion_mem_sets H theorem measurable_cInter {s : ℕ → set X} (H : ∀ i, measurable (s i)) : measurable (⋂ i, s i) := have ∀ i, measurable (-(s i)), from take i, measurable_compl (H i), have measurable (-(⋃ i, -(s i))), from measurable_compl (measurable_cUnion this), show measurable (⋂ i, s i), by rewrite Inter_eq_comp_Union_comp; apply this theorem measurable_union {s t : set X} (Hs : measurable s) (Ht : measurable t) : measurable (s ∪ t) := have ∀ i, measurable (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht, show measurable (s ∪ t), by rewrite -Union_bin_ext; exact measurable_cUnion this theorem measurable_inter {s t : set X} (Hs : measurable s) (Ht : measurable t) : measurable (s ∩ t) := have ∀ i, measurable (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht, show measurable (s ∩ t), by rewrite -Inter_bin_ext; exact measurable_cInter this theorem measurable_diff {s t : set X} (Hs : measurable s) (Ht : measurable t) : measurable (s \ t) := measurable_inter Hs (measurable_compl Ht) theorem measurable_insert {x : X} {s : set X} (Hx : measurable '{x}) (Hs : measurable s) : measurable (insert x s) := !insert_eq⁻¹ ▸ measurable_union Hx Hs end measure_theory /- -- Properties of sigma algebras -/ namespace sigma_algebra open measure_theory variable {X : Type} protected theorem eq {M N : sigma_algebra X} (H : @sets X M = @sets X N) : M = N := by cases M; cases N; cases H; apply rfl /- sigma algebra generated by a set -/ inductive sets_generated_by (G : set (set X)) : set X → Prop := | generators_mem : ∀ ⦃s : set X⦄, s ∈ G → sets_generated_by G s | univ_mem : sets_generated_by G univ | comp_mem : ∀ ⦃s : set X⦄, sets_generated_by G s → sets_generated_by G (-s) | cUnion_mem : ∀ ⦃s : ℕ → set X⦄, (∀ i, sets_generated_by G (s i)) → sets_generated_by G (⋃ i, s i) protected definition generated_by {X : Type} (G : set (set X)) : sigma_algebra X := ⦃sigma_algebra, sets := sets_generated_by G, univ_mem_sets := sets_generated_by.univ_mem G, comp_mem_sets := sets_generated_by.comp_mem , cUnion_mem_sets := sets_generated_by.cUnion_mem ⦄ theorem sets_generated_by_initial {G : set (set X)} {M : sigma_algebra X} (H : G ⊆ @sets _ M) : sets_generated_by G ⊆ @sets _ M := begin intro s Hs, induction Hs with s sG s Hs ssX s Hs sisX, {exact H sG}, {exact measurable_univ}, {exact measurable_compl ssX}, exact measurable_cUnion sisX end theorem measurable_generated_by {G : set (set X)} : ∀₀ s ∈ G, @measurable _ (sigma_algebra.generated_by G) s := λ s H, sets_generated_by.generators_mem H /- The collection of sigma algebras forms a complete lattice. -/ protected definition le (M N : sigma_algebra X) : Prop := @sets _ M ⊆ @sets _ N attribute [instance] definition sigma_algebra_has_le : has_le (sigma_algebra X) := has_le.mk sigma_algebra.le protected theorem le_refl (M : sigma_algebra X) : M ≤ M := subset.refl (@sets _ M) protected theorem le_trans (M N L : sigma_algebra X) : M ≤ N → N ≤ L → M ≤ L := assume H1, assume H2, subset.trans H1 H2 protected theorem le_antisymm (M N : sigma_algebra X) : M ≤ N → N ≤ M → M = N := assume H1, assume H2, sigma_algebra.eq (subset.antisymm H1 H2) protected theorem generated_by_initial {G : set (set X)} {M : sigma_algebra X} (H : G ⊆ @sets X M) : sigma_algebra.generated_by G ≤ M := sets_generated_by_initial H protected definition inf (M N : sigma_algebra X) : sigma_algebra X := ⦃sigma_algebra, sets := @sets X M ∩ @sets X N, univ_mem_sets := abstract and.intro (@measurable_univ X M) (@measurable_univ X N) end, comp_mem_sets := abstract take s, assume Hs, and.intro (@measurable_compl X M s (and.elim_left Hs)) (@measurable_compl X N s (and.elim_right Hs)) end, cUnion_mem_sets := abstract take s, assume Hs, and.intro (@measurable_cUnion X M s (λ i, and.elim_left (Hs i))) (@measurable_cUnion X N s (λ i, and.elim_right (Hs i))) end⦄ protected theorem inf_le_left (M N : sigma_algebra X) : sigma_algebra.inf M N ≤ M := λ s, !inter_subset_left protected theorem inf_le_right (M N : sigma_algebra X) : sigma_algebra.inf M N ≤ N := λ s, !inter_subset_right protected theorem le_inf (M N L : sigma_algebra X) (H1 : L ≤ M) (H2 : L ≤ N) : L ≤ sigma_algebra.inf M N := λ s H, and.intro (H1 s H) (H2 s H) protected definition Inf (MS : set (sigma_algebra X)) : sigma_algebra X := ⦃sigma_algebra, sets := ⋂ M ∈ MS, @sets _ M, univ_mem_sets := abstract take M, assume HM, @measurable_univ X M end, comp_mem_sets := abstract take s, assume Hs, take M, assume HM, measurable_compl (Hs M HM) end, cUnion_mem_sets := abstract take s, assume Hs, take M, assume HM, measurable_cUnion (λ i, Hs i M HM) end ⦄ protected theorem Inf_le {M : sigma_algebra X} {MS : set (sigma_algebra X)} (MMS : M ∈ MS) : sigma_algebra.Inf MS ≤ M := bInter_subset_of_mem MMS protected theorem le_Inf {M : sigma_algebra X} {MS : set (sigma_algebra X)} (H : ∀₀ N ∈ MS, M ≤ N) : M ≤ sigma_algebra.Inf MS := take s, assume Hs : s ∈ @sets _ M, take N, assume NMS : N ∈ MS, show s ∈ @sets _ N, from H NMS s Hs protected definition sup (M N : sigma_algebra X) : sigma_algebra X := sigma_algebra.generated_by (@sets _ M ∪ @sets _ N) protected theorem le_sup_left (M N : sigma_algebra X) : M ≤ sigma_algebra.sup M N := take s, assume Hs : s ∈ @sets _ M, measurable_generated_by (or.inl Hs) protected theorem le_sup_right (M N : sigma_algebra X) : N ≤ sigma_algebra.sup M N := take s, assume Hs : s ∈ @sets _ N, measurable_generated_by (or.inr Hs) protected theorem sup_le {M N L : sigma_algebra X} (H1 : M ≤ L) (H2 : N ≤ L) : sigma_algebra.sup M N ≤ L := have @sets _ M ∪ @sets _ N ⊆ @sets _ L, from union_subset H1 H2, sets_generated_by_initial this protected definition Sup (MS : set (sigma_algebra X)) : sigma_algebra X := sigma_algebra.generated_by (⋃ M ∈ MS, @sets _ M) protected theorem le_Sup {M : sigma_algebra X} {MS : set (sigma_algebra X)} (MMS : M ∈ MS) : M ≤ sigma_algebra.Sup MS := take s, assume Hs : s ∈ @sets _ M, measurable_generated_by (mem_bUnion MMS Hs) protected theorem Sup_le {N : sigma_algebra X} {MS : set (sigma_algebra X)} (H : ∀₀ M ∈ MS, M ≤ N) : sigma_algebra.Sup MS ≤ N := have (⋃ M ∈ MS, @sets _ M) ⊆ @sets _ N, from bUnion_subset H, sets_generated_by_initial this attribute [trans_instance] protected definition complete_lattice : complete_lattice (sigma_algebra X) := ⦃complete_lattice, le := sigma_algebra.le, le_refl := sigma_algebra.le_refl, le_trans := sigma_algebra.le_trans, le_antisymm := sigma_algebra.le_antisymm, inf := sigma_algebra.inf, sup := sigma_algebra.sup, inf_le_left := sigma_algebra.inf_le_left, inf_le_right := sigma_algebra.inf_le_right, le_inf := sigma_algebra.le_inf, le_sup_left := sigma_algebra.le_sup_left, le_sup_right := sigma_algebra.le_sup_right, sup_le := @sigma_algebra.sup_le X, Inf := sigma_algebra.Inf, Sup := sigma_algebra.Sup, Inf_le := @sigma_algebra.Inf_le X, le_Inf := @sigma_algebra.le_Inf X, le_Sup := @sigma_algebra.le_Sup X, Sup_le := @sigma_algebra.Sup_le X⦄ end sigma_algebra /- Borel sets -/ namespace measure_theory section open topology variables (X : Type) [topology X] definition borel_algebra : sigma_algebra X := sigma_algebra.generated_by (opens X) variable {X} definition borel (s : set X) : Prop := @measurable _ (borel_algebra X) s theorem borel_of_open {s : set X} (H : Open s) : borel s := sigma_algebra.measurable_generated_by H theorem borel_of_closed {s : set X} (H : closed s) : borel s := have borel (-s), from borel_of_open H, @measurable_of_measurable_compl _ (borel_algebra X) _ this end end measure_theory
2b42050e84f5720cfb6e2904d9f73bea498eb4e9
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/types/lift.hlean
123f976ee399593523ecbb244e8dd780839eb393
[ "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
6,133
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about lift -/ import ..function open eq equiv is_equiv is_trunc pointed namespace lift universe variables u v variables {A : Type.{u}} (z z' : lift.{u v} A) protected definition eta : up (down z) = z := by induction z; reflexivity protected definition code [unfold 2 3] : lift A → lift A → Type | code (up a) (up a') := a = a' protected definition decode [unfold 2 3] : Π(z z' : lift A), lift.code z z' → z = z' | decode (up a) (up a') := λc, ap up c variables {z z'} protected definition encode [unfold 3 4 5] (p : z = z') : lift.code z z' := by induction p; induction z; esimp variables (z z') definition lift_eq_equiv : (z = z') ≃ lift.code z z' := equiv.MK lift.encode !lift.decode abstract begin intro c, induction z with a, induction z' with a', esimp at *, induction c, reflexivity end end abstract begin intro p, induction p, induction z, reflexivity end end section variables {a a' : A} definition eq_of_up_eq_up [unfold 4] (p : up a = up a') : a = a' := lift.encode p definition lift_transport {P : A → Type} (p : a = a') (z : lift (P a)) : p ▸ z = up (p ▸ down z) := by induction p; induction z; reflexivity end variables {A' : Type} (f : A → A') (g : lift A → lift A') definition lift_functor [unfold 4] : lift A → lift A' | lift_functor (up a) := up (f a) definition is_equiv_lift_functor [constructor] [Hf : is_equiv f] : is_equiv (lift_functor f) := adjointify (lift_functor f) (lift_functor f⁻¹) abstract begin intro z', induction z' with a', esimp, exact ap up !right_inv end end abstract begin intro z, induction z with a, esimp, exact ap up !left_inv end end definition lift_equiv_lift_of_is_equiv [constructor] [Hf : is_equiv f] : lift A ≃ lift A' := equiv.mk _ (is_equiv_lift_functor f) definition lift_equiv_lift [constructor] (f : A ≃ A') : lift A ≃ lift A' := equiv.mk _ (is_equiv_lift_functor f) definition lift_equiv_lift_refl (A : Type) : lift_equiv_lift (erfl : A ≃ A) = erfl := by apply equiv_eq; intro z; induction z with a; reflexivity definition lift_inv_functor [unfold_full] (a : A) : A' := down (g (up a)) definition is_equiv_lift_inv_functor [constructor] [Hf : is_equiv g] : is_equiv (lift_inv_functor g) := adjointify (lift_inv_functor g) (lift_inv_functor g⁻¹) abstract begin intro z', rewrite [▸*,lift.eta,right_inv g], end end abstract begin intro z', rewrite [▸*,lift.eta,left_inv g], end end definition equiv_of_lift_equiv_lift [constructor] (g : lift A ≃ lift A') : A ≃ A' := equiv.mk _ (is_equiv_lift_inv_functor g) definition lift_functor_left_inv : lift_inv_functor (lift_functor f) = f := eq_of_homotopy (λa, idp) definition lift_functor_right_inv : lift_functor (lift_inv_functor g) = g := begin apply eq_of_homotopy, intro z, induction z with a, esimp, apply lift.eta end variables (A A') definition is_equiv_lift_functor_fn [constructor] : is_equiv (lift_functor : (A → A') → (lift A → lift A')) := adjointify lift_functor lift_inv_functor lift_functor_right_inv lift_functor_left_inv definition lift_imp_lift_equiv [constructor] : (lift A → lift A') ≃ (A → A') := (equiv.mk _ (is_equiv_lift_functor_fn A A'))⁻¹ᵉ -- can we deduce this from lift_imp_lift_equiv? definition lift_equiv_lift_equiv [constructor] : (lift A ≃ lift A') ≃ (A ≃ A') := equiv.MK equiv_of_lift_equiv_lift lift_equiv_lift abstract begin intro f, apply equiv_eq, reflexivity end end abstract begin intro g, apply equiv_eq', esimp, apply eq_of_homotopy, intro z, induction z with a, esimp, apply lift.eta end end definition lift_eq_lift_equiv.{u1 u2} (A A' : Type.{u1}) : (lift.{u1 u2} A = lift.{u1 u2} A') ≃ (A = A') := !eq_equiv_equiv ⬝e !lift_equiv_lift_equiv ⬝e !eq_equiv_equiv⁻¹ᵉ definition is_embedding_lift [instance] : is_embedding lift := begin intro A A', fapply is_equiv.homotopy_closed, exact to_inv !lift_eq_lift_equiv, exact _, { intro p, induction p, esimp [lift_eq_lift_equiv,equiv.trans,equiv.symm,eq_equiv_equiv], rewrite [equiv_of_eq_refl, lift_equiv_lift_refl], apply ua_refl} end definition plift [constructor] (A : pType.{u}) : pType.{max u v} := pointed.MK (lift A) (up pt) definition plift_functor [constructor] {A B : Type*} (f : A →* B) : plift A →* plift B := pmap.mk (lift_functor f) (ap up (respect_pt f)) -- is_trunc_lift is defined in init.trunc definition pup [constructor] {A : Type*} : A →* plift A := pmap.mk up idp definition pdown [constructor] {A : Type*} : plift A →* A := pmap.mk down idp definition plift_functor_phomotopy [constructor] {A B : Type*} (f : A →* B) : pdown ∘* plift_functor f ∘* pup ~* f := begin fapply phomotopy.mk, { reflexivity}, { esimp, refine !idp_con ⬝ _, refine _ ⬝ ap02 down !idp_con⁻¹, refine _ ⬝ !ap_compose, exact !ap_id⁻¹} end definition pequiv_plift [constructor] (A : Type*) : A ≃* plift A := pequiv_of_equiv (equiv_lift A) idp definition fiber_lift_functor {A B : Type} (f : A → B) (b : B) : fiber (lift_functor f) (up b) ≃ fiber f b := begin fapply equiv.MK: intro v; cases v with a p, { cases a with a, exact fiber.mk a (eq_of_fn_eq_fn' up p) }, { exact fiber.mk (up a) (ap up p) }, { apply ap (fiber.mk a), apply eq_of_fn_eq_fn'_ap }, { cases a with a, esimp, apply ap (fiber.mk (up a)), apply ap_eq_of_fn_eq_fn' } end end lift
9f9badd2eb11fb87a17fbe9dd7249bd9641e0fa0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/set_theory/game/impartial.lean
4a17f3df9d2ea3cb27bc0d00cf315c904124eb42
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,361
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import set_theory.game.winner import tactic.nth_rewrite.default import tactic.equiv_rw /-! # Basic definitions about impartial (pre-)games We will define an impartial game, one in which left and right can make exactly the same moves. Our definition differs slightly by saying that the game is always equivalent to its negative, no matter what moves are played. This allows for games such as poker-nim to be classifed as impartial. -/ universe u namespace pgame local infix ` ≈ ` := equiv /-- The definition for a impartial game, defined using Conway induction -/ def impartial_aux : pgame → Prop | G := G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ (∀ j, impartial_aux (G.move_right j)) using_well_founded { dec_tac := pgame_wf_tac } lemma impartial_aux_def {G : pgame} : G.impartial_aux ↔ G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ (∀ j, impartial_aux (G.move_right j)) := begin split, { intro hi, unfold1 impartial_aux at hi, exact hi }, { intro hi, unfold1 impartial_aux, exact hi } end /-- A typeclass on impartial games. -/ class impartial (G : pgame) : Prop := (out : impartial_aux G) lemma impartial_iff_aux {G : pgame} : G.impartial ↔ G.impartial_aux := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma impartial_def {G : pgame} : G.impartial ↔ G ≈ -G ∧ (∀ i, impartial (G.move_left i)) ∧ (∀ j, impartial (G.move_right j)) := by simpa only [impartial_iff_aux] using impartial_aux_def namespace impartial instance impartial_zero : impartial 0 := by { rw impartial_def, dsimp, simp } lemma neg_equiv_self (G : pgame) [h : G.impartial] : G ≈ -G := (impartial_def.1 h).1 instance move_left_impartial {G : pgame} [h : G.impartial] (i : G.left_moves) : (G.move_left i).impartial := (impartial_def.1 h).2.1 i instance move_right_impartial {G : pgame} [h : G.impartial] (j : G.right_moves) : (G.move_right j).impartial := (impartial_def.1 h).2.2 j instance impartial_add : ∀ (G H : pgame) [G.impartial] [H.impartial], (G + H).impartial | G H := begin introsI hG hH, rw impartial_def, split, { apply equiv_trans _ (neg_add_relabelling G H).equiv.symm, exact add_congr (neg_equiv_self _) (neg_equiv_self _) }, split, all_goals { intro i, equiv_rw pgame.left_moves_add G H at i <|> equiv_rw pgame.right_moves_add G H at i, cases i }, all_goals { simp only [add_move_left_inl, add_move_right_inl, add_move_left_inr, add_move_right_inr], exact impartial_add _ _ } end using_well_founded { dec_tac := pgame_wf_tac } instance impartial_neg : ∀ (G : pgame) [G.impartial], (-G).impartial | G := begin introI hG, rw impartial_def, split, { rw neg_neg, symmetry, exact neg_equiv_self G }, split, all_goals { intro i, equiv_rw G.left_moves_neg at i <|> equiv_rw G.right_moves_neg at i, simp only [move_left_left_moves_neg_symm, move_right_right_moves_neg_symm], exact impartial_neg _ } end using_well_founded { dec_tac := pgame_wf_tac } lemma winner_cases (G : pgame) [G.impartial] : G.first_loses ∨ G.first_wins := begin rcases G.winner_cases with hl | hr | hp | hn, { cases hl with hpos hnonneg, rw ←not_lt at hnonneg, have hneg := lt_of_lt_of_equiv hpos (neg_equiv_self G), rw [lt_iff_neg_gt, neg_neg, neg_zero] at hneg, contradiction }, { cases hr with hnonpos hneg, rw ←not_lt at hnonpos, have hpos := lt_of_equiv_of_lt (neg_equiv_self G).symm hneg, rw [lt_iff_neg_gt, neg_neg, neg_zero] at hpos, contradiction }, { left, assumption }, { right, assumption } end lemma not_first_wins (G : pgame) [G.impartial] : ¬G.first_wins ↔ G.first_loses := by cases winner_cases G; finish using [not_first_loses_of_first_wins] lemma not_first_loses (G : pgame) [G.impartial] : ¬G.first_loses ↔ G.first_wins := iff.symm $ iff_not_comm.1 $ iff.symm $ not_first_wins G lemma add_self (G : pgame) [G.impartial] : (G + G).first_loses := first_loses_is_zero.2 $ equiv_trans (add_congr (neg_equiv_self G) G.equiv_refl) add_left_neg_equiv lemma equiv_iff_sum_first_loses (G H : pgame) [G.impartial] [H.impartial] : G ≈ H ↔ (G + H).first_loses := begin split, { intro heq, exact first_loses_of_equiv (add_congr (equiv_refl _) heq) (add_self G) }, { intro hGHp, split, { rw le_iff_sub_nonneg, exact le_trans hGHp.2 (le_trans add_comm_le $ le_of_le_of_equiv (pgame.le_refl _) $ add_congr (equiv_refl _) (neg_equiv_self G)) }, { rw le_iff_sub_nonneg, exact le_trans hGHp.2 (le_of_le_of_equiv (pgame.le_refl _) $ add_congr (equiv_refl _) (neg_equiv_self H)) } } end lemma le_zero_iff {G : pgame} [G.impartial] : G ≤ 0 ↔ 0 ≤ G := by rw [le_zero_iff_zero_le_neg, le_congr (equiv_refl 0) (neg_equiv_self G)] lemma lt_zero_iff {G : pgame} [G.impartial] : G < 0 ↔ 0 < G := by rw [lt_iff_neg_gt, neg_zero, lt_congr (equiv_refl 0) (neg_equiv_self G)] lemma first_loses_symm (G : pgame) [G.impartial] : G.first_loses ↔ G ≤ 0 := ⟨and.left, λ h, ⟨h, le_zero_iff.1 h⟩⟩ lemma first_wins_symm (G : pgame) [G.impartial] : G.first_wins ↔ G < 0 := ⟨and.right, λ h, ⟨lt_zero_iff.1 h, h⟩⟩ lemma first_loses_symm' (G : pgame) [G.impartial] : G.first_loses ↔ 0 ≤ G := ⟨and.right, λ h, ⟨le_zero_iff.2 h, h⟩⟩ lemma first_wins_symm' (G : pgame) [G.impartial] : G.first_wins ↔ 0 < G := ⟨and.left, λ h, ⟨h, lt_zero_iff.2 h⟩⟩ lemma no_good_left_moves_iff_first_loses (G : pgame) [G.impartial] : (∀ (i : G.left_moves), (G.move_left i).first_wins) ↔ G.first_loses := begin split, { intro hbad, rw [first_loses_symm G, le_def_lt], split, { intro i, specialize hbad i, exact hbad.2 }, { intro j, exact pempty.elim j } }, { intros hp i, rw first_wins_symm, exact (le_def_lt.1 $ (first_loses_symm G).1 hp).1 i } end lemma no_good_right_moves_iff_first_loses (G : pgame) [G.impartial] : (∀ (j : G.right_moves), (G.move_right j).first_wins) ↔ G.first_loses := begin rw [first_loses_of_equiv_iff (neg_equiv_self G), ←no_good_left_moves_iff_first_loses], refine ⟨λ h i, _, λ h i, _⟩, { simpa [first_wins_of_equiv_iff (neg_equiv_self ((-G).move_left i))] using h (left_moves_neg _ i) }, { simpa [first_wins_of_equiv_iff (neg_equiv_self (G.move_right i))] using h ((left_moves_neg _).symm i) } end lemma good_left_move_iff_first_wins (G : pgame) [G.impartial] : (∃ (i : G.left_moves), (G.move_left i).first_loses) ↔ G.first_wins := begin refine ⟨λ ⟨i, hi⟩, (first_wins_symm' G).2 (lt_def_le.2 $ or.inl ⟨i, hi.2⟩), λ hn, _⟩, rw [first_wins_symm' G, lt_def_le] at hn, rcases hn with ⟨i, hi⟩ | ⟨j, _⟩, { exact ⟨i, (first_loses_symm' _).2 hi⟩ }, { exact pempty.elim j } end lemma good_right_move_iff_first_wins (G : pgame) [G.impartial] : (∃ j : G.right_moves, (G.move_right j).first_loses) ↔ G.first_wins := begin refine ⟨λ ⟨j, hj⟩, (first_wins_symm G).2 (lt_def_le.2 $ or.inr ⟨j, hj.1⟩), λ hn, _⟩, rw [first_wins_symm G, lt_def_le] at hn, rcases hn with ⟨i, _⟩ | ⟨j, hj⟩, { exact pempty.elim i }, { exact ⟨j, (first_loses_symm _).2 hj⟩ } end end impartial end pgame
46b62d0d108f788783d84f6a6c268eefca869029
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/lex.lean
48933ca201879fedce44af9bc0b23feffb7053d8
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,671
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.finsupp.order import data.dfinsupp.lex import data.finsupp.to_dfinsupp /-! # Lexicographic order on finitely supported functions This file defines the lexicographic order on `finsupp`. -/ variables {α N : Type*} namespace finsupp section N_has_zero variables [has_zero N] /-- `finsupp.lex r s` is the lexicographic relation on `α →₀ N`, where `α` is ordered by `r`, and `N` is ordered by `s`. The type synonym `lex (α →₀ N)` has an order given by `finsupp.lex (<) (<)`. -/ protected def lex (r : α → α → Prop) (s : N → N → Prop) (x y : α →₀ N) : Prop := pi.lex r (λ _, s) x y lemma _root_.pi.lex_eq_finsupp_lex {r : α → α → Prop} {s : N → N → Prop} (a b : α →₀ N) : pi.lex r (λ _, s) (a : α → N) (b : α → N) = finsupp.lex r s a b := rfl lemma lex_def {r : α → α → Prop} {s : N → N → Prop} {a b : α →₀ N} : finsupp.lex r s a b ↔ ∃ j, (∀ d, r d j → a d = b d) ∧ s (a j) (b j) := iff.rfl lemma lex_eq_inv_image_dfinsupp_lex (r : α → α → Prop) (s : N → N → Prop) : finsupp.lex r s = inv_image (dfinsupp.lex r $ λ a, s) to_dfinsupp := rfl instance [has_lt α] [has_lt N] : has_lt (lex (α →₀ N)) := ⟨λ f g, finsupp.lex (<) (<) (of_lex f) (of_lex g)⟩ lemma lex_lt_of_lt_of_preorder [preorder N] (r) [is_strict_order α r] {x y : α →₀ N} (hlt : x < y) : ∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i := dfinsupp.lex_lt_of_lt_of_preorder r (id hlt : x.to_dfinsupp < y.to_dfinsupp) lemma lex_lt_of_lt [partial_order N] (r) [is_strict_order α r] {x y : α →₀ N} (hlt : x < y) : pi.lex r (λ i, (<)) x y := dfinsupp.lex_lt_of_lt r (id hlt : x.to_dfinsupp < y.to_dfinsupp) instance lex.is_strict_order [linear_order α] [partial_order N] : is_strict_order (lex (α →₀ N)) (<) := let i : is_strict_order (lex (α → N)) (<) := pi.lex.is_strict_order in { irrefl := to_lex.surjective.forall.2 $ λ a, @irrefl _ _ i.to_is_irrefl a, trans := to_lex.surjective.forall₃.2 $ λ a b c, @trans _ _ i.to_is_trans a b c } variables [linear_order α] /-- The partial order on `finsupp`s obtained by the lexicographic ordering. See `finsupp.lex.linear_order` for a proof that this partial order is in fact linear. -/ instance lex.partial_order [partial_order N] : partial_order (lex (α →₀ N)) := partial_order.lift (λ x, to_lex ⇑(of_lex x)) finsupp.coe_fn_injective--fun_like.coe_injective /-- The linear order on `finsupp`s obtained by the lexicographic ordering. -/ instance lex.linear_order [linear_order N] : linear_order (lex (α →₀ N)) := { ..lex.partial_order, ..linear_order.lift' (to_lex ∘ to_dfinsupp ∘ of_lex) finsupp_equiv_dfinsupp.injective } variable [partial_order N] lemma to_lex_monotone : monotone (@to_lex (α →₀ N)) := λ a b h, dfinsupp.to_lex_monotone (id h : ∀ i, of_lex (to_dfinsupp a) i ≤ of_lex (to_dfinsupp b) i) lemma lt_of_forall_lt_of_lt (a b : lex (α →₀ N)) (i : α) : (∀ j < i, of_lex a j = of_lex b j) → of_lex a i < of_lex b i → a < b := λ h1 h2, ⟨i, h1, h2⟩ end N_has_zero section covariants variables [linear_order α] [add_monoid N] [linear_order N] /-! We are about to sneak in a hypothesis that might appear to be too strong. We assume `covariant_class` with *strict* inequality `<` also when proving the one with the *weak* inequality `≤`. This is actually necessary: addition on `lex (α →₀ N)` may fail to be monotone, when it is "just" monotone on `N`. See `counterexamples.zero_divisors_in_add_monoid_algebras` for a counterexample. -/ section left variables [covariant_class N N (+) (<)] instance lex.covariant_class_lt_left : covariant_class (lex (α →₀ N)) (lex (α →₀ N)) (+) (<) := ⟨λ f g h ⟨a, lta, ha⟩, ⟨a, λ j ja, congr_arg ((+) _) (lta j ja), add_lt_add_left ha _⟩⟩ instance lex.covariant_class_le_left : covariant_class (lex (α →₀ N)) (lex (α →₀ N)) (+) (≤) := has_add.to_covariant_class_left _ end left section right variables [covariant_class N N (function.swap (+)) (<)] instance lex.covariant_class_lt_right : covariant_class (lex (α →₀ N)) (lex (α →₀ N)) (function.swap (+)) (<) := ⟨λ f g h ⟨a, lta, ha⟩, ⟨a, λ j ja, congr_arg (+ (of_lex f j)) (lta j ja), add_lt_add_right ha _⟩⟩ instance lex.covariant_class_le_right : covariant_class (lex (α →₀ N)) (lex (α →₀ N)) (function.swap (+)) (≤) := has_add.to_covariant_class_right _ end right end covariants end finsupp
7031f2d981f7a53f5b248e37750b3964146f956f
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world5/level8.lean
d21a56563d9ac636680d1023d36d123146f2ce3c
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,751
lean
/- # Function world. ## Level 8: `(P → Q) → ((Q → empty) → (P → empty))` Level 8 is the same as level 7, except we have replaced the set $F$ with the empty set $\emptyset$. The same proof will work (after all, our previous proof worked for all sets, and the empty set is a set). But note that if you start with `intro f, intro h, intro p,` (which can incidentally be shortened to `intros f h p`), then the local context looks like this: ``` P Q : Type, f : P → Q, h : Q → empty, p : P ⊢ empty ``` and your job is to construct an element of the empty set! This on the face of it seems hard, but what is going on is that our hypotheses (we have an element of $P$, and functions $P\to Q$ and $Q\to\emptyset$) are themselves contradictory, so I guess we are doing some kind of proof by contradiction at this point? However, if your next line is `apply h` then all of a sudden the goal seems like it might be possible again. If this is confusing, note that the proof of the previous world worked for all sets $F$, so in particular it worked for the empty set, you just probably weren't really thinking about this case explicitly beforehand. [Technical note to constructivists: I know that we are not doing a proof by contradiction. But how else do you explain to a classical mathematician that their goal is to prove something false and this is OK because their hypotheses don't add up?] -/ /- Definition Whatever the sets $P$ and $Q$ are, we make an element of $\operatorname{Hom}(\operatorname{Hom}(P,Q), \operatorname{Hom}(\operatorname{Hom}(Q,\emptyset),\operatorname{Hom}(P,\emptyset)))$. -/ example (P Q : Type) : (P → Q) → ((Q → empty) → (P → empty)) := begin intros f h p, apply h, apply f, exact p, end
7a7ebf793bb951fb2b09723ad0ff827897371a17
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/suggest.lean
7fc686de20ed158ea13804878aa524d0683707ee
[ "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,620
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen -/ import tactic.basic open tactic -- `suggest` fails if there are no goals. example : true := begin trivial, success_if_fail { suggest }, end example (a : Prop) : a ∨ true := begin (do s ← suggest_scripts, guard $ s.head = "Try this: exact or.inr trivial"), exact or.inr trivial, end example {a a' : ℕ} (h : a == a') : a = a' := begin (do s ← suggest_scripts, guard $ s.head = "Try this: exact eq_of_heq h"), exact eq_of_heq h, end example {a b c : ℤ} (h₁ : a = b) (h₂ : b = c) : a = c := begin (do s ← suggest_scripts, guard $ "Try this: exact eq.trans h₁ h₂" ∈ s), exact eq.trans h₁ h₂, end example (n : nat) : n + 0 = n := begin (do s ← suggest_scripts, guard $ s.head = "Try this: exact rfl"), exact rfl, end example (n : nat) : n < n + 1 := begin (do s ← suggest_scripts, guard $ s.head = "Try this: exact nat.lt.base n"), exact nat.lt.base n end example (n : nat) : n < n + 2 := begin (do s ← suggest_scripts, guard $ "Try this: refine nat.lt.step _" ∈ s), refine nat.lt.step _, -- this wasn't the first result; humans still necessary :-( (do s ← suggest_scripts, guard $ s.head = "Try this: exact nat.lt.base n"), exact nat.lt.base n end example (a b : Prop) : (a ∨ true) ∧ (b ∨ true) := begin (do s ← suggest_scripts, guard $ "Try this: refine ⟨_, _⟩" ∈ s), refine ⟨_, _⟩, -- wasn't the first result, because it created two new goals { (do s ← suggest_scripts, guard $ s.head = "Try this: exact or.inr trivial"), exact or.inr trivial }, { (do s ← suggest_scripts, guard $ s.head = "Try this: exact or.inr trivial"), exact or.inr trivial }, end example (A B : Prop) (a : A) (b : unit → B) : A ∧ B := begin (do s ← suggest_scripts, guard $ s.head = "Try this: refine ⟨a, _⟩"), refine ⟨a, _⟩, replace b := b (), (do s ← suggest_scripts, guard $ s.head = "Try this: exact b"), exact b, end example {a b c : ℕ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := begin (do s ← suggest_scripts, guard $ s.head = "Try this: exact le_trans h₁ h₂"), exact le_trans h₁ h₂ end -- Verify that `suggest` focuses on the first goal when there are multiple goals. example (a b c d e f : ℕ) (hab : a ≤ b) (hbc : b ≤ c) (hde : d ≤ e) (hef : e ≤ f) : a ≤ c ∧ d ≤ f := begin split, (do s ← suggest_scripts, guard $ s.head = "Try this: exact le_trans hab hbc"), exact le_trans hab hbc, exact le_trans hde hef end
ef2d2ddff4b215edaa44378f5fe5f1dbcb0cf082
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/W.lean
0e6f09c4b38e7a156de038c2c478f1cb894a6387
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,395
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.list import Mathlib.PostPort universes u_1 u_2 l namespace Mathlib /-! # W types Given `α : Type` and `β : α → Type`, the W type determined by this data, `W_type β`, is the inductively defined type of trees where the nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. This file is currently a stub, awaiting a full development of the theory. Currently, the main result is that if `α` is an encodable fintype and `β a` is encodable for every `a : α`, then `W_type β` is encodable. This can be used to show the encodability of other inductive types, such as those that are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of mathlib. ## Implementation details While the name `W_type` is somewhat verbose, it is preferable to putting a single character identifier `W` in the root namespace. -/ /-- Given `β : α → Type*`, `W_type β` is the type of finitely branching trees where nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. -/ inductive W_type {α : Type u_1} (β : α → Type u_2) where | mk : (a : α) → (β a → W_type β) → W_type β protected instance W_type.inhabited : Inhabited (W_type fun (_x : Unit) => empty) := { default := W_type.mk Unit.unit empty.elim } namespace W_type /-- The depth of a finitely branching tree. -/ def depth {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] : W_type β → ℕ := sorry theorem depth_pos {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] (t : W_type β) : 0 < depth t := W_type.cases_on t fun (t_a : α) (t_f : β t_a → W_type β) => nat.succ_pos (finset.sup finset.univ fun (n : β t_a) => depth (t_f n)) theorem depth_lt_depth_mk {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] (a : α) (f : β a → W_type β) (i : β a) : depth (f i) < depth (mk a f) := nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i)) end W_type /- Show that W types are encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. We define an auxiliary type `W_type' β n` of trees of depth at most `n`, and then we show by induction on `n` that these are all encodable. These auxiliary constructions are not interesting in and of themselves, so we mark them as `private`. -/ namespace encodable /-- `W_type` is encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. -/ protected instance W_type.encodable {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] [(a : α) → encodable (β a)] [encodable α] : encodable (W_type β) := let f : W_type β → sigma fun (n : ℕ) => W_type' β n := fun (t : W_type β) => sigma.mk (W_type.depth t) { val := t, property := sorry }; let finv : (sigma fun (n : ℕ) => W_type' β n) → W_type β := fun (p : sigma fun (n : ℕ) => W_type' β n) => subtype.val (sigma.snd p); of_left_inverse f finv sorry
e8b87531eecf7672ddc343df867ee5aa3e5d02e9
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/topology/bounded_continuous_function.lean
786cd96bb89bc22e6fcc8e7ac6e6c20f9f11f543
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
28,980
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth -/ import analysis.normed_space.basic /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ noncomputable theory open_locale topological_space classical open set filter metric universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] : Type (max u v) := {f : α → β // continuous f ∧ ∃C, ∀x y:α, dist (f x) (f y) ≤ C} local infixr ` →ᵇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space α] [metric_space β] [metric_space γ] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_coe_to_fun (α →ᵇ β) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space α] (f : α → β) (hf : continuous f) : α →ᵇ β := ⟨f, hf, bounded_range_iff.1 $ bounded_of_compact $ compact_range hf⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology α] (f : α → β) (hf : ∃C, ∀x y, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (α →ᵇ β) := ⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩ lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C := begin refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : ∀ (x y : α), dist (f.val x) (f.val y) ≤ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : ∀ (x y : α), dist (g.val x) (g.val y) ≤ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, λ y, calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≤ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≤ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_cInf dist_set_exists $ λb hb, hb.2 x @[ext] lemma ext (H : ∀x, f x = g x) : f = g := subtype.eq $ funext H lemma ext_iff : f = g ↔ ∀ x, f x = g x := ⟨λ h, λ x, h ▸ rfl, ext⟩ /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≤ dist f g := le_cInf dist_set_exists (λ C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (α →ᵇ β) := { dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg', eq_of_dist_eq_zero := λ f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg), dist_comm := λ f g, by simp [dist_eq, dist_comm], dist_triangle := λ f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } variable (α) /-- Constant as a continuous bounded function. -/ def const (b : β) : α →ᵇ β := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ variable {α} @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl lemma const_apply (a : α) (b : β) : (const α b : α → β) a = b := rfl /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α (default β)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) := continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/ have Hs : _ := continuous_iff'.1 f.2.1 x (ε/2) (half_pos ε0), mem_sets_of_superset (prod_mem_nhds_sets (ball_mem_nhds _ (half_pos ε0)) Hs) $ λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) hy ... = ε : add_halves _ /-- In particular, when `x` is fixed, `f → f x` is continuous -/ theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- When `f` is fixed, `x → f x` is also continuous, by definition -/ theorem continuous_evalf {f : α →ᵇ β} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space (α →ᵇ β) := complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : ∀x, cauchy_seq (λn, f n x) := λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N := λ x N, le_of_tendsto (by simp) (tendsto_const_nhds.dist (hF x)) (filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous, as a uniform limit of continuous functions -/ have : tendsto_uniformly (λn x, f n x) F at_top, { refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _), refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _), rw dist_comm, exact lt_of_le_of_lt (fF_bdd x n) hn }, exact this.continuous (λN, (f N).2.1) at_top_ne_bot }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), λ x y, calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≤ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim), exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : β → γ) {C : nnreal} (H : lipschitz_with C G) (f : α →ᵇ β) : α →ᵇ γ := ⟨λx, G (f x), H.continuous.comp f.2.1, let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, λ x y, calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _ ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ lemma lipschitz_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) := lipschitz_with.of_dist_le_mul $ λ f g, (dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x, calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _ ... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2 /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ lemma uniform_continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).uniform_continuous /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s := ⟨s.cod_restrict f H, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space α] [compact_space α] [metric_space β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space β] (A : set (α →ᵇ β)) (closed : is_closed A) (H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (λ ε ε0, _), rcases dense ε0 with ⟨ε₁, ε₁0, εε₁⟩, let ε₂ := ε₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to ε. This information will be provided by the values of `u` on a sufficiently dense set tα, slightly translated to fit in a finite ε₂-dense set tβ in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to ε, one uses the control on the modulus of continuity to extend the closeness on tα to closeness everywhere. -/ have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0), have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β}, f ∈ A → dist (f y) (f z) < ε₂ := λ x, let ⟨U, nhdsU, hU⟩ := H x _ ε₂0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most ε₂. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_univ.elim_finite_subcover_image (λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tα, _, ⟨_⟩, htα⟩, /- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/ rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0 with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI, /- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/ /- Associate to every point `y` in the space a nearby point `F y` in tβ -/ choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y), /- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/ /- Associate to every function a discrete approximation, mapping each point in `tα` to a point in `tβ` close to its true image by the function. -/ refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance ε -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁, obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)), refine calc dist (f x) (g x) ≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = ε₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _), calc dist (f x') (g x') ≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = ε₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (closed : is_closed A) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s, let F : (α →ᵇ s) → α →ᵇ β := comp coe M, refine compact_of_is_closed_subset ((_ : compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < ε : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (λx, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊢, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoli₂ s hs (closure A) is_closed_closure (λ f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ λ ε ε0, let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (λ x ε ε0, show ∃ U ∈ 𝓝 x, ∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε, begin refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)), rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < ε/2/2 + ε/2/2 + ε/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = ε : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α] (b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (α →ᵇ β)) (H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y)) (x:α) (ε : ℝ) (ε0 : ε > 0) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε := begin rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩, refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩, have : dist y z < δ := calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... < δ/2 + δ/2 : add_lt_add hy hz ... = δ : add_halves _, calc dist (f y) (f z) ≤ b (dist y z) : H y z f hf ... ≤ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < ε : hδ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] [normed_group β] variables (f g : α →ᵇ β) {x : α} {C : ℝ} instance : has_zero (α →ᵇ β) := ⟨const α 0⟩ @[simp] lemma coe_zero : (0 : α →ᵇ β) x = 0 := rfl instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩ lemma norm_def : ∥f∥ = dist f 0 := rfl /-- The norm of a bounded continuous function is the supremum of `∥f x∥`. We use `Inf` to ensure that the definition works if `α` has no elements. -/ lemma norm_eq (f : α →ᵇ β) : ∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} := by simp [norm_def, bounded_continuous_function.dist_eq] lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc ∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right] ... ≤ ∥f∥ : dist_coe_le_dist _ lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) : dist (f x) (f y) ≤ 2 * C := calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _ ... ≤ C + C : add_le_add (hC x) (hC y) ... = 2 * C : (two_mul _).symm /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ := dist_le_two_norm' f.norm_coe_le_norm x y variable {f} /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 variable (f) /-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty, then it is equal to `∥b∥`. -/ lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ := (norm_le (norm_nonneg b)).2 $ λ x, le_refl _ @[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ := le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : α →ᵇ β := ⟨λn, f n, ⟨Hf, ⟨_, dist_le_two_norm' H⟩⟩⟩ lemma norm_of_normed_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_group f hfc C hfC∥ ≤ C := (norm_le hC).2 hfC /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β] (f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β := of_normed_group f continuous_of_discrete_topology C H /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (α →ᵇ β) := ⟨λf g, of_normed_group (f + g) (f.2.1.add g.2.1) (∥f∥ + ∥g∥) $ λ x, le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) (g.norm_coe_le_norm x))⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (α →ᵇ β) := ⟨λf, of_normed_group (-f) f.2.1.neg ∥f∥ $ λ x, trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩ @[simp] lemma coe_add : ⇑(f + g) = λ x, f x + g x := rfl lemma add_apply : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : ⇑(-f) = λ x, - f x := rfl lemma neg_apply : (-f) x = -f x := rfl lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 := (@ext_iff _ _ _ _ f 0).symm instance : add_comm_group (α →ᵇ β) := { add_assoc := assume f g h, by ext; simp [add_assoc], zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp [add_comm], ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_sub : ⇑(f - g) = λ x, f x - g x := rfl lemma sub_apply : (f - g) x = f x - g x := rfl instance : normed_group (α →ᵇ β) := { dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] } lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g := by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x } lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 end normed_group section normed_space /-! ### Normed space structure In this section, if `β` is a normed space, then we show that the space of bounded continuous functions from `α` to `β` inherits a normed space structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [normed_group β] [normed_space 𝕜 β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_scalar 𝕜 (α →ᵇ β) := ⟨λ c f, of_normed_group (c • f) (continuous_const.smul f.2.1) (∥c∥ * ∥f∥) $ λ x, trans_rel_right _ (norm_smul _ _) (mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))⟩ @[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl instance : module 𝕜 (α →ᵇ β) := module.of_core $ { smul := (•), smul_add := λ c f g, ext $ λ x, smul_add c (f x) (g x), add_smul := λ c₁ c₂ f, ext $ λ x, add_smul c₁ c₂ (f x), mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul c₁ c₂ (f x), one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } instance : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _⟩ end normed_space section normed_ring /-! ### Normed ring structure In this section, if `R` is a normed ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] {R : Type*} [normed_ring R] instance : ring (α →ᵇ R) := { one := const α 1, mul := λ f g, of_normed_group (f * g) (f.2.1.mul g.2.1) (∥f∥ * ∥g∥) $ λ x, le_trans (normed_ring.norm_mul (f x) (g x)) $ mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _), one_mul := λ f, ext $ λ x, one_mul (f x), mul_one := λ f, ext $ λ x, mul_one (f x), mul_assoc := λ f₁ f₂ f₃, ext $ λ x, mul_assoc _ _ _, left_distrib := λ f₁ f₂ f₃, ext $ λ x, left_distrib _ _ _, right_distrib := λ f₁ f₂ f₃, ext $ λ x, right_distrib _ _ _, .. bounded_continuous_function.add_comm_group } instance : normed_ring (α →ᵇ R) := { norm_mul := λ f g, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, .. bounded_continuous_function.normed_group } end normed_ring section normed_algebra /-! ### Normed algebra structure In this section, if `γ` is a normed algebra, then we show that the space of bounded continuous functions from `α` to `γ` inherits a normed algebra structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [normed_group β] [normed_space 𝕜 β] variables [normed_ring γ] [normed_algebra 𝕜 γ] variables {f g : α →ᵇ γ} {x : α} {c : 𝕜} /-- `bounded_continuous_function.const` as a `ring_hom`. -/ def C : 𝕜 →+* (α →ᵇ γ) := { to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c), map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one, map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _, map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero, map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ } instance : algebra 𝕜 (α →ᵇ γ) := { to_ring_hom := C, commutes' := λ c f, ext $ λ x, algebra.commutes' _ _, smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _, ..bounded_continuous_function.module, ..bounded_continuous_function.ring } instance [nonempty α] : normed_algebra 𝕜 (α →ᵇ γ) := { norm_algebra_map_eq := λ c, begin calc ∥ (algebra_map 𝕜 (α →ᵇ γ)).to_fun c∥ = ∥(algebra_map 𝕜 γ) c∥ : _ ... = ∥c∥ : norm_algebra_map_eq _ _, apply norm_const_eq ((algebra_map 𝕜 γ) c), assumption, end, ..bounded_continuous_function.algebra } /-! ### Structure as normed module over scalar functions If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous functions from `α` to `β` is naturally a module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ instance has_scalar' : has_scalar (α →ᵇ 𝕜) (α →ᵇ β) := ⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_group (λ x, (f x) • (g x)) (continuous.smul f.2.1 g.2.1) (∥f∥ * ∥g∥) (λ x, calc ∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _ ... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _) (norm_nonneg _)) ⟩ instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) := module.of_core $ { smul := (•), smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _, add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ := norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ /- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts show that the space of bounded continuous functions from `α` to `β` is naturally a normed module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ end normed_algebra end bounded_continuous_function
0d048a41ddc70dea712bda6e3a9b6924c3df2676
9d85d84996d37da7dde61d51c44e980f8a3e5f5f
/src/m845_hw1.lean
9af64487158f63afee5df2961897661c27c84e9a
[]
no_license
agusakov/m845_lean
3a877ceccc38a011b7d91d6d178fca2fbb345c24
b741f408954b629e56e9ceadbc27fee0ae9eb48e
refs/heads/master
1,667,636,075,536
1,593,036,005,000
1,593,036,005,000
274,777,815
0
0
null
null
null
null
UTF-8
Lean
false
false
3,598
lean
import algebra.group.basic import data.real.basic import group_theory.order_of_element noncomputable theory open_locale classical def star_set := set.Ico (0:ℝ) 1 #check star_set section star_group #check has_coe_to_sort #check semigroup def star : ℝ → ℝ → ℝ | x y := x + y - ⌊ x + y ⌋ notation x`⋆`y := star x y variables (x y : ℝ) (A : Type*) #check star_set lemma star_closed {a b : ℝ} (ha : a ∈ star_set) (hb : b ∈ star_set) : (a ⋆ b) ∈ star_set := begin unfold star, unfold star_set, split, exact fract_nonneg (a + b), exact fract_lt_one (a + b), end lemma star_assoc {a b c : ℝ} (ha : a ∈ star_set) (hb : b ∈ star_set) (hc : c ∈ star_set): (a ⋆ b ⋆ c) = (a ⋆ (b ⋆ c)) := begin unfold star, repeat {rw ← fract}, rw fract_eq_fract, let z : ℤ := _, use z, repeat {rw fract}, ring, norm_cast, --thanks Reid! end lemma zero_in_star_set : (0 : ℝ) ∈ star_set := begin unfold star_set, split, by refl, exact zero_lt_one, end lemma star_identity_is_zero {a : ℝ} (ha : a ∈ star_set) : (a ⋆ 0) = a := begin unfold star, unfold star_set at ha, cases ha with h0 h1, rw add_zero, rw ← fract, have h2 := fract_nonneg a, have h3 := fract_lt_one a, rw fract_eq_iff, split, {exact h0}, {split, {exact h1}, {use 0, exact sub_self a}, }, end lemma star_inverses {a : ℝ} (ha : a ∈ star_set) : ∃ (b : ℝ), (a ⋆ b) = (0 : ℝ) ∧ b ∈ star_set := begin by_cases (a = 0), { rw h, use (0 : ℝ), split, unfold star, rw ← fract, rw add_zero, exact fract_zero, rw h at ha, exact ha }, { use (1 - a), split, { unfold star, rw add_comm, rw sub_add, rw sub_self, rw sub_zero, simp }, { unfold star_set, unfold star_set at ha, cases ha with h0 h1, have h2 : 0 < a := by { rw lt_iff_le_and_ne, split, {exact h0}, {exact ne.symm h}, }, split, { apply le_of_lt, apply lt_sub_right_of_add_lt, rw zero_add, exact h1, }, { apply sub_lt_self, exact h2, }, }, } end #lint end star_group section my_group universe u /- Prove that (a\_1a_2···a_n)^-1 = a_n^−1···a_2^−1a_1^−1 for all a_1,a_2,···,a_n ∈G -/ -- use rcases here cause I guess it does inductive magic <3 --(list.map a (list.range n)), where (a : ℕ → G) variables (G : Type*) [group G] (a : G) lemma inv_prod' {G : Type*} [group G] (l : list G) : (l.prod)⁻¹ = (list.map (λ (x : G), x⁻¹) l.reverse).prod := begin induction l with hd tl h, simp only [one_inv, list.prod_nil, list.map, list.reverse_nil], simp only [h, list.reverse_cons, mul_inv_rev, mul_one, list.map_append, list.prod_append, list.prod_cons, list.prod_nil, list.map], end /-Let x be an element of G. Prove that if |x|=n for some positive integer n then x^−1 = x^n−1 -/ /-lemma gpow_eq_mod_order_of' {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one]-/ end my_group
3429106cf2d451ad5f952a93a4f95753e7e6138a
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/reduction/cpge_reduction_002.lean
8f377e9b23637bd4cb8bfb476158f20af2e6315f
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
683
lean
import algebra.module.basic import algebra.module.linear_map import linear_algebra.basic import linear_algebra.prod import linear_algebra.projection import order.bounded_lattice import logic.function.conjugate -- Montrer qu'un endomorphisme f d'un K -espace vectoriel E commute avec un -- projecteur p si, et seulement si, les espaces Im(p) et Ker(p) sont stables par f . theorem cpge_reduction_2 {K : Type*} [ring K] {E : Type*} [add_comm_group E] [module K E] (A B : submodule K E) (h : is_compl A B) (u : linear_map K E E): let p: linear_map K E E := A.subtype.comp (A.linear_proj_of_is_compl B h) in function.commute p u <-> (A.map u = A /\ B.map u = B) := sorry
3a0899af9ad61c5755d1e15ad066697228642d46
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/dynamics/ergodic/ergodic.lean
c879e1a26b7c0c9c08c36797b5b582c9f857dda0
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,863
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import dynamics.ergodic.measure_preserving /-! # Ergodic maps and measures Let `f : α → α` be measure preserving with respect to a measure `μ`. We say `f` is ergodic with respect to `μ` (or `μ` is ergodic with respect to `f`) if the only measurable sets `s` such that `f⁻¹' s = s` are either almost empty or full. In this file we define ergodic maps / measures together with quasi-ergodic maps / measures and provide some basic API. Quasi-ergodicity is a weaker condition than ergodicity for which the measure preserving condition is relaxed to quasi measure preserving. # Main definitions: * `pre_ergodic`: the ergodicity condition without the measure preserving condition. This exists to share code between the `ergodic` and `quasi_ergodic` definitions. * `ergodic`: the definition of ergodic maps / measures. * `quasi_ergodic`: the definition of quasi ergodic maps / measures. * `ergodic.quasi_ergodic`: an ergodic map / measure is quasi ergodic. * `quasi_ergodic.ae_empty_or_univ'`: when the map is quasi measure preserving, one may relax the strict invariance condition to almost invariance in the ergodicity condition. -/ open set function filter measure_theory measure_theory.measure variables {α : Type*} {m : measurable_space α} (f : α → α) {s : set α} include m /-- A map `f : α → α` is said to be pre-ergodic with respect to a measure `μ` if any measurable strictly invariant set is either almost empty or full. -/ structure pre_ergodic (μ : measure α . volume_tac) : Prop := (ae_empty_or_univ : ∀ ⦃s⦄, measurable_set s → f⁻¹' s = s → s =ᵐ[μ] (∅ : set α) ∨ s =ᵐ[μ] univ) /-- A map `f : α → α` is said to be ergodic with respect to a measure `μ` if it is measure preserving and pre-ergodic. -/ @[nolint has_nonempty_instance] structure ergodic (μ : measure α . volume_tac) extends measure_preserving f μ μ, pre_ergodic f μ : Prop /-- A map `f : α → α` is said to be quasi ergodic with respect to a measure `μ` if it is quasi measure preserving and pre-ergodic. -/ @[nolint has_nonempty_instance] structure quasi_ergodic (μ : measure α . volume_tac) extends quasi_measure_preserving f μ μ, pre_ergodic f μ : Prop variables {f} {μ : measure α} namespace pre_ergodic lemma measure_self_or_compl_eq_zero (hf : pre_ergodic f μ) (hs : measurable_set s) (hs' : f⁻¹' s = s) : μ s = 0 ∨ μ sᶜ = 0 := by simpa using hf.ae_empty_or_univ hs hs' /-- On a probability space, the (pre)ergodicity condition is a zero one law. -/ lemma prob_eq_zero_or_one [is_probability_measure μ] (hf : pre_ergodic f μ) (hs : measurable_set s) (hs' : f⁻¹' s = s) : μ s = 0 ∨ μ s = 1 := by simpa [hs] using hf.measure_self_or_compl_eq_zero hs hs' lemma of_iterate (n : ℕ) (hf : pre_ergodic (f^[n]) μ) : pre_ergodic f μ := ⟨λ s hs hs', hf.ae_empty_or_univ hs $ is_fixed_pt.preimage_iterate hs' n⟩ end pre_ergodic namespace ergodic /-- An ergodic map is quasi ergodic. -/ lemma quasi_ergodic (hf : ergodic f μ) : quasi_ergodic f μ := { .. hf.to_pre_ergodic, .. hf.to_measure_preserving.quasi_measure_preserving, } end ergodic namespace quasi_ergodic /-- For a quasi ergodic map, sets that are almost invariant (rather than strictly invariant) are still either almost empty or full. -/ lemma ae_empty_or_univ' (hf : quasi_ergodic f μ) (hs : measurable_set s) (hs' : f⁻¹' s =ᵐ[μ] s) : s =ᵐ[μ] (∅ : set α) ∨ s =ᵐ[μ] univ := begin obtain ⟨t, h₀, h₁, h₂⟩ := hf.to_quasi_measure_preserving.exists_preimage_eq_of_preimage_ae hs hs', rcases hf.ae_empty_or_univ h₀ h₂ with h₃ | h₃; [left, right]; exact ae_eq_trans h₁.symm h₃, end end quasi_ergodic
43f0ab55df0ae5e0ad813e7ddaa40741da23a700
618003631150032a5676f229d13a079ac875ff77
/src/tactic/solve_by_elim.lean
289d1bc94b8546b1fe612f2e7794e87f93ed0e17
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
12,724
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic.core /-! # solve_by_elim A depth-first search backwards reasoner. `solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against the goals, recursively acting on any generated subgoals. It accepts a variety of configuration options described below, enabling * backtracking across multiple goals, * pruning the search tree, and * invoking other tactics before or after trying to apply lemmas. At present it has no "premise selection", and simply tries the supplied lemmas in order at each step of the search. -/ namespace tactic namespace solve_by_elim /-- `mk_assumption_set` builds a collection of lemmas for use in the backtracking search in `solve_by_elim`. * By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and `congr_arg`. * The flag `no_dflt` removes these. * The argument `hs` is a list of `simp_arg_type`s, and can be used to add, or remove, lemmas or expressions from the set. * The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes. `mk_assumption_set` returns not a `list expr`, but a `list (tactic expr)`. The problem here is that we may generate lemmas that have as yet unspecified implicit arguments, and these implicit arguments would be filled in by metavariables if we created the actual `expr` objects now. As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become `@rfl ?m_1 ?m_2`. Because `solve_by_elim` works by repeated application of lemmas against subgoals, the first time such a lemma is successfully applied, those metavariables will be unified, and thereafter have fixed values. This would make it impossible to apply the lemma a second time with different values of the metavariables. See https://github.com/leanprover-community/mathlib/issues/2269 As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any that do not in fact produce metavariables with a simple `return` tactic. -/ meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name) : tactic (list (tactic expr)) := -- We lock the tactic state so that any spurious goals generated during -- elaboration of pre-expressions are discarded lock_tactic_state $ do -- `hs` are expressions specified explicitly, -- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses, -- `gex` are the other exceptions (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, -- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s. -- Note that while we evaluate these thunks on two occasions below while preparing the list, -- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the -- length of the search `solve_by_elim` executes. let hs := hs.map (λ h, i_to_expr_for_apply h), l ← attr.mmap $ λ a, attribute.get_instances a, let l := l.join, let m := l.map (λ h, mk_const h), -- In order to remove the expressions we need to evaluate the thunks. hs ← (hs ++ m).mfilter $ λ h, (do h ← h, return $ expr.const_name h ∉ gex), let hs := if no_dflt then hs else ([`rfl, `trivial, `congr_fun, `congr_arg].map (λ n, (mk_const n))) ++ hs, hs ← if ¬ no_dflt ∨ all_hyps then do ctx ← local_context, -- Remove local exceptions specified in `hex`: return $ hs.append ((ctx.filter (λ h : expr, h.local_uniq_name ∉ hex)).map return) else return hs, -- Finally, run all of the tactics: any that return an expression without metavariables can safely -- be replaced by a `return` tactic. hs.mmap (λ h, do e ← h, if e.has_meta_var then return h else return (return e)) /-- Configuration options for `solve_by_elim`. * `accept : list expr → tactic unit` determines whether the current branch should be explored. At each step, before the lemmas are applied, `accept` is passed the proof terms for the original goals, as reported by `get_goals` when `solve_by_elim` started. These proof terms may be metavariables (if no progress has been made on that goal) or may contain metavariables at some leaf nodes (if the goal has been partially solved by previous `apply` steps). If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks. By default `accept := λ _, skip` always succeeds. (There is an example usage in `tests/solve_by_elim.lean`.) * `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`. * `discharger : tactic unit` specifies an additional tactic to apply on subgoals for which no lemma applies. If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals. -/ meta structure basic_opt extends apply_any_opt := (accept : list expr → tactic unit := λ _, skip) (pre_apply : tactic unit := skip) (discharger : tactic unit := failed) /-- The internal implementation of `solve_by_elim`, with a limiting counter. -/ meta def solve_by_elim_aux (opt : basic_opt) (original_goals : list expr) (lemmas : list (tactic expr)) : ℕ → tactic unit | n := do -- First, check that progress so far is `accept`able. lock_tactic_state (original_goals.mmap instantiate_mvars >>= opt.accept) >> -- Then check if we've finished. (done <|> -- Otherwise, if there's more time left, guard (n > 0) >> -- run the `pre_apply` tactic, then opt.pre_apply >> -- try either applying a lemma and recursing, or ((apply_any_thunk lemmas opt.to_apply_any_opt $ solve_by_elim_aux (n-1)) <|> -- if that doesn't work, run the discharger and recurse. (opt.discharger >> solve_by_elim_aux (n-1)))) /-- Arguments for `solve_by_elim`: * By default `solve_by_elim` operates only on the first goal, but with `backtrack_all_goals := true`, it operates on all goals at once, backtracking across goals as needed, and only succeeds if it discharges all goals. * `lemmas` specifies the list of lemmas to use in the backtracking search. If `none`, `solve_by_elim` uses the local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. * `lemma_thunks` provides the lemmas as a list of `tactic expr`, which are used to regenerate the `expr` objects to avoid binding metavariables. (If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.) * `max_depth` bounds the depth of the search. -/ meta structure opt extends basic_opt := (backtrack_all_goals : bool := ff) (lemmas : option (list expr) := none) (lemma_thunks : option (list (tactic expr)) := lemmas.map (λ l, l.map return)) (max_depth : ℕ := 3) /-- If no lemmas have been specified, generate the default set (local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`). -/ meta def opt.get_lemma_thunks (opt : opt) : tactic (list (tactic expr)) := match opt.lemma_thunks with | none := mk_assumption_set ff [] [] | some lemma_thunks := return lemma_thunks end end solve_by_elim open solve_by_elim /-- `solve_by_elim` repeatedly tries `apply`ing a lemma from the list of assumptions (passed via the `opt` argument), recursively operating on any generated subgoals, backtracking as necessary. `solve_by_elim` succeeds only if it discharges the goal. (By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that. With the option `backtrack_all_goals := tt`, it attempts to solve all goals, and only succeeds if it does so. With `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for one goal if it then can't discharge other goals.) If passed an empty list of assumptions, `solve_by_elim` builds a default set as per the interactive tactic, using the `local_context` along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. To pass a particular list of assumptions, use the `lemmas` field in the configuration argument. This expects an `option (list expr)`. In certain situations it may be necessary to instead use the `lemma_thunks` field, which expects a `option (list (tactic expr))`. This allows for regenerating metavariables for each application, which might otherwise get stuck. See also the simpler tactic `apply_rules`, which does not perform backtracking. -/ meta def solve_by_elim (opt : opt := { }) : tactic unit := do tactic.fail_if_no_goals, lemmas ← opt.get_lemma_thunks, (if opt.backtrack_all_goals then id else focus1) $ (do gs ← get_goals, solve_by_elim_aux opt.to_basic_opt gs lemmas opt.max_depth <|> fail "solve_by_elim failed; try increasing `max_depth`?") open interactive lean.parser interactive.types local postfix `?`:9001 := optional namespace interactive /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. If this fails, `apply_assumption` will call `symmetry` and try again. If this also fails, `apply_assumption` will call `exfalso` and try again, so that if there is an assumption of the form `P → ¬ Q`, the new tactic state will have two goals, `P` and `Q`. Optional arguments: - `lemmas`: a list of expressions to apply, instead of the local constants - `tac`: a tactic to run on each subgoal after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (lemmas : option (list expr) := none) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := do lemmas ← match lemmas with | none := local_context | some lemmas := return lemmas end, tactic.apply_any lemmas opt tac add_tactic_doc { name := "apply_assumption", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_assumption], tags := ["context management", "lemma application"] } /-- `solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches and then repeatedly calls `apply` on the generated subgoals until no subgoals remain, performing at most `max_depth` recursive steps. `solve_by_elim` discharges the current goal or fails. `solve_by_elim` performs back-tracking if subgoals can not be solved. By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`, `congr_fun` and `congr_arg`. The assumptions can be modified with similar syntax as for `simp`: * `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas. * `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes. * `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included. * `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones. `solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal makes other goals impossible. optional arguments passed via a configuration argument as `solve_by_elim { ... }` - max_depth: number of attempts at discharging generated sub-goals - discharger: a subsidiary tactic to try at each step when no lemmas apply (e.g. `cc` may be helpful). - pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`). - accept: a subsidiary tactic `list expr → tactic unit` that at each step, before any lemmas are applied, is passed the original proof terms as reported by `get_goals` when `solve_by_elim` started (but which may by now have been partially solved by previous `apply` steps). If the `accept` tactic fails, `solve_by_elim` will abort searching the current branch and backtrack. This may be used to filter results, either at every step of the search, or filtering complete results (by testing for the absence of metavariables, and then the filtering condition). -/ meta def solve_by_elim (all_goals : parse $ (tk "*")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : solve_by_elim.opt := { }) : tactic unit := do lemma_thunks ← mk_assumption_set no_dflt hs attr_names, tactic.solve_by_elim { backtrack_all_goals := all_goals.is_some ∨ opt.backtrack_all_goals, lemma_thunks := some lemma_thunks, ..opt } add_tactic_doc { name := "solve_by_elim", category := doc_category.tactic, decl_names := [`tactic.interactive.solve_by_elim], tags := ["search"] } end interactive end tactic
f006616335d7c897ea63cd85d11856d054b8dd49
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/mynat/prime.lean
e8c14a7a31ec18dcb2a4d40d40bcef03a100a4a6
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
8,136
lean
-- vim: ts=2 sw=0 sts=-1 et ai tw=70 import .dvd import .induction import .fact namespace hidden namespace mynat def prime (m: mynat) := m ≠ 1 ∧ ∀ k: mynat, k ∣ m → k = 1 ∨ k = m def composite (m : mynat) := ∃ a b: mynat, a ≠ 1 ∧ b ≠ 1 ∧ a * b = m def coprime (m n : mynat) := ∀ k: mynat, k ∣ m → k ∣ n → k = 1 variables {m n p k : mynat} theorem zero_nprime: ¬prime 0 := begin assume h0pm, cases h0pm with h0pm_left h0pm_right, have h2d0: (2: mynat) ∣ 0 := dvd_zero, have h2n2: 2 ≠ 2, have h2eq01 := h0pm_right 2 h2d0, repeat { cases h2eq01 }, from h2n2 rfl, end theorem one_nprime: ¬prime 1 := begin assume h1pm, cases h1pm with h1ne1 _, from h1ne1 rfl, end theorem zero_composite: composite 0 := begin existsi zero, existsi zero, split, { assume h01, cases h01, }, { split, { assume h01, cases h01, }, simp, }, end theorem one_ncomposite: ¬composite 1 := begin assume h1cmp, cases h1cmp with a h, cases h with b h, cases h with han1 h, cases h with hbn1 hab1, from han1 (one_unit hab1), end theorem two_ncomposite: ¬composite 2 := begin assume h2cmp, cases h2cmp with a h, cases h with b h, cases h with han1 h, cases h with hbn1 hab2, cases a, { simp at hab2, cases hab2, }, { cases b, { simp at hab2, cases hab2, }, { cases a, { simp at han1, contradiction, }, { cases b, { simp at hbn1, contradiction, }, { simp at hab2, have h := succ_inj hab2, have h' := succ_inj h, from succ_ne_zero h', }, }, }, }, end -- prove 2 is prime by a massive case-bash -- frankly this was just proved by going into a tactics red mist theorem two_prime: prime 2 := begin split, { assume h21, cases h21, }, { intro k, assume hk2, cases hk2 with n hn, cases k, { simp at hn, cases hn, }, { cases k, { simp, }, { simp at hn, cases n, { simp at hn, cases hn, }, { simp at hn, cases n, { simp at hn, cc, }, { have hcontr' := succ_inj hn.symm, simp at hcontr', have hcontr := succ_inj hcontr', simp at hcontr, exfalso, from succ_ne_zero hcontr, }, }, }, }, }, end @[symm] theorem coprime_symm {m n : mynat} : coprime m n → coprime n m := begin assume h, intro k, assume hkn hkm, exact h k hkm hkn, end theorem coprime_one: coprime m 1 := begin intro k, assume _ hk, from dvd_one hk, end theorem one_coprime: coprime 1 m := coprime_symm coprime_one theorem coprime_succ: coprime m (succ m) := begin intro a, assume hm hsucc, cases hm with b hb, cases hsucc with c hc, rw [←add_one_succ, hb] at hc, have : a ∣ 1, apply dvd_remainder (b * a) 1 (c * a) a, rw mul_comm, apply dvd_mul, refl, rw mul_comm, apply dvd_mul, refl, assumption, from dvd_one this, end theorem succ_coprime: coprime (succ m) m := coprime_symm coprime_succ theorem coprime_prime (hp : prime p) : ¬(coprime p n) → p ∣ n := begin assume hncoprime, unfold coprime at hncoprime, rw not_forall at hncoprime, cases hncoprime with k hk, rw [not_imp, not_imp] at hk, cases hp.right k hk.left; subst h, exfalso, from hk.right.right rfl, from hk.right.left, end open classical local attribute [instance] prop_decidable lemma nprime_imp_ncomp_or_one: ¬prime m → composite m ∨ m = 1 := begin assume h, cases not_and_distrib.mp h with heq hnall, { right, from not_not.mp heq, }, { left, cases not_forall.mp hnall with k hk, cases not_imp.mp hk with hkdvdm heq1m, cases hkdvdm with a hak, existsi a, existsi k, split, { assume ha1, rw [ha1, one_mul] at hak, have : k = 1 ∨ k = m, right, symmetry, assumption, contradiction, }, split, { assume hk1, have : k = 1 ∨ k = m, left, assumption, contradiction, }, { symmetry, assumption, }, }, end -- Requires strong induction theorem prime_divisor: m ≠ 1 → ∃ p: mynat, prime p ∧ p ∣ m := begin assume h, apply strong_induction (λ m, m ≠ 1 → ∃ p: mynat, prime p ∧ p ∣ m), { assume h, existsi (2: mynat), split, from two_prime, from dvd_zero, }, { intro n, assume hn hn0, cases em (prime (succ n)) with hp hnp, { existsi succ n, split, assumption, refl, }, { have hcomp_or_one := nprime_imp_ncomp_or_one hnp, cases hcomp_or_one with hcomp h1, { cases hcomp with a h₁, cases h₁ with b hab, have ha₁ := hn a, have hadvds : a ∣ succ n, { have := hab.right.right, existsi b, symmetry, rw mul_comm, assumption, }, have halen: a ≤ n, { apply le_iff_lt_succ.mpr, have hasn := dvd_le succ_ne_zero hadvds, have hansn: a ≠ succ n, { -- the oldest trick in the book: just wear it down by -- cases assume hasn, have habsn := hab.right.right, rw [hasn] at habsn, cases b, simp at habsn, from succ_ne_zero habsn.symm, cases b, simp at hab, assumption, suffices : succ (succ b) = 1, rw [←one_eq_succ_zero] at this, suffices hcontra : succ b = 0, from mynat.no_confusion hcontra, apply succ_inj, assumption, apply @mul_cancel_to_one (succ n) _, assume hsucc0, from mynat.no_confusion hsucc0, symmetry, assumption, }, rw le_iff_lt_or_eq at hasn, cases hasn, assumption, contradiction, }, have ha₂ := ha₁ halen hab.left, cases ha₂ with p hp, existsi p, split, from hp.left, from dvd_trans hp.right hadvds, }, contradiction, }, }, assumption, end theorem infinitude_of_primes: infinitely_many prime := begin -- Famously, this is a proof by contradiction by_contradiction h, -- As there are only finitely many primes, there exists an n than -- which there is no prime greater cases not_forall.mp h with n hn, -- So any x greater than n is not prime have halln : ∀ x, n ≤ x → ¬prime x, { have := not_exists.mp hn, assume x hnx hpx, have hx := this x, from hx ⟨hnx, hpx⟩, }, -- We can form a contradiction if we can exhibit a k which is not 1, -- and is not divisible by anything less than n except 1 suffices: ∃ k : mynat, k ≠ 1 ∧ ∀ x : mynat, x ≠ 1 → x ≤ n → ¬(x ∣ k), { cases this with k h₁, have hk := h₁.right, -- and is not divisible by any prime have hnoprimediv : ∀ p : mynat, prime p → ¬(p ∣ k), { -- Since assume we have some prime divisor p assume p hp, -- If p were more than n, it wouldn't be prime have := halln p, -- And it's greater than or equal to n by_cases (n ≤ p), { -- Which is a contradiction, exfalso, from this h hp, }, { -- Or less than or equal to n, so doesn't divide k! from hk p hp.left (lt_impl_le h), }, }, -- Which directly contradicts the fact that every natural > 1 is -- divisible by a prime have hprimediv := prime_divisor h₁.left, cases hprimediv with p hp, from hnoprimediv p hp.left hp.right, }, -- Exhibit (fact n) + 1, and we are done. existsi (fact n) + 1, split, { assume h₁, have heq := h₁.symm, clear h₁, rw add_comm at heq, suffices : fact n = 0, from fact_nzero this, apply add_cancel_to_zero, assumption, }, from fact_ndvd_lt, end end mynat end hidden
0c300e783947eb44c5d3ef75a431057727869585
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/solutions/thursday/category_theory/exercise2.lean
d42e5e05ebb31179978ce8d7fad2d39d24615641
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,367
lean
import algebra.category.CommRing.basic import data.polynomial /-! Let's show that taking polynomials over a ring is functor `Ring ⥤ Ring`. -/ noncomputable theory -- the default implementation of polynomials is noncomputable -- Just ignore this for now: it's a hack that prevents an annoying problem, -- and a cleaner fix is on its way to mathlib. local attribute [irreducible] polynomial.eval₂ /-! Hints: * use `polynomial.map_ring_hom` -/ def Ring.polynomial : Ring ⥤ Ring := -- sorry { obj := λ R, Ring.of (polynomial R), map := λ R S f, polynomial.map_ring_hom f, map_id' := by { intros, ext; simp, }, map_comp' := by { intros, ext; simp, }, } -- sorry def CommRing.polynomial : CommRing ⥤ CommRing := -- sorry { obj := λ R, CommRing.of (polynomial R), map := λ R S f, polynomial.map_ring_hom f, map_id' := by { intros, ext; simp, }, map_comp' := by { intros, ext; simp, }, } -- sorry open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := -- Hint: You can do this in two lines, ≤ 33 columns! -- sorry { hom := { app := λ R, 𝟙 _, }, inv := { app := λ R, 𝟙 _, }, }. -- sorry /-! There are some further hints in `hints/category_theory/exercise2/` -/ /-! Bonus problem: Why did we set `local attribute [irreducible] polynomial.eval₂`? What goes wrong without it? Why? -/ -- omit local attribute [semireducible] polynomial.eval₂ /- def Ring.polynomial' : Ring ⥤ Ring := { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), map_comp' := λ R S T f g, begin refl end, }. -/ -- fails, but takes >5s seconds to do so! /-! What's going on? For some reason trying to solve the goal in `map_comp'` using `refl` takes a huge amount of time. This causes the automation which is responsible for automatically proving functoriality of functors to time out, and fail. How can `refl` take so long? Isn't it just checking if two things are the same? The problem is that when we work in type theory, in principle no definition is "opaque", and Lean sometimes has to unfold definitions in order to compare if two things are actually the same. Usually it's pretty conservative about this, and manages to avoid unfolding too deeply before coming up with an answer, but in bad cases it can get really bad. Somehow this is happening here! The solution we have available is to mark definitions as `[irreducible]`, which (almost, but not quite completely) prevents Lean from unfolding when checking definitional equality. Of course, this has a consequence --- Lean will sometimes fail to prove things by `refl` now! The solution to this is to provide a thorough API for our important definitions, so that after some point in the development one never needs to unfold the actual definition again, but one can work through theorems proved about the definition (e.g. characterisations and universal properties). An important example of this is that we have marked `real` as `[irreducible]` in Lean --- after you've got things working, no one should ever have to know whether the "actual definition" is in terms of Cauchy sequences or Dedekind cuts. Unfortunately at this point we don't use `[irreducible]` often enough in Lean, and improving this aspect of mathlib is an ongoin project. -/ -- omit