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
8133ac07dacf8d4c2b2159b1d663430fa59e4685
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/linear_algebra/determinant.lean
2b3f432d475ea860529cf5a15759ee6cea0ba209
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
5,500
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.matrix.basic import group_theory.perm.sign universes u v open equiv equiv.perm finset function namespace matrix variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) definition det (M : matrix n n R) : R := univ.sum (λ (σ : perm n), ε σ * univ.prod (λ i, M (σ i) i)) @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = univ.prod d := begin refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt (equiv.ext _ _) h2) with x h3, convert ring.mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card, zero_pow (fintype.card_pos_iff.2 h)] @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : univ.sum (λ σ : perm n, (ε σ) * (univ.prod (λ x, M (σ x) (p x) * N (p x) x))) = 0 := let ⟨i, hi⟩ := classical.not_forall.1 (mt fintype.injective_iff_bijective.1 H) in let ⟨j, hij'⟩ := classical.not_forall.1 hi in have hij : p i = p j ∧ i ≠ j, from not_imp.1 hij', sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc, have univ.prod (λ x, M (σ x) (p x)) = univ.prod (λ x, M ((σ * swap i j) x) (p x)), from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this]) (λ _ _ _ _ h, (swap i j).injective h) (λ b _, ⟨swap i j b, mem_univ _, by simp⟩), by simp [sign_mul, this, sign_swap hij.2, prod_mul_distrib]) (λ σ _ _ h, hij.2 (σ.injective $ by conv {to_lhs, rw ← h}; simp)) (λ _ _, mem_univ _) (λ _ _, equiv.ext _ _ $ by simp) @[simp] lemma det_mul (M N : matrix n n R) : det (M * N) = det M * det N := calc det (M * N) = univ.sum (λ σ : perm n, (univ.pi (λ a, univ)).sum (λ (p : Π (a : n), a ∈ univ → n), ε σ * univ.attach.prod (λ i, M (σ i.1) (p i.1 (mem_univ _)) * N (p i.1 (mem_univ _)) i.1))) : by simp only [det, mul_val', prod_sum, mul_sum] ... = univ.sum (λ σ : perm n, univ.sum (λ p : n → n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : sum_congr rfl (λ σ _, sum_bij (λ f h i, f i (mem_univ _)) (λ _ _, mem_univ _) (by simp) (by simp [funext_iff]) (λ b _, ⟨λ i hi, b i, by simp⟩)) ... = univ.sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_comm ... = ((@univ (n → n) _).filter bijective ∪ univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_congr (finset.ext.2 (by simp; tauto)) (λ _ _, rfl) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) + (univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_union (by simp [finset.ext]; tauto) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) + (univ.filter (λ p : n → n, ¬bijective p)).sum (λ p, 0) : (add_left_inj _).2 (finset.sum_congr rfl $ λ p h, det_mul_aux (mem_filter.1 h).2) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : by simp ... = (@univ (perm n) _).sum (λ τ, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (τ i) * N (τ i) i))) : sum_bij (λ p h, equiv.of_bijective (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, eq_of_to_fun_eq rfl⟩) ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * ε τ) * univ.prod (λ j, M (τ j) (σ j)))) : by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * (ε σ * ε τ)) * univ.prod (λ i, M (τ i) i))) : sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _) (λ τ _, have univ.prod (λ j, M (τ j) (σ j)) = univ.prod (λ j, M ((τ * σ⁻¹) j) j), by rw prod_univ_perm σ⁻¹; simp [mul_apply], have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul] ... = ε τ : by simp, by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm]) (λ _ _ _ _, (mul_right_inj _).1) (λ τ _, ⟨τ * σ, by simp⟩)) ... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm] instance : is_monoid_hom (det : matrix n n R → R) := { map_one := det_one, map_mul := det_mul } end matrix
899db5434c9f21876db43f7943baa84fdb8164f7
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/rcases.lean
6ebcbb11ef1c49cf50b9009c4c34329b2823eee1
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
19,438
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.dlist tactic.core open lean lean.parser namespace tactic /- These synonyms for `list` are used to clarify the meanings of the many usages of lists in this module. - `listΣ` is used where a list represents a disjunction, such as the list of possible constructors of an inductive type. - `listΠ` is used where a list represents a conjunction, such as the list of arguments of an individual constructor. These are merely type synonyms, and so are not checked for consistency by the compiler. The `def`/`local notation` combination makes Lean retain these annotations in reported types. -/ @[reducible] def list_Sigma := list @[reducible] def list_Pi := list local notation `listΣ` := list_Sigma local notation `listΠ` := list_Pi @[reducible] meta def goals := list expr meta inductive rcases_patt : Type | one : name → rcases_patt | many : listΣ (listΠ rcases_patt) → rcases_patt meta instance rcases_patt.inhabited : inhabited rcases_patt := ⟨rcases_patt.one `_⟩ meta def rcases_patt.name : rcases_patt → name | (rcases_patt.one n) := n | _ := `_ meta instance rcases_patt.has_reflect : has_reflect rcases_patt | (rcases_patt.one n) := `(_) | (rcases_patt.many l) := `(λ l, rcases_patt.many l).subst $ by haveI := rcases_patt.has_reflect; exact list.reflect l /-- The parser/printer uses an "inverted" meaning for the `many` constructor: rather than representing a sum of products, here it represents a product of sums. We fix this by applying `invert`, defined below, to the result. -/ meta inductive rcases_patt_inverted : Type | one : name → rcases_patt_inverted | many : listΠ (listΣ rcases_patt_inverted) → rcases_patt_inverted meta instance rcases_patt_inverted.inhabited : inhabited rcases_patt_inverted := ⟨rcases_patt_inverted.one `_⟩ meta instance rcases_patt_inverted.has_reflect : has_reflect rcases_patt_inverted | (rcases_patt_inverted.one n) := `(_) | (rcases_patt_inverted.many l) := `(λ l, rcases_patt_inverted.many l).subst $ by haveI := rcases_patt_inverted.has_reflect; exact list.reflect l meta mutual def rcases_patt_inverted.invert, rcases_patt_inverted.invert_list with rcases_patt_inverted.invert : listΣ rcases_patt_inverted → rcases_patt | [rcases_patt_inverted.one n] := rcases_patt.one n | l := rcases_patt.many (rcases_patt_inverted.invert_list l) with rcases_patt_inverted.invert_list : listΣ rcases_patt_inverted → listΣ (listΠ rcases_patt) | l := l.map $ λ p, match p with | rcases_patt_inverted.one n := [rcases_patt.one n] | rcases_patt_inverted.many l := rcases_patt_inverted.invert <$> l end meta mutual def rcases_patt.invert, rcases_patt.invert_many, rcases_patt.invert_list, rcases_patt.invert' with rcases_patt.invert : rcases_patt → listΣ rcases_patt_inverted | (rcases_patt.one n) := [rcases_patt_inverted.one n] | (rcases_patt.many ls) := rcases_patt.invert_many ls with rcases_patt.invert_many : listΣ (listΠ rcases_patt) → listΣ rcases_patt_inverted | [] := [] | [[rcases_patt.many ls@(_::_::_)]] := rcases_patt.invert_many ls | (l::ls) := rcases_patt.invert' l :: rcases_patt.invert_many ls with rcases_patt.invert_list : listΠ rcases_patt → listΠ (listΣ rcases_patt_inverted) | [] := [] | [rcases_patt.many [l@(_::_::_)]] := rcases_patt.invert_list l | (p::l) := rcases_patt.invert p :: rcases_patt.invert_list l with rcases_patt.invert' : listΠ rcases_patt → rcases_patt_inverted | [rcases_patt.one n] := rcases_patt_inverted.one n | [] := rcases_patt_inverted.one `_ | ls := rcases_patt_inverted.many (rcases_patt.invert_list ls) meta mutual def rcases_patt_inverted.format, rcases_patt_inverted.format_list with rcases_patt_inverted.format : rcases_patt_inverted → format | (rcases_patt_inverted.one n) := to_fmt n | (rcases_patt_inverted.many []) := "⟨⟩" | (rcases_patt_inverted.many ls) := "⟨" ++ format.group (format.nest 1 $ format.join $ list.intersperse ("," ++ format.line) $ ls.map (format.group ∘ rcases_patt_inverted.format_list)) ++ "⟩" with rcases_patt_inverted.format_list : listΣ rcases_patt_inverted → opt_param bool ff → format | [] br := "⟨⟩" | [p] br := rcases_patt_inverted.format p | (p::l) br := let fmt := rcases_patt_inverted.format p ++ " |" ++ format.space ++ rcases_patt_inverted.format_list l in if br then format.bracket "(" ")" fmt else fmt meta instance rcases_patt_inverted.has_to_format : has_to_format rcases_patt_inverted := ⟨rcases_patt_inverted.format⟩ meta def rcases_patt.format (p : rcases_patt) (br := ff) : format := rcases_patt_inverted.format_list p.invert br meta instance rcases_patt.has_to_format : has_to_format rcases_patt := ⟨rcases_patt.format⟩ /-- Takes the number of fields of a single constructor and patterns to match its fields against (not necessarily the same number). The returned lists each contain one element per field of the constructor. The `name` is the name which will be used in the top-level `cases` tactic, and the `rcases_patt` is the pattern which the field will be matched against by subsequent `cases` tactics. -/ meta def rcases.process_constructor : nat → listΠ rcases_patt → listΠ name × listΠ rcases_patt | 0 ids := ([], []) | 1 [] := ([`_], [default _]) | 1 [id] := ([id.name], [id]) -- The interesting case: we matched the last field against multiple -- patterns, so split off the remaining patterns into a subsequent -- match. This handles matching `α × β × γ` against `⟨a, b, c⟩`. | 1 ids := ([`_], [rcases_patt.many [ids]]) | (n+1) ids := let (ns, ps) := rcases.process_constructor n ids.tail, p := ids.head in (p.name :: ns, p :: ps) meta def rcases.process_constructors (params : nat) : listΣ name → listΣ (listΠ rcases_patt) → tactic (dlist name × listΣ (name × listΠ rcases_patt)) | [] ids := pure (dlist.empty, []) | (c::cs) ids := do n ← mk_const c >>= get_arity, let (h, t) := (match cs, ids.tail with -- We matched the last constructor against multiple patterns, -- so split off the remaining constructors. This handles matching -- `α ⊕ β ⊕ γ` against `a|b|c`. | [], _::_ := ([rcases_patt.many ids], []) | _, _ := (ids.head, ids.tail) end : _), let (ns, ps) := rcases.process_constructor (n - params) h, (l, r) ← rcases.process_constructors cs t, pure (dlist.of_list ns ++ l, (c, ps) :: r) private def align {α β} (p : α → β → Prop) [∀ a b, decidable (p a b)] : list α → list β → list (α × β) | (a::as) (b::bs) := if p a b then (a, b) :: align as bs else align as (b::bs) | _ _ := [] private meta def get_local_and_type (e : expr) : tactic (expr × expr) := (do t ← infer_type e, pure (t, e)) <|> (do e ← get_local e.local_pp_name, t ← infer_type e, pure (t, e)) meta mutual def rcases_core, rcases.continue with rcases_core : listΣ (listΠ rcases_patt) → expr → tactic goals | ids e := do (t, e) ← get_local_and_type e, t ← whnf t, env ← get_env, let I := t.get_app_fn.const_name, (ids, r, l) ← (if I ≠ `quot then do when (¬env.is_inductive I) $ fail format!"rcases tactic failed: {e} : {I} is not an inductive datatype", let params := env.inductive_num_params I, let c := env.constructors_of I, (ids, r) ← rcases.process_constructors params c ids, l ← cases_core e ids.to_list, return (ids, r, l) else do (ids, r) ← rcases.process_constructors 2 [`quot.mk] ids, [(_, d)] ← induction e ids.to_list `quot.induction_on | fail format!"quotient induction on {e} failed. Maybe goal is not in Prop?", -- the result from `induction` is missing the information that the original constructor was -- `quot.mk` so we fix this up: return (ids, r, [(`quot.mk, d)])), gs ← get_goals, -- `cases_core` may not generate a new goal for every constructor, -- as some constructors may be impossible for type reasons. (See its -- documentation.) Match up the new goals with our remaining work -- by constructor name. list.join <$> (align (λ (a : name × _) (b : _ × name × _), a.1 = b.2.1) r (gs.zip l)).mmap (λ⟨⟨_, ps⟩, g, _, hs, _⟩, set_goals [g] >> rcases.continue (ps.zip hs)) with rcases.continue : listΠ (rcases_patt × expr) → tactic goals | [] := get_goals | ((rcases_patt.many ids, e) :: l) := do gs ← rcases_core ids e, list.join <$> gs.mmap (λ g, set_goals [g] >> rcases.continue l) | ((rcases_patt.one `rfl, e) :: l) := do (t, e) ← get_local_and_type e, subst e, rcases.continue l -- If the pattern is any other name, we already bound the name in the -- top-level `cases` tactic, so there is no more work to do for it. | (_ :: l) := rcases.continue l /-- `rcases h e pat` performs case distinction on `e` using `pat` to name the arising new variables and assumptions. If `h` is `some` name, a new assumption `h : e = pat` will relate the expression `e` with the current pattern. -/ meta def rcases (h : option name) (p : pexpr) (ids : listΣ (listΠ rcases_patt)) : tactic unit := do e ← match h with | some h := do x ← get_unused_name, interactive.generalize h () (p, x), get_local x | none := i_to_expr p end, if e.is_local_constant then focus1 (rcases_core ids e >>= set_goals) else do x ← mk_fresh_name, n ← revert_kdependencies e semireducible, (tactic.generalize e x) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (rcases_core ids h >>= set_goals) meta def rintro (ids : listΠ rcases_patt) : tactic unit := do l ← ids.mmap (λ id, do e ← intro id.name, return (id, e)), focus1 (rcases.continue l >>= set_goals) def merge_list {α} (m : α → α → α) : list α → list α → list α | [] l₂ := l₂ | l₁ [] := l₁ | (a :: l₁) (b :: l₂) := m a b :: merge_list l₁ l₂ meta def rcases_patt.merge : rcases_patt → rcases_patt → rcases_patt | (rcases_patt.many ids₁) (rcases_patt.many ids₂) := rcases_patt.many (merge_list (merge_list rcases_patt.merge) ids₁ ids₂) | (rcases_patt.one `rfl) (rcases_patt.many ids₂) := rcases_patt.many (merge_list (merge_list rcases_patt.merge) [[]] ids₂) | (rcases_patt.many ids₁) (rcases_patt.one `rfl) := rcases_patt.many (merge_list (merge_list rcases_patt.merge) ids₁ [[]]) | (rcases_patt.one `rfl) (rcases_patt.one `rfl) := rcases_patt.one `rfl | (rcases_patt.one `_) p := p | p (rcases_patt.one `_) := p | (rcases_patt.one n) _ := rcases_patt.one n | _ (rcases_patt.one n) := rcases_patt.one n meta mutual def rcases_hint_core, rcases_hint.process_constructors, rcases_hint.continue with rcases_hint_core : ℕ → expr → tactic (rcases_patt × goals) | depth e := do (t, e) ← get_local_and_type e, t ← whnf t, env ← get_env, some l ← try_core (guard (depth ≠ 0) >> cases_core e) | prod.mk (rcases_patt.one e.local_pp_name) <$> get_goals, let I := t.get_app_fn.const_name, if I = ``eq then prod.mk (rcases_patt.one `rfl) <$> get_goals else do let c := env.constructors_of I, gs ← get_goals, (ps, gs') ← rcases_hint.process_constructors (depth - 1) c (gs.zip l), pure (rcases_patt.many ps, gs') with rcases_hint.process_constructors : ℕ → listΣ name → list (expr × name × listΠ expr × list (name × expr)) → tactic (listΣ (listΠ rcases_patt) × goals) | depth [] _ := pure ([], []) | depth cs [] := pure (cs.map (λ _, []), []) | depth (c::cs) ((g, c', hs, _) :: l) := if c ≠ c' then do (ps, gs) ← rcases_hint.process_constructors depth cs l, pure ([] :: ps, gs) else do (p, gs) ← set_goals [g] >> rcases_hint.continue depth hs, (ps, gs') ← rcases_hint.process_constructors depth cs l, pure (p :: ps, gs ++ gs') with rcases_hint.continue : ℕ → listΠ expr → tactic (listΠ rcases_patt × goals) | depth [] := prod.mk [] <$> get_goals | depth (e :: l) := do (p, gs) ← rcases_hint_core depth e, (ps, gs') ← gs.mfoldl (λ (r : listΠ rcases_patt × goals) g, do (ps, gs') ← set_goals [g] >> rcases_hint.continue depth l, pure (merge_list rcases_patt.merge r.1 ps, r.2 ++ gs')) ([], []), pure (p :: ps, gs') meta def rcases_hint (p : pexpr) (depth : nat) : tactic rcases_patt := do e ← i_to_expr p, if e.is_local_constant then focus1 $ do (p, gs) ← rcases_hint_core depth e, set_goals gs, pure p else do x ← mk_fresh_name, n ← revert_kdependencies e semireducible, (tactic.generalize e x) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, pure ()), h ← tactic.intro1, focus1 $ do (p, gs) ← rcases_hint_core depth h, set_goals gs, pure p meta def rintro_hint (depth : nat) : tactic (listΠ rcases_patt) := do l ← intros, focus1 $ do (p, gs) ← rcases_hint.continue depth l, set_goals gs, pure p setup_tactic_parser local notation `listΣ` := list_Sigma local notation `listΠ` := list_Pi meta def rcases_patt_parse_core (rcases_patt_parse_list : parser (listΣ rcases_patt_inverted)) : parser rcases_patt_inverted | x := ((rcases_patt_inverted.one <$> ident_) <|> (rcases_patt_inverted.many <$> brackets "⟨" "⟩" (sep_by (tk ",") rcases_patt_parse_list))) x meta def rcases_patt_parse_list : parser (listΣ rcases_patt_inverted) := with_desc "patt" $ list.cons <$> rcases_patt_parse_core rcases_patt_parse_list <*> (tk "|" *> rcases_patt_parse_core rcases_patt_parse_list)* meta def rcases_patt_parse : parser rcases_patt_inverted := with_desc "patt_list" $ rcases_patt_parse_core rcases_patt_parse_list meta def rcases_parse_depth : parser nat := do o ← (tk ":" *> small_nat)?, pure $ o.get_or_else 5 precedence `?`:max /-- syntax for a `rcases` pattern: `('?' expr (: n)?) | ((h :)? expr (with patt_list)?)` -/ meta def rcases_parse : parser (pexpr × ((option name × listΣ (listΠ rcases_patt)) ⊕ nat)) := with_desc "('?' expr (: n)?) | ((h :)? expr (with patt_list)?)" $ do hint ← (tk "?")?, p ← texpr, match hint with | none := do (h,p) ← (do { expr.local_const h _ _ _ ← pure p, tk ":", prod.mk (some h) <$> texpr } <|> pure (none,p)), ids ← (tk "with" *> rcases_patt_parse_list)?, pure (p, sum.inl (h, rcases_patt_inverted.invert_list (ids.get_or_else [default _]))) | some _ := do depth ← rcases_parse_depth, pure (p, sum.inr depth) end meta def rintro_parse : parser (listΠ rcases_patt ⊕ nat) := with_desc "('?' (: n)?) | patt_list" $ (tk "?" >> sum.inr <$> rcases_parse_depth) <|> sum.inl <$> (rcases_patt_inverted.invert <$> (brackets "(" ")" rcases_patt_parse_list <|> (λ x, [x]) <$> rcases_patt_parse))* meta def ext_patt := listΠ rcases_patt meta def ext_parse : parser ext_patt := (rcases_patt_inverted.invert <$> (brackets "(" ")" rcases_patt_parse_list <|> (λ x, [x]) <$> rcases_patt_parse))* namespace interactive open interactive interactive.types expr /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. `rcases` also has special support for quotient types: quotient induction into Prop works like matching on the constructor `quot.mk`. `rcases h : e with PAT` will do the same as `rcases e with PAT` with the exception that an assumption `h : e = PAT` will be added to the context. `rcases? e` will perform case splits on `e` in the same way as `rcases e`, but rather than accepting a pattern, it does a maximal cases and prints the pattern that would produce this case splitting. The default maximum depth is 5, but this can be modified with `rcases? e : n`. -/ meta def rcases : parse rcases_parse → tactic unit | (p, sum.inl (h, ids)) := tactic.rcases h p ids | (p, sum.inr depth) := do patt ← tactic.rcases_hint p depth, pe ← pp p, trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt /-- The `rintro` tactic is a combination of the `intros` tactic with `rcases` to allow for destructuring patterns while introducing variables. See `rcases` for a description of supported patterns. For example, `rintro (a | ⟨b, c⟩) ⟨d, e⟩` will introduce two variables, and then do case splits on both of them producing two subgoals, one with variables `a d e` and the other with `b c d e`. `rintro?` will introduce and case split on variables in the same way as `rintro`, but will also print the `rintro` invocation that would have the same result. Like `rcases?`, `rintro? : n` allows for modifying the depth of splitting; the default is 5. -/ meta def rintro : parse rintro_parse → tactic unit | (sum.inl []) := intros [] | (sum.inl l) := tactic.rintro l | (sum.inr depth) := do ps ← tactic.rintro_hint depth, trace $ ↑"snippet: rintro" ++ format.join (ps.map $ λ p, format.space ++ format.group (p.format tt)) /-- Alias for `rintro`. -/ meta def rintros := rintro setup_tactic_parser meta def obtain_parse : parser (option (listΣ rcases_patt_inverted) × (option pexpr) × (option pexpr)) := with_desc "patt_list? (: expr)? (:= expr)?" $ do pat ← rcases_patt_parse_list?, tp ← (tk ":" >> texpr)?, val ← (tk ":=" >> texpr)?, return (pat, tp, val) /-- The `obtain` tactic is a combination of `have` and `rcases`. `obtain ⟨patt⟩ : type, { ... }` is equivalent to `have h : type, { ... }, rcases h with ⟨patt⟩`. The syntax `obtain ⟨patt⟩ : type := proof` is also supported. If `⟨patt⟩` is omitted, `rcases` will try to infer the pattern. If `type` is omitted, `:= proof` is required. -/ meta def obtain : interactive.parse obtain_parse → tactic unit | (pat, tp, some val) := tactic.rcases none ``(%%val : %%(tp.get_or_else pexpr.mk_placeholder)) $ rcases_patt_inverted.invert_list (pat.get_or_else [default _]) | (pat, some tp, none) := do nm ← mk_fresh_name, e ← to_expr tp >>= assert nm, (g :: gs) ← get_goals, set_goals gs, tactic.rcases none ``(%%e) $ rcases_patt_inverted.invert_list (pat.get_or_else [default _]), gs ← get_goals, set_goals (g::gs) | (pat, none, none) := fail $ "`obtain` requires either an expected type or a value.\n" ++ "usage: `obtain ⟨patt⟩? : type (:= val)?` or `obtain ⟨patt⟩? (: type)? := val`" end interactive end tactic
82446c2b73f1c1c0f22262c679e66e0f0c07d8c3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/shapes/biproducts.lean
70c836bd537072c9c81beeb352d3e3f1d65bf776
[ "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
37,799
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.binary_products import category_theory.preadditive /-! # Biproducts and binary biproducts We introduce the notion of (finite) biproducts and binary biproducts. These are slightly unusual relative to the other shapes in the library, as they are simultaneously limits and colimits. (Zero objects are similar; they are "biterminal".) We treat first the case of a general category with zero morphisms, and subsequently the case of a preadditive category. In a category with zero morphisms, we model the (binary) biproduct of `P Q : C` using a `binary_bicone`, which has a cone point `X`, and morphisms `fst : X ⟶ P`, `snd : X ⟶ Q`, `inl : P ⟶ X` and `inr : X ⟶ Q`, such that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q`. Such a `binary_bicone` is a biproduct if the cone is a limit cone, and the cocone is a colimit cocone. In a preadditive category, * any `binary_biproduct` satisfies `total : fst ≫ inl + snd ≫ inr = 𝟙 X` * any `binary_product` is a `binary_biproduct` * any `binary_coproduct` is a `binary_biproduct` For biproducts indexed by a `fintype J`, a `bicone` again consists of a cone point `X` and morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. In a preadditive category, * any `biproduct` satisfies `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` * any `product` is a `biproduct` * any `coproduct` is a `biproduct` ## Notation As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for a binary biproduct. We introduce `⨁ f` for the indexed biproduct. -/ noncomputable theory universes v u open category_theory open category_theory.functor namespace category_theory.limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- A `c : bicone F` is: * an object `c.X` and * morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, * such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. -/ @[nolint has_inhabited_instance] structure bicone (F : J → C) := (X : C) (π : Π j, X ⟶ F j) (ι : Π j, F j ⟶ X) (ι_π : ∀ j j', ι j ≫ π j' = if h : j = j' then eq_to_hom (congr_arg F h) else 0) @[simp] lemma bicone_ι_π_self {F : J → C} (B : bicone F) (j : J) : B.ι j ≫ B.π j = 𝟙 (F j) := by simpa using B.ι_π j j @[simp] lemma bicone_ι_π_ne {F : J → C} (B : bicone F) {j j' : J} (h : j ≠ j') : B.ι j ≫ B.π j' = 0 := by simpa [h] using B.ι_π j j' variables {F : J → C} namespace bicone /-- Extract the cone from a bicone. -/ @[simps] def to_cone (B : bicone F) : cone (discrete.functor F) := { X := B.X, π := { app := λ j, B.π j }, } /-- Extract the cocone from a bicone. -/ @[simps] def to_cocone (B : bicone F) : cocone (discrete.functor F) := { X := B.X, ι := { app := λ j, B.ι j }, } end bicone /-- A bicone over `F : J → C`, which is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure limit_bicone (F : J → C) := (bicone : bicone F) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) /-- `has_biproduct F` expresses the mere existence of a bicone which is simultaneously a limit and a colimit of the diagram `F`. -/ class has_biproduct (F : J → C) : Prop := mk' :: (exists_biproduct : nonempty (limit_bicone F)) lemma has_biproduct.mk {F : J → C} (d : limit_bicone F) : has_biproduct F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `biproduct_data F` from `has_biproduct F`. -/ def get_biproduct_data (F : J → C) [has_biproduct F] : limit_bicone F := classical.choice has_biproduct.exists_biproduct /-- A bicone for `F` which is both a limit cone and a colimit cocone. -/ def biproduct.bicone (F : J → C) [has_biproduct F] : bicone F := (get_biproduct_data F).bicone /-- `biproduct.bicone F` is a limit cone. -/ def biproduct.is_limit (F : J → C) [has_biproduct F] : is_limit (biproduct.bicone F).to_cone := (get_biproduct_data F).is_limit /-- `biproduct.bicone F` is a colimit cocone. -/ def biproduct.is_colimit (F : J → C) [has_biproduct F] : is_colimit (biproduct.bicone F).to_cocone := (get_biproduct_data F).is_colimit @[priority 100] instance has_product_of_has_biproduct [has_biproduct F] : has_limit (discrete.functor F) := has_limit.mk { cone := (biproduct.bicone F).to_cone, is_limit := biproduct.is_limit F, } @[priority 100] instance has_coproduct_of_has_biproduct [has_biproduct F] : has_colimit (discrete.functor F) := has_colimit.mk { cocone := (biproduct.bicone F).to_cocone, is_colimit := biproduct.is_colimit F, } variables (J C) /-- `C` has biproducts of shape `J` if we have a limit and a colimit, with the same cone points, of every function `F : J → C`. -/ class has_biproducts_of_shape : Prop := (has_biproduct : Π F : J → C, has_biproduct F) attribute [instance, priority 100] has_biproducts_of_shape.has_biproduct /-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C` indexed by a finite type with decidable equality. -/ class has_finite_biproducts : Prop := (has_biproducts_of_shape : Π (J : Type v) [decidable_eq J] [fintype J], has_biproducts_of_shape J C) attribute [instance, priority 100] has_finite_biproducts.has_biproducts_of_shape @[priority 100] instance has_finite_products_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_products C := λ J _ _, ⟨λ F, by exactI has_limit_of_iso discrete.nat_iso_functor.symm⟩ @[priority 100] instance has_finite_coproducts_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_coproducts C := λ J _ _, ⟨λ F, by exactI has_colimit_of_iso discrete.nat_iso_functor⟩ variables {J C} /-- The isomorphism between the specified limit and the specified colimit for a functor with a bilimit. -/ def biproduct_iso (F : J → C) [has_biproduct F] : limits.pi_obj F ≅ limits.sigma_obj F := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (biproduct.is_limit F)).trans $ is_colimit.cocone_point_unique_up_to_iso (biproduct.is_colimit F) (colimit.is_colimit _) end category_theory.limits namespace category_theory.limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `biproduct f`, you will just use general facts about limits and colimits.) -/ abbreviation biproduct (f : J → C) [has_biproduct f] : C := (biproduct.bicone f).X notation `⨁ ` f:20 := biproduct f /-- The projection onto a summand of a biproduct. -/ abbreviation biproduct.π (f : J → C) [has_biproduct f] (b : J) : ⨁ f ⟶ f b := (biproduct.bicone f).π b @[simp] lemma biproduct.bicone_π (f : J → C) [has_biproduct f] (b : J) : (biproduct.bicone f).π b = biproduct.π f b := rfl /-- The inclusion into a summand of a biproduct. -/ abbreviation biproduct.ι (f : J → C) [has_biproduct f] (b : J) : f b ⟶ ⨁ f := (biproduct.bicone f).ι b @[simp] lemma biproduct.bicone_ι (f : J → C) [has_biproduct f] (b : J) : (biproduct.bicone f).ι b = biproduct.ι f b := rfl @[reassoc] lemma biproduct.ι_π (f : J → C) [has_biproduct f] (j j' : J) : biproduct.ι f j ≫ biproduct.π f j' = if h : j = j' then eq_to_hom (congr_arg f h) else 0 := (biproduct.bicone f).ι_π j j' @[simp,reassoc] lemma biproduct.ι_π_self (f : J → C) [has_biproduct f] (j : J) : biproduct.ι f j ≫ biproduct.π f j = 𝟙 _ := by simp [biproduct.ι_π] @[simp,reassoc] lemma biproduct.ι_π_ne (f : J → C) [has_biproduct f] {j j' : J} (h : j ≠ j') : biproduct.ι f j ≫ biproduct.π f j' = 0 := by simp [biproduct.ι_π, h] /-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/ abbreviation biproduct.lift {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f := (biproduct.is_limit f).lift (fan.mk P p) /-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/ abbreviation biproduct.desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P := (biproduct.is_colimit f).desc (cofan.mk P p) @[simp, reassoc] lemma biproduct.lift_π {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) (j : J) : biproduct.lift p ≫ biproduct.π f j = p j := (biproduct.is_limit f).fac _ _ @[simp, reassoc] lemma biproduct.ι_desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) (j : J) : biproduct.ι f j ≫ biproduct.desc p = p j := (biproduct.is_colimit f).fac _ _ /-- Given a collection of maps between corresponding summands of a pair of biproducts indexed by the same type, we obtain a map between the biproducts. -/ abbreviation biproduct.map [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := is_limit.map (biproduct.bicone f).to_cone (biproduct.is_limit g) (discrete.nat_trans p) /-- An alternative to `biproduct.map` constructed via colimits. This construction only exists in order to show it is equal to `biproduct.map`. -/ abbreviation biproduct.map' [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := is_colimit.map (biproduct.is_colimit f) (biproduct.bicone g).to_cocone (discrete.nat_trans p) @[ext] lemma biproduct.hom_ext {f : J → C} [has_biproduct f] {Z : C} (g h : Z ⟶ ⨁ f) (w : ∀ j, g ≫ biproduct.π f j = h ≫ biproduct.π f j) : g = h := (biproduct.is_limit f).hom_ext w @[ext] lemma biproduct.hom_ext' {f : J → C} [has_biproduct f] {Z : C} (g h : ⨁ f ⟶ Z) (w : ∀ j, biproduct.ι f j ≫ g = biproduct.ι f j ≫ h) : g = h := (biproduct.is_colimit f).hom_ext w lemma biproduct.map_eq_map' [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : biproduct.map p = biproduct.map' p := begin ext j j', simp only [discrete.nat_trans_app, limits.is_colimit.ι_map, limits.is_limit.map_π, category.assoc, ←bicone.to_cone_π_app, ←biproduct.bicone_π, ←bicone.to_cocone_ι_app, ←biproduct.bicone_ι], simp only [biproduct.bicone_ι, biproduct.bicone_π, bicone.to_cocone_ι_app, bicone.to_cone_π_app], rw [biproduct.ι_π_assoc, biproduct.ι_π], split_ifs, { subst h, rw [eq_to_hom_refl, category.id_comp], erw category.comp_id, }, { simp, }, end instance biproduct.ι_mono (f : J → C) [has_biproduct f] (b : J) : split_mono (biproduct.ι f b) := { retraction := biproduct.desc $ λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b } instance biproduct.π_epi (f : J → C) [has_biproduct f] (b : J) : split_epi (biproduct.π f b) := { section_ := biproduct.lift $ λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' } @[simp, reassoc] lemma biproduct.map_π [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π j, f j ⟶ g j) (j : J) : biproduct.map p ≫ biproduct.π g j = biproduct.π f j ≫ p j := limits.is_limit.map_π _ _ _ _ @[simp, reassoc] lemma biproduct.ι_map [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π j, f j ⟶ g j) (j : J) : biproduct.ι f j ≫ biproduct.map p = p j ≫ biproduct.ι g j := begin rw biproduct.map_eq_map', convert limits.is_colimit.ι_map _ _ _ _; refl end variables {C} /-- A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`, maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`, so that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q` -/ @[nolint has_inhabited_instance] structure binary_bicone (P Q : C) := (X : C) (fst : X ⟶ P) (snd : X ⟶ Q) (inl : P ⟶ X) (inr : Q ⟶ X) (inl_fst' : inl ≫ fst = 𝟙 P . obviously) (inl_snd' : inl ≫ snd = 0 . obviously) (inr_fst' : inr ≫ fst = 0 . obviously) (inr_snd' : inr ≫ snd = 𝟙 Q . obviously) restate_axiom binary_bicone.inl_fst' restate_axiom binary_bicone.inl_snd' restate_axiom binary_bicone.inr_fst' restate_axiom binary_bicone.inr_snd' attribute [simp, reassoc] binary_bicone.inl_fst binary_bicone.inl_snd binary_bicone.inr_fst binary_bicone.inr_snd namespace binary_bicone variables {P Q : C} /-- Extract the cone from a binary bicone. -/ def to_cone (c : binary_bicone P Q) : cone (pair P Q) := binary_fan.mk c.fst c.snd @[simp] lemma to_cone_X (c : binary_bicone P Q) : c.to_cone.X = c.X := rfl @[simp] lemma to_cone_π_app_left (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.left) = c.fst := rfl @[simp] lemma to_cone_π_app_right (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.right) = c.snd := rfl /-- Extract the cocone from a binary bicone. -/ def to_cocone (c : binary_bicone P Q) : cocone (pair P Q) := binary_cofan.mk c.inl c.inr @[simp] lemma to_cocone_X (c : binary_bicone P Q) : c.to_cocone.X = c.X := rfl @[simp] lemma to_cocone_ι_app_left (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.left) = c.inl := rfl @[simp] lemma to_cocone_ι_app_right (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.right) = c.inr := rfl end binary_bicone namespace bicone /-- Convert a `bicone` over a function on `walking_pair` to a binary_bicone. -/ @[simps] def to_binary_bicone {X Y : C} (b : bicone (pair X Y).obj) : binary_bicone X Y := { X := b.X, fst := b.π walking_pair.left, snd := b.π walking_pair.right, inl := b.ι walking_pair.left, inr := b.ι walking_pair.right, inl_fst' := by { simp [bicone.ι_π], refl, }, inr_fst' := by simp [bicone.ι_π], inl_snd' := by simp [bicone.ι_π], inr_snd' := by { simp [bicone.ι_π], refl, }, } /-- If the cone obtained from a bicone over `pair X Y` is a limit cone, so is the cone obtained by converting that bicone to a binary_bicone, then to a cone. -/ def to_binary_bicone_is_limit {X Y : C} {b : bicone (pair X Y).obj} (c : is_limit (b.to_cone)) : is_limit (b.to_binary_bicone.to_cone) := { lift := λ s, c.lift s, fac' := λ s j, by { cases j; erw c.fac, }, uniq' := λ s m w, begin apply c.uniq s, rintro (⟨⟩|⟨⟩), exact w walking_pair.left, exact w walking_pair.right, end, } /-- If the cocone obtained from a bicone over `pair X Y` is a colimit cocone, so is the cocone obtained by converting that bicone to a binary_bicone, then to a cocone. -/ def to_binary_bicone_is_colimit {X Y : C} {b : bicone (pair X Y).obj} (c : is_colimit (b.to_cocone)) : is_colimit (b.to_binary_bicone.to_cocone) := { desc := λ s, c.desc s, fac' := λ s j, by { cases j; erw c.fac, }, uniq' := λ s m w, begin apply c.uniq s, rintro (⟨⟩|⟨⟩), exact w walking_pair.left, exact w walking_pair.right, end, } end bicone /-- A bicone over `P Q : C`, which is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure binary_biproduct_data (P Q : C) := (bicone : binary_bicone P Q) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) /-- `has_binary_biproduct P Q` expresses the mere existence of a bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`. -/ class has_binary_biproduct (P Q : C) : Prop := mk' :: (exists_binary_biproduct : nonempty (binary_biproduct_data P Q)) lemma has_binary_biproduct.mk {P Q : C} (d : binary_biproduct_data P Q) : has_binary_biproduct P Q := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `binary_biproduct_data F` from `has_binary_biproduct F`. -/ def get_binary_biproduct_data (P Q : C) [has_binary_biproduct P Q] : binary_biproduct_data P Q := classical.choice has_binary_biproduct.exists_binary_biproduct /-- A bicone for `P Q ` which is both a limit cone and a colimit cocone. -/ def binary_biproduct.bicone (P Q : C) [has_binary_biproduct P Q] : binary_bicone P Q := (get_binary_biproduct_data P Q).bicone /-- `binary_biproduct.bicone P Q` is a limit cone. -/ def binary_biproduct.is_limit (P Q : C) [has_binary_biproduct P Q] : is_limit (binary_biproduct.bicone P Q).to_cone := (get_binary_biproduct_data P Q).is_limit /-- `binary_biproduct.bicone P Q` is a colimit cocone. -/ def binary_biproduct.is_colimit (P Q : C) [has_binary_biproduct P Q] : is_colimit (binary_biproduct.bicone P Q).to_cocone := (get_binary_biproduct_data P Q).is_colimit section variable (C) /-- `has_binary_biproducts C` represents the existence of a bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`. -/ class has_binary_biproducts : Prop := (has_binary_biproduct : Π (P Q : C), has_binary_biproduct P Q) attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct /-- A category with finite biproducts has binary biproducts. This is not an instance as typically in concrete categories there will be an alternative construction with nicer definitional properties. -/ lemma has_binary_biproducts_of_finite_biproducts [has_finite_biproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ P Q, has_binary_biproduct.mk { bicone := (biproduct.bicone (pair P Q).obj).to_binary_bicone, is_limit := bicone.to_binary_bicone_is_limit (biproduct.is_limit _), is_colimit := bicone.to_binary_bicone_is_colimit (biproduct.is_colimit _) } } end variables {P Q : C} instance has_binary_biproduct.has_limit_pair [has_binary_biproduct P Q] : has_limit (pair P Q) := has_limit.mk ⟨_, binary_biproduct.is_limit P Q⟩ instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct P Q] : has_colimit (pair P Q) := has_colimit.mk ⟨_, binary_biproduct.is_colimit P Q⟩ @[priority 100] instance has_binary_products_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_products C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } @[priority 100] instance has_binary_coproducts_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_coproducts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } /-- The isomorphism between the specified binary product and the specified binary coproduct for a pair for a binary biproduct. -/ def biprod_iso (X Y : C) [has_binary_biproduct X Y] : limits.prod X Y ≅ limits.coprod X Y := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (binary_biproduct.is_limit X Y)).trans $ is_colimit.cocone_point_unique_up_to_iso (binary_biproduct.is_colimit X Y) (colimit.is_colimit _) /-- An arbitrary choice of biproduct of a pair of objects. -/ abbreviation biprod (X Y : C) [has_binary_biproduct X Y] := (binary_biproduct.bicone X Y).X notation X ` ⊞ `:20 Y:20 := biprod X Y /-- The projection onto the first summand of a binary biproduct. -/ abbreviation biprod.fst {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ X := (binary_biproduct.bicone X Y).fst /-- The projection onto the second summand of a binary biproduct. -/ abbreviation biprod.snd {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ Y := (binary_biproduct.bicone X Y).snd /-- The inclusion into the first summand of a binary biproduct. -/ abbreviation biprod.inl {X Y : C} [has_binary_biproduct X Y] : X ⟶ X ⊞ Y := (binary_biproduct.bicone X Y).inl /-- The inclusion into the second summand of a binary biproduct. -/ abbreviation biprod.inr {X Y : C} [has_binary_biproduct X Y] : Y ⟶ X ⊞ Y := (binary_biproduct.bicone X Y).inr section variables {X Y : C} [has_binary_biproduct X Y] @[simp] lemma binary_biproduct.bicone_fst : (binary_biproduct.bicone X Y).fst = biprod.fst := rfl @[simp] lemma binary_biproduct.bicone_snd : (binary_biproduct.bicone X Y).snd = biprod.snd := rfl @[simp] lemma binary_biproduct.bicone_inl : (binary_biproduct.bicone X Y).inl = biprod.inl := rfl @[simp] lemma binary_biproduct.bicone_inr : (binary_biproduct.bicone X Y).inr = biprod.inr := rfl end @[simp,reassoc] lemma biprod.inl_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 𝟙 X := (binary_biproduct.bicone X Y).inl_fst @[simp,reassoc] lemma biprod.inl_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 0 := (binary_biproduct.bicone X Y).inl_snd @[simp,reassoc] lemma biprod.inr_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 0 := (binary_biproduct.bicone X Y).inr_fst @[simp,reassoc] lemma biprod.inr_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 𝟙 Y := (binary_biproduct.bicone X Y).inr_snd /-- Given a pair of maps into the summands of a binary biproduct, we obtain a map into the binary biproduct. -/ abbreviation biprod.lift {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⊞ Y := (binary_biproduct.is_limit X Y).lift (binary_fan.mk f g) /-- Given a pair of maps out of the summands of a binary biproduct, we obtain a map out of the binary biproduct. -/ abbreviation biprod.desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⊞ Y ⟶ W := (binary_biproduct.is_colimit X Y).desc (binary_cofan.mk f g) @[simp, reassoc] lemma biprod.lift_fst {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift f g ≫ biprod.fst = f := (binary_biproduct.is_limit X Y).fac _ walking_pair.left @[simp, reassoc] lemma biprod.lift_snd {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift f g ≫ biprod.snd = g := (binary_biproduct.is_limit X Y).fac _ walking_pair.right @[simp, reassoc] lemma biprod.inl_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : biprod.inl ≫ biprod.desc f g = f := (binary_biproduct.is_colimit X Y).fac _ walking_pair.left @[simp, reassoc] lemma biprod.inr_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : biprod.inr ≫ biprod.desc f g = g := (binary_biproduct.is_colimit X Y).fac _ walking_pair.right instance biprod.mono_lift_of_mono_left {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (biprod.lift f g) := mono_of_mono_fac $ biprod.lift_fst _ _ instance biprod.mono_lift_of_mono_right {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (biprod.lift f g) := mono_of_mono_fac $ biprod.lift_snd _ _ instance biprod.epi_desc_of_epi_left {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (biprod.desc f g) := epi_of_epi_fac $ biprod.inl_desc _ _ instance biprod.epi_desc_of_epi_right {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (biprod.desc f g) := epi_of_epi_fac $ biprod.inr_desc _ _ /-- Given a pair of maps between the summands of a pair of binary biproducts, we obtain a map between the binary biproducts. -/ abbreviation biprod.map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := is_limit.map (binary_biproduct.bicone W X).to_cone (binary_biproduct.is_limit Y Z) (@map_pair _ _ (pair W X) (pair Y Z) f g) /-- An alternative to `biprod.map` constructed via colimits. This construction only exists in order to show it is equal to `biprod.map`. -/ abbreviation biprod.map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := is_colimit.map (binary_biproduct.is_colimit W X) (binary_biproduct.bicone Y Z).to_cocone (@map_pair _ _ (pair W X) (pair Y Z) f g) @[ext] lemma biprod.hom_ext {X Y Z : C} [has_binary_biproduct X Y] (f g : Z ⟶ X ⊞ Y) (h₀ : f ≫ biprod.fst = g ≫ biprod.fst) (h₁ : f ≫ biprod.snd = g ≫ biprod.snd) : f = g := binary_fan.is_limit.hom_ext (binary_biproduct.is_limit X Y) h₀ h₁ @[ext] lemma biprod.hom_ext' {X Y Z : C} [has_binary_biproduct X Y] (f g : X ⊞ Y ⟶ Z) (h₀ : biprod.inl ≫ f = biprod.inl ≫ g) (h₁ : biprod.inr ≫ f = biprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (binary_biproduct.is_colimit X Y) h₀ h₁ lemma biprod.map_eq_map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g = biprod.map' f g := begin ext, { simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, biprod.inl_fst_assoc, category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst, ←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl], simp }, { simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, zero_comp, biprod.inl_snd_assoc, category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd, ←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl], simp }, { simp only [map_pair_right, biprod.inr_fst_assoc, is_colimit.ι_map, is_limit.map_π, zero_comp, category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst, ←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr], simp }, { simp only [map_pair_right, is_colimit.ι_map, is_limit.map_π, biprod.inr_snd_assoc, category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd, ←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr], simp } end instance biprod.inl_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inl : X ⟶ X ⊞ Y) := { retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) } instance biprod.inr_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inr : Y ⟶ X ⊞ Y) := { retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)} instance biprod.fst_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.fst : X ⊞ Y ⟶ X) := { section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) } instance biprod.snd_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.snd : X ⊞ Y ⟶ Y) := { section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) } @[simp,reassoc] lemma biprod.map_fst {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.fst = biprod.fst ≫ f := is_limit.map_π _ _ _ walking_pair.left @[simp,reassoc] lemma biprod.map_snd {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.snd = biprod.snd ≫ g := is_limit.map_π _ _ _ walking_pair.right -- Because `biprod.map` is defined in terms of `lim` rather than `colim`, -- we need to provide additional `simp` lemmas. @[simp,reassoc] lemma biprod.inl_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inl ≫ biprod.map f g = f ≫ biprod.inl := begin rw biprod.map_eq_map', exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ walking_pair.left end @[simp,reassoc] lemma biprod.inr_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inr ≫ biprod.map f g = g ≫ biprod.inr := begin rw biprod.map_eq_map', exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ walking_pair.right end /-- Given a pair of isomorphisms between the summands of a pair of binary biproducts, we obtain an isomorphism between the binary biproducts. -/ @[simps] def biprod.map_iso {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⊞ X ≅ Y ⊞ Z := { hom := biprod.map f.hom g.hom, inv := biprod.map f.inv g.inv } section variables [has_binary_biproducts C] /-- The braiding isomorphism which swaps a binary biproduct. -/ @[simps] def biprod.braiding (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.lift biprod.snd biprod.fst, inv := biprod.lift biprod.snd biprod.fst } /-- An alternative formula for the braiding isomorphism which swaps a binary biproduct, using the fact that the biproduct is a coproduct. -/ @[simps] def biprod.braiding' (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.desc biprod.inr biprod.inl, inv := biprod.desc biprod.inr biprod.inl } lemma biprod.braiding'_eq_braiding {P Q : C} : biprod.braiding' P Q = biprod.braiding P Q := by tidy /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma biprod.braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : biprod.map f g ≫ (biprod.braiding _ _).hom = (biprod.braiding _ _).hom ≫ biprod.map g f := by tidy @[reassoc] lemma biprod.braiding_map_braiding {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : (biprod.braiding X W).hom ≫ biprod.map f g ≫ (biprod.braiding Y Z).hom = biprod.map g f := by tidy @[simp, reassoc] lemma biprod.symmetry' (P Q : C) : biprod.lift biprod.snd biprod.fst ≫ biprod.lift biprod.snd biprod.fst = 𝟙 (P ⊞ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma biprod.symmetry (P Q : C) : (biprod.braiding P Q).hom ≫ (biprod.braiding Q P).hom = 𝟙 _ := by simp end -- TODO: -- If someone is interested, they could provide the constructions: -- has_binary_biproducts ↔ has_finite_biproducts end category_theory.limits namespace category_theory.limits section preadditive variables {C : Type u} [category.{v} C] [preadditive C] variables {J : Type v} [decidable_eq J] [fintype J] open category_theory.preadditive open_locale big_operators /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : has_biproduct f := has_biproduct.mk { bicone := b, is_limit := { lift := λ s, ∑ j, s.π.app j ≫ b.ι j, uniq' := λ s m h, begin erw [←category.comp_id m, ←total, comp_sum], apply finset.sum_congr rfl, intros j m, erw [reassoc_of (h j)], end, fac' := λ s j, begin simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite], -- See note [dsimp, simp]. dsimp, simp, end }, is_colimit := { desc := λ s, ∑ j, b.π j ≫ s.ι.app j, uniq' := λ s m h, begin erw [←category.id_comp m, ←total, sum_comp], apply finset.sum_congr rfl, intros j m, erw [category.assoc, h], end, fac' := λ s j, begin simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp], dsimp, simp, end } } /-- In a preadditive category, if the product over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_product (f : J → C) [has_product f] : has_biproduct f := has_biproduct_of_total { X := pi_obj f, π := limits.pi.π f, ι := λ j, pi.lift (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0), ι_π := λ j j', by simp, } (by { ext, simp [sum_comp, comp_dite] }) /-- In a preadditive category, if the coproduct over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_coproduct (f : J → C) [has_coproduct f] : has_biproduct f := has_biproduct_of_total { X := sigma_obj f, π := λ j, sigma.desc (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0), ι := limits.sigma.ι f, ι_π := λ j j', by simp, } begin ext, simp only [comp_sum, limits.colimit.ι_desc_assoc, eq_self_iff_true, limits.colimit.ι_desc, category.comp_id], dsimp, simp only [dite_comp, finset.sum_dite_eq, finset.mem_univ, if_true, category.id_comp, eq_to_hom_refl, zero_comp], end /-- A preadditive category with finite products has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_products [has_finite_products C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_product _ }⟩ /-- A preadditive category with finite coproducts has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_coproduct _ }⟩ section variables {f : J → C} [has_biproduct f] /-- In any preadditive category, any biproduct satsifies `∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` -/ @[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) := begin ext j j', simp [comp_sum, sum_comp, biproduct.ι_π, comp_dite, dite_comp], end lemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} : biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j := begin ext j, simp [sum_comp, biproduct.ι_π, comp_dite], end lemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} : biproduct.desc g = ∑ j, biproduct.π f j ≫ g j := begin ext j, simp [comp_sum, biproduct.ι_π_assoc, dite_comp], end @[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} : biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j := by simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc, comp_dite, dite_comp] lemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} : biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j := begin ext, simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp], end end /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := b, is_limit := { lift := λ s, binary_fan.fst s ≫ b.inl + binary_fan.snd s ≫ b.inr, uniq' := λ s m h, by erw [←category.comp_id m, ←total, comp_add, reassoc_of (h walking_pair.left), reassoc_of (h walking_pair.right)], fac' := λ s j, by cases j; simp, }, is_colimit := { desc := λ s, b.fst ≫ binary_cofan.inl s + b.snd ≫ binary_cofan.inr s, uniq' := λ s m h, by erw [←category.id_comp m, ←total, add_comp, category.assoc, category.assoc, h walking_pair.left, h walking_pair.right], fac' := λ s j, by cases j; simp, } } /-- In a preadditive category, if the product of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] : has_binary_biproduct X Y := has_binary_biproduct_of_total { X := X ⨯ Y, fst := category_theory.limits.prod.fst, snd := category_theory.limits.prod.snd, inl := prod.lift (𝟙 X) 0, inr := prod.lift 0 (𝟙 Y) } begin ext; simp [add_comp], end /-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_products [has_binary_products C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, } /-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] : has_binary_biproduct X Y := has_binary_biproduct_of_total { X := X ⨿ Y, fst := coprod.desc (𝟙 X) 0, snd := coprod.desc 0 (𝟙 Y), inl := category_theory.limits.coprod.inl, inr := category_theory.limits.coprod.inr } begin ext; simp [add_comp], end /-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, } section variables {X Y : C} [has_binary_biproduct X Y] /-- In any preadditive category, any binary biproduct satsifies `biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`. -/ @[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) := begin ext; simp [add_comp], end lemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} : biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr := begin ext; simp [add_comp], end lemma biprod.desc_eq {T : C} {f : X ⟶ T} {g : Y ⟶ T} : biprod.desc f g = biprod.fst ≫ f + biprod.snd ≫ g := begin ext; simp [add_comp], end @[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} : biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i := by simp [biprod.lift_eq, biprod.desc_eq] lemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} : biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr := by apply biprod.hom_ext; apply biprod.hom_ext'; simp end end preadditive end category_theory.limits
a49c24bbb0d617afade2d9dc9f7a35f6337807f8
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Meta/TransparencyMode.lean
44ebf8acaa1d256fb9df09d1401e57b9662e655e
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
810
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 -/ namespace Lean.Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq namespace TransparencyMode def hash : TransparencyMode → USize | all => 7 | default => 11 | reducible => 13 | instances => 17 instance : Hashable TransparencyMode := ⟨hash⟩ def lt : TransparencyMode → TransparencyMode → Bool | reducible, default => true | reducible, all => true | reducible, instances => true | instances, default => true | instances, all => true | default, all => true | _, _ => false end TransparencyMode end Lean.Meta
dafb8f0d3d6ade48ec30b986b5c8fd303633dd39
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/stone_separation.lean
016748b8b6545073ab0c1f02b7a68c1df404d3a4
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
1,709
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simplicial_complex.convex_join open set variables {E : Type*} [add_comm_group E] [module ℝ E] {x y : E} {A B : set E} {c : set (set E)} /-- Stone's Separation Theorem -/ lemma subsets_compl_convexes (hA : convex A) (hB : convex B) (hAB : disjoint A B) : ∃ C : set E, convex C ∧ convex Cᶜ ∧ A ⊆ C ∧ B ⊆ Cᶜ := begin sorry /- let S : set (set E) := {C | convex C ∧ C ⊆ Bᶜ}, obtain ⟨C, hC, hAC, hCmax⟩ := zorn.zorn_subset_nonempty S (λ c hcS hc ⟨B, hB⟩, ⟨⋃₀c, ⟨(zorn.chain.directed_on hc).convex_sUnion (λ A hA, (hcS hA).1), sUnion_subset (λ C hC, (hcS hC).2)⟩, λ s, subset_sUnion_of_mem⟩) A ⟨hA, disjoint_iff_subset_compl_right.1 hAB⟩, refine ⟨C, hC.1, _, hAC, subset_compl_comm.1 hC.2⟩, rw convex_iff_segment_subset, rintro x y hx hy z hz hzC, suffices h : ∀ c ∈ Cᶜ, ∃ a ∈ C, (segment c a ∩ B).nonempty, { obtain ⟨p, hp, u, huC, huB⟩ := h x hx, obtain ⟨q, hq, v, hvC, hvB⟩ := h y hy, rw disjoint_iff_subset_compl_left at hAB, apply hAB, sorry }, rintro c hc, by_contra, push_neg at h, suffices h : convex_hull (insert c C) ⊆ Bᶜ, { rw ←hCmax _ ⟨convex_convex_hull _, h⟩ (subset.trans (subset_insert _ _) (subset_convex_hull _)) at hc, exact hc (subset_convex_hull _ (mem_insert _ _)) }, rw convex_hull_insert ⟨z, hzC⟩, refine bUnion_subset _, rintro a ha b hb hbB, rw convex.convex_hull_eq hC.1 at ha, exact h a ha ⟨b, hb, hbB⟩, -/ end
1e9b08dd4889f74d633e77640ffb692f1091616b
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/order/conditionally_complete_lattice.lean
a895422a829412e5f83a300cfe531119f6feee50
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
27,955
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 Adapted from the corresponding theory for complete lattices. -/ import data.nat.enat /-! # Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ set_option old_structure_cmd true open set universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} section /-! Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α` -/ open_locale classical noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) := ⟨λ S, if ⊤ ∈ S then ⊤ else if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩ noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) := ⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩ noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) := ⟨(@with_top.has_Inf (order_dual α) _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.has_Sup (order_dual α) _ _).Sup⟩ end -- section section prio set_option default_priority 100 -- see Note [default priority] /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α class conditionally_complete_linear_order_bot (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) end prio /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α› } @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹_› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹_› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_cSup ne hb) theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_cInf ne hb) lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any `w<b`.-/ theorem cSup_intro (_ : s.nonempty) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹_› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any `w>b`.-/ theorem cInf_intro (_ : s.nonempty) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹_› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := is_least_singleton.cInf_eq /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_cInf sne hs).union (is_glb_cInf tne ht)).cInf_eq sne.inl /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le hst, simp only [le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s ∩ t).nonempty) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf hst, simp only [and_imp, set.mem_inter_eq, sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s := ((is_glb_cInf sne hs).insert a).cInf_eq (insert_nonempty a s) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : ι → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g := begin classical, by_cases hι : nonempty ι, { have Rf : (range f).nonempty := range_nonempty _, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = ∅, from range_eq_empty.2 hι, have Rg : range g = ∅, from range_eq_empty.2 hι, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c := cSup_le (range_nonempty f) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : ι → α} (H : bdd_above (range f)) (c : ι) : f c ≤ supr f := le_cSup H (mem_range_self _) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : ι → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g := begin classical, by_cases hι : nonempty ι, { have Rg : (range g).nonempty, from range_nonempty _, apply le_cInf Rg, rintros y ⟨x, rfl⟩, have : f x ∈ range f := ⟨x, rfl⟩, exact cInf_le_of_le B this (H x) }, { have Rf : range f = ∅, from range_eq_empty.2 hι, have Rg : range g = ∅, from range_eq_empty.2 hι, unfold infi, rw [Rf, Rg] } end /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f := le_cInf (range_nonempty f) (by rwa forall_range_iff) /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) (c : ι) : infi f ≤ f c := cInf_le H (mem_range_self _) @[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, cInf_singleton] @[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b:ι, a) = a := by rw [supr, range_const, cSup_singleton] end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃a∈s, b < a := begin classical, contrapose! hb, exact cSup_le hs hb end /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) : ∃i, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃a∈s, a < b := begin classical, contrapose! hb, exact le_cInf hs hb end /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) : (∃i, f i < a) := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt (range_nonempty f) h in ⟨i, h⟩ /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_intro' (_ : s.nonempty) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := le_antisymm (show Sup s ≤ b, from cSup_le ‹s.nonempty› h_is_ub) (show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty end conditionally_complete_linear_order_bot section open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := infer_instance noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_nat_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ), .. (infer_instance : decidable_linear_order ℕ) } end namespace with_top open_locale classical variables [conditionally_complete_linear_order_bot α] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact _root_.le_refl _ }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact _root_.le_refl _ }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, show is_lub ∅ (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊤ }, { exact (h ⟨a, ha⟩).elim }}, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use ⊥, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin cases s.eq_empty_or_nonempty with hs hs, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s.nonempty) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top namespace enat open_locale classical noncomputable instance : complete_linear_order enat := { Sup := λ s, with_top_equiv.symm $ Sup (with_top_equiv '' s), Inf := λ s, with_top_equiv.symm $ Inf (with_top_equiv '' s), le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa, Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa, Sup_le := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply Sup_le _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, le_Inf := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply le_Inf _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, ..enat.decidable_linear_order, ..enat.bounded_lattice } end enat section order_dual instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice (order_dual α) := { le_cSup := @cInf_le α _, cSup_le := @le_cInf α _, le_cInf := @cSup_le α _, cInf_le := @le_cSup α _, ..order_dual.has_Inf α, ..order_dual.has_Sup α, ..order_dual.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order (order_dual α) := { ..order_dual.conditionally_complete_lattice α, ..order_dual.decidable_linear_order α } end order_dual section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot α)` If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that for α a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes the unboundedness problem and the extension to `with_bot α` fixes the problem with the empty set. This result can be used to show that the extended reals [-∞, ∞] are a complete lattice. -/ open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_top α) := { le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.has_Sup, ..with_top.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_bot α) := { le_cSup := (@with_top.conditionally_complete_lattice (order_dual α) _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice (order_dual α) _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } /-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/ noncomputable instance with_top.with_bot.bounded_lattice {α : Type*} [conditionally_complete_lattice α] : bounded_lattice (with_top (with_bot α)) := { ..with_top.order_bot, ..with_top.order_top, ..conditionally_complete_lattice.to_lattice _ } theorem with_bot.cSup_empty {α : Type*} [conditionally_complete_lattice α] : Sup (∅ : set (with_bot α)) = ⊥ := begin show ite _ _ _ = ⊥, split_ifs; finish, end noncomputable instance with_top.with_bot.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := λ S a ha, begin cases S.eq_empty_or_nonempty with h, { show ite _ _ _ ≤ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := λ S a haS, show ite _ _ _ ≤ a, begin split_ifs, { cases a with a, exact _root_.le_refl _, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } } end, le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.has_Inf, ..with_top.has_Sup, ..with_top.with_bot.bounded_lattice } end with_top_bot
1f79ce9ae8f7b8bbfa852a705b1b9907321bde6f
99b5e6372af1f404777312358869f95be7de84a3
/src/hott/types/fiber.lean
e766675b6ab0d86c943248a220f83ae11310c3d1
[ "Apache-2.0" ]
permissive
forked-from-1kasper/hott3
8fa064ab5e8c9d6752a783d74ab226ddc5b5232a
2db24de7a361a7793b0eae4ca5c3fd4d4a0fc691
refs/heads/master
1,584,867,131,028
1,530,766,841,000
1,530,766,841,000
139,797,034
0
0
Apache-2.0
1,530,766,961,000
1,530,766,961,000
null
UTF-8
Lean
false
false
18,785
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mike Shulman Ported from Coq HoTT Theorems about fibers -/ import .sigma .eq .pi ..cubical.squareover .pointed .eq universes u v w hott_theory namespace hott open hott.equiv hott.sigma hott.eq hott.pi hott.pointed hott.is_equiv structure fiber {A B : Type _} (f : A → B) (b : B) := (point : A) (point_eq : f point = b) namespace fiber variables {A : Type _} {B : Type _} {f : A → B} {b : B} @[hott] protected def sigma_char (f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) := begin fapply equiv.MK, {intro x, exact ⟨point x, point_eq x⟩}, {intro x, exact (fiber.mk x.1 x.2)}, {intro x, cases x, apply idp }, {intro x, cases x, apply idp }, end @[hott, hsimp] def sigma_char_mk_snd {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b) : ((fiber.sigma_char f b) ⟨ a , p ⟩).snd = p := refl _ @[hott, hsimp] def sigma_char_mk_fst {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b) : ((fiber.sigma_char f b) ⟨ a , p ⟩).fst = a := refl _ @[hott] def fiber_eq_equiv (x y : fiber f b) : (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) := begin apply equiv.trans, apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char, apply equiv.trans, apply sigma_eq_equiv, apply sigma_equiv_sigma_right, intro p, apply eq_pathover_equiv_Fl, end @[hott] def fiber_eq {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : x = y := to_inv (fiber_eq_equiv _ _) ⟨p, q⟩ @[hott] def fiber_pathover {X : Type _} {A B : X → Type _} {x₁ x₂ : X} {p : x₁ = x₂} {f : Πx, A x → B x} {b : Πx, B x} {v₁ : fiber (f x₁) (b x₁)} {v₂ : fiber (f x₂) (b x₂)} (q : point v₁ =[p] point v₂) (r : squareover B hrfl (pathover_idp_of_eq _ (point_eq v₁)) (pathover_idp_of_eq _ (point_eq v₂)) (apo f q) (apd b p)) : v₁ =[p; λ x, fiber (f x) (b x)] v₂ := begin apply (pathover_of_fn_pathover_fn (λ (x : X), @fiber.sigma_char (A x) (B x) (f x) (b x))), dsimp, fapply sigma_pathover; dsimp, { exact q}, { induction v₁ with a₁ p₁, induction v₂ with a₂ p₂, dsimp at *, induction q, apply pathover_idp_of_eq, apply eq_of_vdeg_square, dsimp[hrfl] at r, dsimp[apo, apd] at r, exact (square_of_squareover_ids B r)} end open is_trunc @[hott] def π₁ {B : A → Type _} : (Σa, B a) → A := sigma.fst @[hott] def fiber_pr1 (B : A → Type _) (a : A) : fiber (π₁ : (Σa, B a) → A) a ≃ B a := calc fiber π₁ a ≃ Σ(u : Σ a, B a), (π₁ u) = a : fiber.sigma_char _ _ ... ≃ Σ (a' : A) (b : B a'), a' = a : (sigma_assoc_equiv (λ (u : Σ a, B a), (π₁ u) = a) ) ⁻¹ᵉ ... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', comm_equiv_nondep _ _) ... ≃ Σ(w : Σ a', a'=a), B (π₁ w) : sigma_assoc_equiv (λ (w : Σ a', a'=a), B (π₁ w)) ... ≃ B a : sigma_equiv_of_is_contr_left (λ (w : Σ a', a'=a), B (π₁ w)) @[hott] def sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A := calc (Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, fiber.sigma_char _ b) ... ≃ Σa b, f a = b : sigma_comm_equiv _ ... ≃ A : sigma_equiv_of_is_contr_right _ @[hott, instance] def is_pointed_fiber (f : A → B) (a : A) : pointed (fiber f (f a)) := pointed.mk (fiber.mk a idp) @[hott] def pointed_fiber (f : A → B) (a : A) : Type* := pointed.Mk (fiber.mk a (idpath (f a))) @[hott, reducible] def is_trunc_fun (n : ℕ₋₂) (f : A → B) := Π(b : B), is_trunc n (fiber f b) @[hott, reducible] def is_contr_fun (f : A → B) := is_trunc_fun -2 f -- pre and post composition with equivalences open function variable (f) @[hott] protected def equiv_postcompose {B' : Type _} (g : B ≃ B') --[H : is_equiv g] (b : B) : fiber (g ∘ f) (g b) ≃ fiber f b := calc fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char _ _ ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma_right, intro a, apply equiv.symm, apply eq_equiv_fn_eq end ... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott] protected def equiv_precompose {A' : Type _} (g : A' ≃ A) --[H : is_equiv g] (b : B) : fiber (f ∘ g) b ≃ fiber f b := calc fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char _ _ ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma g, intro a', apply erfl end ... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ end fiber open unit is_trunc pointed namespace fiber @[hott] def fiber_star_equiv (A : Type _) : fiber (λx : A, star) star ≃ A := begin fapply equiv.MK, { intro f, cases f with a H, exact a }, { intro a, apply fiber.mk a, reflexivity }, { intro a, reflexivity }, { intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H, rwr [is_set.elim H (refl star)] } end @[hott] def fiber_const_equiv (A : Type _) (a₀ : A) (a : A) : fiber (λz : unit, a₀) a ≃ a₀ = a := calc fiber (λz : unit, a₀) a ≃ Σz : unit, a₀ = a : fiber.sigma_char _ _ ... ≃ a₀ = a : sigma_unit_left _ -- the pointed fiber of a pointed map, which is the fiber over the basepoint open pointed @[hott] def pfiber {X Y : Type*} (f : X →* Y) : Type* := pointed.MK (fiber f pt) (fiber.mk pt (respect_pt _)) @[hott] def ppoint {X Y : Type*} (f : X →* Y) : pfiber f →* X := pmap.mk point idp @[hott] def pfiber.sigma_char {A B : Type*} (f : A →* B) : pfiber f ≃* pointed.MK (Σa, f a = pt) ⟨pt, respect_pt f⟩ := pequiv_of_equiv (fiber.sigma_char f pt) idp @[hott, hsimp] def pfiber.sigma_char_mk_snd {A B : Type*} (f : A →* B) (a : A) (p : f a = pt) : ((pfiber.sigma_char f).to_pmap ⟨ a , p ⟩).snd = p := refl _ @[hott] def pointed_fst {A : Type*} (B : A → Type) (pt_B : B pt) : pointed.MK (Σa, B a) ⟨pt, pt_B⟩ →* A := pmap.mk π₁ (refl _) @[hott] def ppoint_sigma_char {A B : Type*} (f : A →* B) : ppoint f ~* (pointed_fst _ _) ∘* (pfiber.sigma_char f).to_pmap := phomotopy.refl _ @[hott] def pfiber_pequiv_of_phomotopy {A B : Type*} {f g : A →* B} (h : f ~* g) : pfiber f ≃* pfiber g := begin fapply pequiv_of_equiv, { refine (fiber.sigma_char f pt ⬝e _ ⬝e (fiber.sigma_char g pt)⁻¹ᵉ), apply sigma_equiv_sigma_right, intros a, apply equiv_eq_closed_left, apply (to_homotopy h) }, { refine (fiber_eq rfl _), change (h pt)⁻¹ ⬝ respect_pt f = idp ⬝ respect_pt g, rwr idp_con, apply inv_con_eq_of_eq_con, symmetry, exact (to_homotopy_pt h) } end @[hott] def transport_fiber_equiv {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2) : fiber f b1 ≃ fiber f b2 := calc fiber f b1 ≃ Σa, f a = b1 : fiber.sigma_char _ _ ... ≃ Σa, f a = b2 : sigma_equiv_sigma_right (λa, equiv_eq_closed_right (f a) p) ... ≃ fiber f b2 : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott,hsimp] def transport_fiber_equiv_mk {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2) (a : A) (q : f a = b1) : (transport_fiber_equiv f p) ⟨ a , q ⟩ = ⟨ a , q ⬝ p ⟩ := begin induction p, induction q, refl end @[hott, hsimp] def snd_point_pfiber_eq_respect_pt {A B : Type*} (f : A →* B) : (pfiber f).Point = ⟨ pt , respect_pt f ⟩ := by refl @[hott] def pequiv_postcompose {A B B' : Type*} (f : A →* B) (g : B ≃* B') : pfiber (g.to_pmap ∘* f) ≃* pfiber f := begin fapply pequiv_of_equiv, refine transport_fiber_equiv (g.to_pmap ∘* f) (respect_pt g.to_pmap)⁻¹ ⬝e fiber.equiv_postcompose f (equiv_of_pequiv g) (Point B), dsimp, apply (ap (fiber.mk (Point A))), refine (con.assoc _ _ _) ⬝ _, apply inv_con_eq_of_eq_con, dsimp, rwr [con.assoc, eq.con.right_inv, con_idp, ← ap_compose], exact ap_con_eq_con (λ x, ap g⁻¹ᵉ*.to_pmap (ap g.to_pmap (pleft_inv' g x)⁻¹) ⬝ ap g⁻¹ᵉ*.to_pmap (pright_inv g (g.to_pmap x)) ⬝ pleft_inv' g x) (respect_pt f) end @[hott] def pequiv_precompose {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : pfiber (f ∘* g.to_pmap) ≃* pfiber f := begin fapply pequiv_of_equiv, refine fiber.equiv_precompose f (equiv_of_pequiv g) (Point B), apply (eq_of_fn_eq_fn (fiber.sigma_char _ _)), fapply sigma_eq, { apply respect_pt g.to_pmap }, { apply eq_pathover_Fl' } end @[hott] def pfiber_pequiv_of_square {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : pfiber f ≃* pfiber g := calc pfiber f ≃* pfiber (k.to_pmap ∘* f) : (pequiv_postcompose f k) ⁻¹ᵉ* ... ≃* pfiber (g ∘* h.to_pmap) : pfiber_pequiv_of_phomotopy s ... ≃* pfiber g : (pequiv_precompose _ _) @[hott] def pcompose_ppoint {A B : Type*} (f : A →* B) : f ∘* ppoint f ~* pconst (pfiber f) B := begin fapply phomotopy.mk, { exact point_eq }, { exact !idp_con⁻¹ } end @[hott] def point_fiber_eq {A B : Type _} {f : A → B} {b : B} {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : ap point (fiber_eq p q) = p := begin induction x with a γ, induction y with a' γ', dsimp at p q, induction p, induction γ', dsimp at q, hinduction q using eq.rec_symm, reflexivity end @[hott] def fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} (x y : fiber f b) : x = y ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) := calc x = y ≃ fiber.sigma_char f b x = fiber.sigma_char f b y : eq_equiv_fn_eq_of_equiv (fiber.sigma_char f b) x y ... ≃ Σ(p : point x = point y), point_eq x =[p; λ z, f z = b] point_eq y : sigma_eq_equiv _ _ ... ≃ Σ(p : point x = point y), (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : sigma_equiv_sigma_right (λp, calc point_eq x =[p; λ z, f z = b] point_eq y ≃ point_eq x = ap f p ⬝ point_eq y : eq_pathover_equiv_Fl _ _ _ ... ≃ ap f p ⬝ point_eq y = point_eq x : eq_equiv_eq_symm _ _ ... ≃ (point_eq x)⁻¹ ⬝ (ap f p ⬝ point_eq y) = idp : eq_equiv_inv_con_eq_idp _ _ ... ≃ (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : equiv_eq_closed_left _ (con.assoc _ _ _) ⁻¹) ... ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott] def loop_pfiber {A B : Type*} (f : A →* B) : Ω (pfiber f) ≃* pfiber (Ω→ f) := pequiv_of_equiv (fiber_eq_equiv_fiber (Point (pfiber f)) (Point (pfiber f))) begin induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity end @[hott] def pfiber_loop_space {A B : Type*} (f : A →* B) : pfiber (Ω→ f) ≃* Ω (pfiber f) := (loop_pfiber f)⁻¹ᵉ* @[hott] def point_fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} {x y : fiber f b} (p : x = y) : point (fiber_eq_equiv_fiber x y p) = ap1_gen point idp idp p := by induction p; reflexivity @[hott] lemma ppoint_loop_pfiber {A B : Type*} (f : A →* B) : ppoint (Ω→ f) ∘* (loop_pfiber f).to_pmap ~* Ω→ (ppoint f) := phomotopy.mk (point_fiber_eq_equiv_fiber) begin induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity end @[hott] lemma ppoint_loop_pfiber_inv {A B : Type*} (f : A →* B) : Ω→ (ppoint f) ∘* ((loop_pfiber f)⁻¹ᵉ*).to_pmap ~* ppoint (Ω→ f) := (phomotopy_pinv_right_of_phomotopy (ppoint_loop_pfiber f))⁻¹* @[hott] def pfiber_pequiv_of_phomotopy_ppoint {A B : Type*} {f g : A →* B} (h : f ~* g) : ppoint g ∘* (pfiber_pequiv_of_phomotopy h).to_pmap ~* ppoint f := begin induction f with f f₀, induction g with g g₀, induction h with h h₀, induction B with B b₀, induction A with A a₀, dsimp at *, induction g₀, dsimp [respect_pt] at h₀, induction h₀, dsimp [ppoint], fapply phomotopy.mk, { reflexivity }, { refine idp_con _ ⬝ _, symmetry, apply point_fiber_eq } end @[hott] def pequiv_postcompose_ppoint {A B B' : Type*} (f : A →* B) (g : B ≃* B') : ppoint f ∘* (fiber.pequiv_postcompose f g).to_pmap ~* ppoint (g.to_pmap ∘* f) := begin induction f with f f₀, induction g with g hg g₀, induction B with B b₀, induction B' with B' b₀', dsimp at *, induction g₀, induction f₀, fapply phomotopy.mk, { reflexivity }, -- { sorry } { refine idp_con _ ⬝ _, symmetry, dsimp [pequiv_postcompose], sorry --refine (ap_compose' _ _ _) ⬝ _, apply ap_constant } end @[hott] def pequiv_precompose_ppoint {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : ppoint f ∘* (fiber.pequiv_precompose f g).to_pmap ~* g.to_pmap ∘* ppoint (f ∘* g.to_pmap) := begin induction f with f f₀, induction g with g h₁ h₂ p₁ p₂, induction B with B b₀, induction g with g g₀, induction A with A a₀', dsimp at *, induction g₀, induction f₀, reflexivity end @[hott] def pfiber_pequiv_of_square_ppoint {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : ppoint g ∘* (pfiber_pequiv_of_square h k s).to_pmap ~* h.to_pmap ∘* ppoint f := begin refine (passoc _ _ _) ⁻¹* ⬝* _, refine pwhisker_right _ (pequiv_precompose_ppoint _ _) ⬝* _, refine (passoc _ _ _) ⬝* _, apply pwhisker_left, refine (passoc _ _ _) ⁻¹* ⬝* _, refine pwhisker_right _ (pfiber_pequiv_of_phomotopy_ppoint _) ⬝* _, apply pinv_right_phomotopy_of_phomotopy, refine (pequiv_postcompose_ppoint _ _)⁻¹*, end -- this breaks certain proofs if it is an instance @[hott] def is_trunc_fiber (n : ℕ₋₂) {A B : Type _} (f : A → B) (b : B) [is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (fiber f b) := is_trunc_equiv_closed_rev n (fiber.sigma_char _ _) (is_trunc_sigma _ n) @[hott] def is_trunc_pfiber (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (pfiber f) := is_trunc_fiber n f pt @[hott] def fiber_equiv_of_is_contr {A B : Type _} (f : A → B) (b : B) [is_contr B] : fiber f b ≃ A := (fiber.sigma_char _ _) ⬝e sigma_equiv_of_is_contr_right _ @[hott] def pfiber_pequiv_of_is_contr {A B : Type*} (f : A →* B) [is_contr B] : pfiber f ≃* A := pequiv_of_equiv (fiber_equiv_of_is_contr f pt) idp @[hott] def pfiber_ppoint_equiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃ Ω B := calc pfiber (ppoint f) ≃ Σ(x : pfiber f), ppoint f x = pt : fiber.sigma_char _ _ ... ≃ Σ(x : Σa, f a = pt), x.1 = pt : by exact sigma_equiv_sigma (fiber.sigma_char _ _) (λ a, erfl) ... ≃ Σ(x : Σa, a = pt), f x.1 = pt : sigma_assoc_comm_equiv (λa, f a = pt) (λa, a = pt) ... ≃ f pt = pt : sigma_equiv_of_is_contr_left _ ⬝e by refl ... ≃ Ω B : equiv_eq_closed_left _ (respect_pt _) @[hott] def pfiber_ppoint_pequiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃* Ω B := pequiv_of_equiv (pfiber_ppoint_equiv f) (con.left_inv _) @[hott] def fiber_ppoint_equiv_eq {A B : Type*} {f : A →* B} {a : A} (p : f a = pt) (q : ppoint f (fiber.mk a p) = pt) : pfiber_ppoint_equiv f (fiber.mk (fiber.mk a p) q) = (respect_pt f)⁻¹ ⬝ ap f q⁻¹ ⬝ p := begin refine _ ⬝ (con.assoc _ _ _) ⁻¹, apply whisker_left, sorry -- refine eq_transport_Fl _ _ ⬝ _, -- apply whisker_right -- refine inverse2 (ap_inv _ _) ⬝ (inv_inv _) ⬝ _, -- refine ap_compose f pr₁ _ ⬝ ap02 f !ap_pr1_center_eq_sigma_eq', end @[hott] def fiber_ppoint_equiv_inv_eq {A B : Type*} (f : A →* B) (p : Ω B) : (pfiber_ppoint_equiv f)⁻¹ᵉ p = fiber.mk (fiber.mk pt (respect_pt f ⬝ p)) idp := begin apply inv_eq_of_eq, refine _ ⬝ (fiber_ppoint_equiv_eq _ _)⁻¹, exact (inv_con_cancel_left _ _)⁻¹ end end fiber open function is_equiv namespace fiber /- @[hott] theorem 4.7.6 -/ variables {A : Type _} {P : A → Type _ } {Q : A → Type _} variable (f : Πa, P a → Q a) @[hott] def fiber_total_equiv {a : A} (q : Q a) : fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q := sorry -- calc -- fiber (total f) ⟨a , q⟩ -- ≃ Σ(w : Σx, P x), (⟨w.1 , f w.1 w.2 ⟩ : Σ x, _) = ⟨a , q⟩ -- : fiber.sigma_char _ _ -- ... ≃ Σ(x : A), Σ(p : P x), (⟨x , f x p⟩ : Σx, _) = ⟨a , q⟩ -- : (sigma_assoc_equiv _) -- ... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q -- : -- begin -- apply sigma_equiv_sigma_right, intro x, -- apply sigma_equiv_sigma_right, intro p, -- apply sigma_eq_equiv -- end -- ... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q -- : -- begin -- apply sigma_equiv_sigma_right, intro x, -- apply sigma_comm_equiv -- end -- ... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q -- : sigma_assoc_equiv -- ... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q -- : sigma_equiv_of_is_contr_left -- ... ≃ Σ(p : P a), f a p =[idpath a] q -- : equiv_of_eq idp -- ... ≃ Σ(p : P a), f a p = q -- : -- begin -- apply sigma_equiv_sigma_right, intro p, -- apply pathover_idp -- end -- ... ≃ fiber (f a) q -- : fiber.sigma_char end fiber end hott
1556a149ed3321cd22d1847e9b3b0b2b32715578
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/linear_algebra/basis.lean
ce277f0c489ac8059ac198fdfabdcad98493b615
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
53,139
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import linear_algebra.finsupp import linear_algebra.projection import order.zorn import data.fintype.card /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type*} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, s.sum (λ i, g i • v i) = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (s.sum $ λ i, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = s.sum (λ j, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j))) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = s.sum (λ j, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma linear_independent.ne_zero {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' ↑l.support : set s) ↑l.support, { apply bij_on.mk, { unfold maps_to }, { apply subtype.val_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_val], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' ↑l.support) ↑l.support, { apply bij_on.mk, { unfold maps_to }, { apply (linear_independent.injective zero_eq_one hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ subtype.val : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' ↑s), exact finite_preimage (assume i j _ _, plift.up.inj) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero zero_eq_one h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact prod.injective_inl.comp inj_v }, { exact prod.injective_inr.comp inj_v' }, { intros, simp [hv.ne_zero zero_eq_one] } }, { rw sum.elim_range, refine (hv.image _).to_subtype_range.union (hv'.image _).to_subtype_range _; [simp, simp, skip], apply disjoint_inl_inr.mono _ _; simp only [set.range_comp, span_image, linear_map.map_le_range] } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. s.sum (λ i, ((g i * i x - g i * a x) • i : G → L)) y = s.sum (λ i, (g i * i x - g i * a x) * i y) : pi.finset_sum_apply _ _ _ ... = s.sum (λ i, g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = s.sum (λ i, g i * i x * i y) - s.sum (λ i, g i * a x * i y) : finset.sum_sub_distrib ... = (g a * a x * a y + s.sum (λ i, g i * i x * i y)) - (g a * a x * a y + s.sum (λ i, g i * a x * i y)) : by rw add_sub_add_left_eq_sub ... = (insert a s).sum (λ i, g i * i x * i y) - (insert a s).sum (λ i, g i * a x * i y) : by rw [finset.sum_insert has, finset.sum_insert has] ... = (insert a s).sum (λ i, g i * i (x * y)) - (insert a s).sum (λ i, a x * (g i * i y)) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (insert a s).sum (λ i, (g i • i : G → L)) (x * y) - a x * (insert a s).sum (λ i, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (insert a s).sum (λ i, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end @[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ λ b, by simp lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ λ b, by simp lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the indexing sets of the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') (e : ι ≃ ι') : M ≃ₗ[R] M' := { inv_fun := hv'.constr (v ∘ e.symm), left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id, from hv.ext $ by simp, λ x, congr_arg (λ h : M →ₗ[R] M, h x) this, right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id, from hv'.ext $ by simp, λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this, ..hv.constr (v' ∘ e) } /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M) (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, add := λ x y, by ext; exact finsupp.add_apply, smul := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ (equiv_fun_basis h).to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) : (equiv_fun_basis h).symm x = finset.sum finset.univ (λi, x i • v i) := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = finset.sum finset.univ (λi, x i • v i), dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (coe : b → V) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one K _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), rwa B.range_coe_subtype at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hB.ext (λ b, _), rw image_subset_iff at BC, have : f b = (⟨f b, BC b.2⟩ : C) := rfl, dsimp, rw [this, constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, f.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hC.ext (λ c, _), simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) open fintype theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩ end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), unit), (std_basis R (λ (i : η), R) (ji.fst)) 1) := @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _) lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use sigma.fst, suffices : ∀ (a : η) (b : unit), punit.star = b, { simpa [function.left_inverse, function.right_inverse] }, exact λ _, punit_eq _ end end end module end pi
e06f849a9e4498f1d2e6197dc0a7ede334572ef2
9028d228ac200bbefe3a711342514dd4e4458bff
/src/analysis/asymptotics.lean
d1b1bd9ab127824c341cda2a6955d0a7e879bcf6
[ "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
46,729
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov -/ import analysis.normed_space.basic import topology.local_homeomorph /-! # Asymptotics We introduce these relations: * `is_O_with c f g l` : "f is big O of g along l with constant c"; * `is_O f g l` : "f is big O of g along l"; * `is_o f g l` : "f is little o of g along l". Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. The relation `is_O_with c` is introduced to factor out common algebraic arguments in the proofs of similar properties of `is_O` and `is_o`. Usually proofs outside of this file should use `is_O` instead. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter set open_locale topological_space big_operators classical namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] [normed_group E'] [normed_group F'] [normed_group G'] [normed_ring R] [normed_ring R'] [normed_field 𝕜] [normed_field 𝕜'] {c c' : ℝ} {f : α → E} {g : α → F} {k : α → G} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l l' : filter α} section defs /-! ### Definitions -/ /-- This version of the Landau notation `is_O_with C f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by `C * ∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded by `C`, modulo division by zero issues that are avoided by this definition. Probably you want to use `is_O` instead of this relation. -/ def is_O_with (c : ℝ) (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ /-- Definition of `is_O_with`. We record it in a lemma as we will set `is_O_with` to be irreducible at the end of this file. -/ lemma is_O_with_iff {c : ℝ} {f : α → E} {g : α → F} {l : filter α} : is_O_with c f g l ↔ ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := iff.rfl lemma is_O_with.of_bound {c : ℝ} {f : α → E} {g : α → F} {l : filter α} (h : ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥) : is_O_with c f g l := h /-- The Landau notation `is_O f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by a constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ def is_O (f : α → E) (g : α → F) (l : filter α) : Prop := ∃ c : ℝ, is_O_with c f g l /-- Definition of `is_O` in terms of `is_O_with`. We record it in a lemma as we will set `is_O` to be irreducible at the end of this file. -/ lemma is_O_iff_is_O_with {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ c : ℝ, is_O_with c f g l := iff.rfl /-- Definition of `is_O` in terms of filters. We record it in a lemma as we will set `is_O` to be irreducible at the end of this file. -/ lemma is_O_iff {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ c : ℝ, ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := iff.rfl lemma is_O.of_bound (c : ℝ) {f : α → E} {g : α → F} {l : filter α} (h : ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥) : is_O f g l := ⟨c, h⟩ /-- The Landau notation `is_o f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by an arbitrarily small constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ def is_o (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c f g l /-- Definition of `is_o` in terms of `is_O_with`. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff_forall_is_O_with {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c f g l := iff.rfl /-- Definition of `is_o` in terms of filters. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ ⦃c : ℝ⦄, 0 < c → ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := iff.rfl lemma is_o.def {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := h hc lemma is_o.def' {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : is_O_with c f g l := h hc end defs /-! ### Conversions -/ theorem is_O_with.is_O (h : is_O_with c f g l) : is_O f g l := ⟨c, h⟩ theorem is_o.is_O_with (hgf : is_o f g l) : is_O_with 1 f g l := hgf zero_lt_one theorem is_o.is_O (hgf : is_o f g l) : is_O f g l := hgf.is_O_with.is_O theorem is_O_with.weaken (h : is_O_with c f g' l) (hc : c ≤ c') : is_O_with c' f g' l := mem_sets_of_superset h $ λ x hx, calc ∥f x∥ ≤ c * ∥g' x∥ : hx ... ≤ _ : mul_le_mul_of_nonneg_right hc (norm_nonneg _) theorem is_O_with.exists_pos (h : is_O_with c f g' l) : ∃ c' (H : 0 < c'), is_O_with c' f g' l := ⟨max c 1, lt_of_lt_of_le zero_lt_one (le_max_right c 1), h.weaken $ le_max_left c 1⟩ theorem is_O.exists_pos (h : is_O f g' l) : ∃ c (H : 0 < c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_pos theorem is_O_with.exists_nonneg (h : is_O_with c f g' l) : ∃ c' (H : 0 ≤ c'), is_O_with c' f g' l := let ⟨c, cpos, hc⟩ := h.exists_pos in ⟨c, le_of_lt cpos, hc⟩ theorem is_O.exists_nonneg (h : is_O f g' l) : ∃ c (H : 0 ≤ c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_nonneg /-! ### Congruence -/ theorem is_O_with_congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₁ f₁ g₁ l ↔ is_O_with c₂ f₂ g₂ l := begin subst c₂, apply filter.congr_sets, filter_upwards [hf, hg], assume x e₁ e₂, dsimp at e₁ e₂ ⊢, rw [e₁, e₂] end theorem is_O_with.congr' {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := (is_O_with_congr hc hf hg).mp theorem is_O_with.congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := λ h, h.congr' hc (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O_with.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O_with c f₁ g l → is_O_with c f₂ g l := is_O_with.congr rfl hf (λ _, rfl) theorem is_O_with.congr_right {g₁ g₂ : α → F} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O_with c f g₁ l → is_O_with c f g₂ l := is_O_with.congr rfl (λ _, rfl) hg theorem is_O_with.congr_const {c₁ c₂} {l : filter α} (hc : c₁ = c₂) : is_O_with c₁ f g l → is_O_with c₂ f g l := is_O_with.congr hc (λ _, rfl) (λ _, rfl) theorem is_O_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := exists_congr $ λ c, is_O_with_congr rfl hf hg theorem is_O.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O f₁ g₁ l → is_O f₂ g₂ l := (is_O_congr hf hg).mp theorem is_O.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf (λ _, rfl) theorem is_O.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (λ _, rfl) hg theorem is_o_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr (λ c hc, is_O_with_congr (eq.refl c) hf hg) theorem is_o.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_o f₁ g₁ l → is_o f₂ g₂ l := (is_o_congr hf hg).mp theorem is_o.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_o.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf (λ _, rfl) theorem is_o.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (λ _, rfl) hg /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto (hcfg : is_O_with c f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l): is_O_with c (f ∘ k) (g ∘ k) l' := hk hcfg theorem is_O.comp_tendsto (hfg : is_O f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_O (f ∘ k) (g ∘ k) l' := hfg.imp (λ c h, h.comp_tendsto hk) theorem is_o.comp_tendsto (hfg : is_o f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_o (f ∘ k) (g ∘ k) l' := λ c cpos, (hfg cpos).comp_tendsto hk theorem is_O_with.mono (h : is_O_with c f g l') (hl : l ≤ l') : is_O_with c f g l := hl h theorem is_O.mono (h : is_O f g l') (hl : l ≤ l') : is_O f g l := h.imp (λ c h, h.mono hl) theorem is_o.mono (h : is_o f g l') (hl : l ≤ l') : is_o f g l := λ c cpos, (h cpos).mono hl theorem is_O_with.trans (hfg : is_O_with c f g l) (hgk : is_O_with c' g k l) (hc : 0 ≤ c) : is_O_with (c * c') f k l := begin filter_upwards [hfg, hgk], assume x hx hx', calc ∥f x∥ ≤ c * ∥g x∥ : hx ... ≤ c * (c' * ∥k x∥) : mul_le_mul_of_nonneg_left hx' hc ... = c * c' * ∥k x∥ : (mul_assoc _ _ _).symm end theorem is_O.trans (hfg : is_O f g' l) (hgk : is_O g' k l) : is_O f k l := let ⟨c, cnonneg, hc⟩ := hfg.exists_nonneg, ⟨c', hc'⟩ := hgk in (hc.trans hc' cnonneg).is_O theorem is_o.trans_is_O_with (hfg : is_o f g l) (hgk : is_O_with c g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact ((hfg this).trans hgk (le_of_lt this)).congr_const (div_mul_cancel _ (ne_of_gt hc)) end theorem is_o.trans_is_O (hfg : is_o f g l) (hgk : is_O g k' l) : is_o f k' l := let ⟨c, cpos, hc⟩ := hgk.exists_pos in hfg.trans_is_O_with hc cpos theorem is_O_with.trans_is_o (hfg : is_O_with c f g l) (hgk : is_o g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact (hfg.trans (hgk this) (le_of_lt hc)).congr_const (mul_div_cancel' _ (ne_of_gt hc)) end theorem is_O.trans_is_o (hfg : is_O f g' l) (hgk : is_o g' k l) : is_o f k l := let ⟨c, cpos, hc⟩ := hfg.exists_pos in hc.trans_is_o hgk cpos theorem is_o.trans (hfg : is_o f g l) (hgk : is_o g k' l) : is_o f k' l := hfg.trans_is_O hgk.is_O theorem is_o.trans' (hfg : is_o f g' l) (hgk : is_o g' k l) : is_o f k l := hfg.is_O.trans_is_o hgk section variable (l) theorem is_O_with_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O_with c f g l := univ_mem_sets' hfg theorem is_O_with_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O_with 1 f g l := is_O_with_of_le' l $ λ x, by { rw one_mul, exact hfg x } theorem is_O_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O f g l := (is_O_with_of_le' l hfg).is_O theorem is_O_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O f g l := (is_O_with_of_le l hfg).is_O end theorem is_O_with_refl (f : α → E) (l : filter α) : is_O_with 1 f f l := is_O_with_of_le l $ λ _, le_refl _ theorem is_O_refl (f : α → E) (l : filter α) : is_O f f l := (is_O_with_refl f l).is_O theorem is_O_with.trans_le (hfg : is_O_with c f g l) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) (hc : 0 ≤ c) : is_O_with c f k l := (hfg.trans (is_O_with_of_le l hgk) hc).congr_const $ mul_one c theorem is_O.trans_le (hfg : is_O f g' l) (hgk : ∀ x, ∥g' x∥ ≤ ∥k x∥) : is_O f k l := hfg.trans (is_O_of_le l hgk) theorem is_o.trans_le (hfg : is_o f g l) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) : is_o f k l := hfg.trans_is_O_with (is_O_with_of_le _ hgk) zero_lt_one section bot variables (c f g) theorem is_O_with_bot : is_O_with c f g ⊥ := trivial theorem is_O_bot : is_O f g ⊥ := (is_O_with_bot c f g).is_O theorem is_o_bot : is_o f g ⊥ := λ c _, is_O_with_bot c f g end bot theorem is_O_with.join (h : is_O_with c f g l) (h' : is_O_with c f g l') : is_O_with c f g (l ⊔ l') := mem_sup_sets.2 ⟨h, h'⟩ theorem is_O_with.join' (h : is_O_with c f g' l) (h' : is_O_with c' f g' l') : is_O_with (max c c') f g' (l ⊔ l') := mem_sup_sets.2 ⟨(h.weaken $ le_max_left c c'), (h'.weaken $ le_max_right c c')⟩ theorem is_O.join (h : is_O f g' l) (h' : is_O f g' l') : is_O f g' (l ⊔ l') := let ⟨c, hc⟩ := h, ⟨c', hc'⟩ := h' in (hc.join' hc').is_O theorem is_o.join (h : is_o f g l) (h' : is_o f g l') : is_o f g (l ⊔ l') := λ c cpos, (h cpos).join (h' cpos) /-! ### Simplification : norm -/ @[simp] theorem is_O_with_norm_right : is_O_with c f (λ x, ∥g' x∥) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_right ↔ asymptotics.is_O_with.of_norm_right asymptotics.is_O_with.norm_right @[simp] theorem is_O_norm_right : is_O f (λ x, ∥g' x∥) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_norm_right alias is_O_norm_right ↔ asymptotics.is_O.of_norm_right asymptotics.is_O.norm_right @[simp] theorem is_o_norm_right : is_o f (λ x, ∥g' x∥) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_right alias is_o_norm_right ↔ asymptotics.is_o.of_norm_right asymptotics.is_o.norm_right @[simp] theorem is_O_with_norm_left : is_O_with c (λ x, ∥f' x∥) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_left ↔ asymptotics.is_O_with.of_norm_left asymptotics.is_O_with.norm_left @[simp] theorem is_O_norm_left : is_O (λ x, ∥f' x∥) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_norm_left alias is_O_norm_left ↔ asymptotics.is_O.of_norm_left asymptotics.is_O.norm_left @[simp] theorem is_o_norm_left : is_o (λ x, ∥f' x∥) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_left alias is_o_norm_left ↔ asymptotics.is_o.of_norm_left asymptotics.is_o.norm_left theorem is_O_with_norm_norm : is_O_with c (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O_with c f' g' l := is_O_with_norm_left.trans is_O_with_norm_right alias is_O_with_norm_norm ↔ asymptotics.is_O_with.of_norm_norm asymptotics.is_O_with.norm_norm theorem is_O_norm_norm : is_O (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O f' g' l := is_O_norm_left.trans is_O_norm_right alias is_O_norm_norm ↔ asymptotics.is_O.of_norm_norm asymptotics.is_O.norm_norm theorem is_o_norm_norm : is_o (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_o f' g' l := is_o_norm_left.trans is_o_norm_right alias is_o_norm_norm ↔ asymptotics.is_o.of_norm_norm asymptotics.is_o.norm_norm /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right : is_O_with c f (λ x, -(g' x)) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_right ↔ asymptotics.is_O_with.of_neg_right asymptotics.is_O_with.neg_right @[simp] theorem is_O_neg_right : is_O f (λ x, -(g' x)) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_neg_right alias is_O_neg_right ↔ asymptotics.is_O.of_neg_right asymptotics.is_O.neg_right @[simp] theorem is_o_neg_right : is_o f (λ x, -(g' x)) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_right alias is_o_neg_right ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_right @[simp] theorem is_O_with_neg_left : is_O_with c (λ x, -(f' x)) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_left ↔ asymptotics.is_O_with.of_neg_left asymptotics.is_O_with.neg_left @[simp] theorem is_O_neg_left : is_O (λ x, -(f' x)) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_neg_left alias is_O_neg_left ↔ asymptotics.is_O.of_neg_left asymptotics.is_O.neg_left @[simp] theorem is_o_neg_left : is_o (λ x, -(f' x)) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_left alias is_o_neg_left ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_left /-! ### Product of functions (right) -/ lemma is_O_with_fst_prod : is_O_with 1 f' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_left _ _ lemma is_O_with_snd_prod : is_O_with 1 g' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_right _ _ lemma is_O_fst_prod : is_O f' (λ x, (f' x, g' x)) l := is_O_with_fst_prod.is_O lemma is_O_snd_prod : is_O g' (λ x, (f' x, g' x)) l := is_O_with_snd_prod.is_O lemma is_O_fst_prod' {f' : α → E' × F'} : is_O (λ x, (f' x).1) f' l := is_O_fst_prod lemma is_O_snd_prod' {f' : α → E' × F'} : is_O (λ x, (f' x).2) f' l := is_O_snd_prod section variables (f' k') lemma is_O_with.prod_rightl (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (g' x, k' x)) l := (h.trans is_O_with_fst_prod hc).congr_const (mul_one c) lemma is_O.prod_rightl (h : is_O f g' l) : is_O f (λx, (g' x, k' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightl k' cnonneg).is_O lemma is_o.prod_rightl (h : is_o f g' l) : is_o f (λ x, (g' x, k' x)) l := λ c cpos, (h cpos).prod_rightl k' (le_of_lt cpos) lemma is_O_with.prod_rightr (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (f' x, g' x)) l := (h.trans is_O_with_snd_prod hc).congr_const (mul_one c) lemma is_O.prod_rightr (h : is_O f g' l) : is_O f (λx, (f' x, g' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightr f' cnonneg).is_O lemma is_o.prod_rightr (h : is_o f g' l) : is_o f (λx, (f' x, g' x)) l := λ c cpos, (h cpos).prod_rightr f' (le_of_lt cpos) end lemma is_O_with.prod_left_same (hf : is_O_with c f' k' l) (hg : is_O_with c g' k' l) : is_O_with c (λ x, (f' x, g' x)) k' l := begin filter_upwards [hf, hg], simp only [mem_set_of_eq], exact λ x, max_le end lemma is_O_with.prod_left (hf : is_O_with c f' k' l) (hg : is_O_with c' g' k' l) : is_O_with (max c c') (λ x, (f' x, g' x)) k' l := (hf.weaken $ le_max_left c c').prod_left_same (hg.weaken $ le_max_right c c') lemma is_O_with.prod_left_fst (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c f' k' l := (is_O_with_fst_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with.prod_left_snd (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c g' k' l := (is_O_with_snd_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with_prod_left : is_O_with c (λ x, (f' x, g' x)) k' l ↔ is_O_with c f' k' l ∧ is_O_with c g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left_same h.2⟩ lemma is_O.prod_left (hf : is_O f' k' l) (hg : is_O g' k' l) : is_O (λ x, (f' x, g' x)) k' l := let ⟨c, hf⟩ := hf, ⟨c', hg⟩ := hg in (hf.prod_left hg).is_O lemma is_O.prod_left_fst (h : is_O (λ x, (f' x, g' x)) k' l) : is_O f' k' l := is_O_fst_prod.trans h lemma is_O.prod_left_snd (h : is_O (λ x, (f' x, g' x)) k' l) : is_O g' k' l := is_O_snd_prod.trans h @[simp] lemma is_O_prod_left : is_O (λ x, (f' x, g' x)) k' l ↔ is_O f' k' l ∧ is_O g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_o.prod_left (hf : is_o f' k' l) (hg : is_o g' k' l) : is_o (λ x, (f' x, g' x)) k' l := λ c hc, (hf hc).prod_left_same (hg hc) lemma is_o.prod_left_fst (h : is_o (λ x, (f' x, g' x)) k' l) : is_o f' k' l := is_O_fst_prod.trans_is_o h lemma is_o.prod_left_snd (h : is_o (λ x, (f' x, g' x)) k' l) : is_o g' k' l := is_O_snd_prod.trans_is_o h @[simp] lemma is_o_prod_left : is_o (λ x, (f' x, g' x)) k' l ↔ is_o f' k' l ∧ is_o g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ /-! ### Addition and subtraction -/ section add_sub variables {c₁ c₂ : ℝ} {f₁ f₂ : α → E'} theorem is_O_with.add (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x + f₂ x) g l := by filter_upwards [h₁, h₂] λ x hx₁ hx₂, calc ∥f₁ x + f₂ x∥ ≤ c₁ * ∥g x∥ + c₂ * ∥g x∥ : norm_add_le_of_le hx₁ hx₂ ... = (c₁ + c₂) * ∥g x∥ : (add_mul _ _ _).symm theorem is_O.add : is_O f₁ g l → is_O f₂ g l → is_O (λ x, f₁ x + f₂ x) g l | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := (hc₁.add hc₂).is_O theorem is_o.add (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x + f₂ x) g l := λ c cpos, ((h₁ $ half_pos cpos).add (h₂ $ half_pos cpos)).congr_const (add_halves c) theorem is_o.add_add {g₁ g₂ : α → F'} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x + f₂ x) (λ x, ∥g₁ x∥ + ∥g₂ x∥) l := by refine (h₁.trans_le $ λ x, _).add (h₂.trans_le _); simp [real.norm_eq_abs, abs_of_nonneg, add_nonneg] theorem is_O.add_is_o (h₁ : is_O f₁ g l) (h₂ : is_o f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.add h₂.is_O theorem is_o.add_is_O (h₁ : is_o f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.is_O.add h₂ theorem is_O_with.add_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₁.add (h₂ (sub_pos.2 hc))).congr_const (add_sub_cancel'_right _ _) theorem is_o.add_is_O_with (h₁ : is_o f₁ g l) (h₂ : is_O_with c₁ f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₂.add_is_o h₁ hc).congr_left $ λ _, add_comm _ _ theorem is_O_with.sub (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left theorem is_O_with.sub_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λ x, f₁ x - f₂ x) g l := h₁.add_is_o h₂.neg_left hc theorem is_O.sub (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left theorem is_o.sub (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left end add_sub /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ section is_oO_as_rel variables {f₁ f₂ f₃ : α → E'} theorem is_O_with.symm (h : is_O_with c (λ x, f₁ x - f₂ x) g l) : is_O_with c (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_with_comm : is_O_with c (λ x, f₁ x - f₂ x) g l ↔ is_O_with c (λ x, f₂ x - f₁ x) g l := ⟨is_O_with.symm, is_O_with.symm⟩ theorem is_O.symm (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_comm : is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l := ⟨is_O.symm, is_O.symm⟩ theorem is_o.symm (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o (λ x, f₂ x - f₁ x) g l := by simpa only [neg_sub] using h.neg_left theorem is_o_comm : is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l := ⟨is_o.symm, is_o.symm⟩ theorem is_O_with.triangle (h₁ : is_O_with c (λ x, f₁ x - f₂ x) g l) (h₂ : is_O_with c' (λ x, f₂ x - f₃ x) g l) : is_O_with (c + c') (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.triangle (h₁ : is_O (λ x, f₁ x - f₂ x) g l) (h₂ : is_O (λ x, f₂ x - f₃ x) g l) : is_O (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_o.triangle (h₁ : is_o (λ x, f₁ x - f₂ x) g l) (h₂ : is_o (λ x, f₂ x - f₃ x) g l) : is_o (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.congr_of_sub (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o.congr_of_sub (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ end is_oO_as_rel /-! ### Zero, one, and other constants -/ section zero_const variables (g g' l) theorem is_o_zero : is_o (λ x, (0 : E')) g' l := λ c hc, univ_mem_sets' $ λ x, by simpa using mul_nonneg (le_of_lt hc) (norm_nonneg $ g' x) theorem is_O_with_zero (hc : 0 ≤ c) : is_O_with c (λ x, (0 : E')) g' l := univ_mem_sets' $ λ x, by simpa using mul_nonneg hc (norm_nonneg $ g' x) theorem is_O_with_zero' : is_O_with 0 (λ x, (0 : E')) g l := univ_mem_sets' $ λ x, by simp theorem is_O_zero : is_O (λ x, (0 : E')) g l := ⟨0, is_O_with_zero' _ _⟩ theorem is_O_refl_left : is_O (λ x, f' x - f' x) g' l := (is_O_zero g' l).congr_left $ λ x, (sub_self _).symm theorem is_o_refl_left : is_o (λ x, f' x - f' x) g' l := (is_o_zero g' l).congr_left $ λ x, (sub_self _).symm variables {g g' l} theorem is_O_with_zero_right_iff : is_O_with c f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := by simp only [is_O_with, exists_prop, true_and, norm_zero, mul_zero, norm_le_zero_iff] theorem is_O_zero_right_iff : is_O f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := ⟨λ h, let ⟨c, hc⟩ := h in (is_O_with_zero_right_iff).1 hc, λ h, (is_O_with_zero_right_iff.2 h : is_O_with 1 _ _ _).is_O⟩ theorem is_o_zero_right_iff : is_o f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := ⟨λ h, is_O_zero_right_iff.1 h.is_O, λ h c hc, is_O_with_zero_right_iff.2 h⟩ theorem is_O_with_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O_with (∥c∥ / ∥c'∥) (λ x : α, c) (λ x, c') l := begin apply univ_mem_sets', intro x, rw [mem_set_of_eq, div_mul_cancel], rwa [ne.def, norm_eq_zero] end theorem is_O_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O (λ x : α, c) (λ x, c') l := (is_O_with_const_const c hc' l).is_O end zero_const theorem is_O_with_const_one (c : E) (l : filter α) : is_O_with ∥c∥ (λ x : α, c) (λ x, (1 : 𝕜)) l := begin refine (is_O_with_const_const c _ l).congr_const _, { rw [norm_one, div_one] }, { exact one_ne_zero } end theorem is_O_const_one (c : E) (l : filter α) : is_O (λ x : α, c) (λ x, (1 : 𝕜)) l := (is_O_with_const_one c l).is_O section variable (𝕜) theorem is_o_const_iff_is_o_one {c : F'} (hc : c ≠ 0) : is_o f (λ x, c) l ↔ is_o f (λ x, (1:𝕜)) l := ⟨λ h, h.trans_is_O $ is_O_const_one c l, λ h, h.trans_is_O $ is_O_const_const _ hc _⟩ end theorem is_o_const_iff {c : F'} (hc : c ≠ 0) : is_o f' (λ x, c) l ↔ tendsto f' l (𝓝 0) := (is_o_const_iff_is_o_one ℝ hc).trans begin clear hc c, simp only [is_o, is_O_with, norm_one, mul_one, metric.nhds_basis_closed_ball.tendsto_right_iff, metric.mem_closed_ball, dist_zero_right] end lemma is_o_id_const {c : F'} (hc : c ≠ 0) : is_o (λ (x : E'), x) (λ x, c) (𝓝 0) := (is_o_const_iff hc).mpr (continuous_id.tendsto 0) theorem is_O_const_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) {c : F'} (hc : c ≠ 0) : is_O f' (λ x, c) l := begin refine is_O.trans _ (is_O_const_const (∥y∥ + 1) hc l), use 1, simp only [is_O_with, one_mul], have : tendsto (λx, ∥f' x∥) l (𝓝 ∥y∥), from (continuous_norm.tendsto _).comp h, have Iy : ∥y∥ < ∥∥y∥ + 1∥, from lt_of_lt_of_le (lt_add_one _) (le_abs_self _), exact this (ge_mem_nhds Iy) end section variable (𝕜) theorem is_o_one_iff : is_o f' (λ x, (1 : 𝕜)) l ↔ tendsto f' l (𝓝 0) := is_o_const_iff one_ne_zero theorem is_O_one_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) : is_O f' (λ x, (1:𝕜)) l := is_O_const_of_tendsto h one_ne_zero theorem is_O.trans_tendsto_nhds (hfg : is_O f g' l) {y : F'} (hg : tendsto g' l (𝓝 y)) : is_O f (λ x, (1:𝕜)) l := hfg.trans $ is_O_one_of_tendsto 𝕜 hg end theorem is_O.trans_tendsto (hfg : is_O f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := (is_o_one_iff ℝ).1 $ hfg.trans_is_o $ (is_o_one_iff ℝ).2 hg theorem is_o.trans_tendsto (hfg : is_o f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := hfg.is_O.trans_tendsto hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O_with ∥c∥ (λ x, c * f x) f l := is_O_with_of_le' _ $ λ x, norm_mul_le _ _ theorem is_O_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O (λ x, c * f x) f l := (is_O_with_const_mul_self c f l).is_O theorem is_O_with.const_mul_left {f : α → R} (h : is_O_with c f g l) (c' : R) : is_O_with (∥c'∥ * c) (λ x, c' * f x) g l := (is_O_with_const_mul_self c' f l).trans h (norm_nonneg c') theorem is_O.const_mul_left {f : α → R} (h : is_O f g l) (c' : R) : is_O (λ x, c' * f x) g l := let ⟨c, hc⟩ := h in (hc.const_mul_left c').is_O theorem is_O_with_self_const_mul' (u : units R) (f : α → R) (l : filter α) : is_O_with ∥(↑u⁻¹:R)∥ f (λ x, ↑u * f x) l := (is_O_with_const_mul_self ↑u⁻¹ _ l).congr_left $ λ x, u.inv_mul_cancel_left (f x) theorem is_O_with_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with ∥c∥⁻¹ f (λ x, c * f x) l := (is_O_with_self_const_mul' (units.mk0 c hc) f l).congr_const $ normed_field.norm_inv c theorem is_O_self_const_mul' {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : is_O f (λ x, c * f x) l := let ⟨u, hu⟩ := hc in hu ▸ (is_O_with_self_const_mul' u f l).is_O theorem is_O_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O f (λ x, c * f x) l := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_O (λ x, c * f x) g l ↔ is_O f g l := ⟨(is_O_self_const_mul' hc f l).trans, λ h, h.const_mul_left c⟩ theorem is_O_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c * f x) g l ↔ is_O f g l := is_O_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_o.const_mul_left {f : α → R} (h : is_o f g l) (c : R) : is_o (λ x, c * f x) g l := (is_O_const_mul_self c f l).trans_is_o h theorem is_o_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_o (λ x, c * f x) g l ↔ is_o f g l := ⟨(is_O_self_const_mul' hc f l).trans_is_o, λ h, h.const_mul_left c⟩ theorem is_o_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c * f x) g l ↔ is_o f g l := is_o_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_O_with.of_const_mul_right {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' f (λ x, c * g x) l) : is_O_with (c' * ∥c∥) f g l := h.trans (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {g : α → R} {c : R} (h : is_O f (λ x, c * g x) l) : is_O f g l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.of_const_mul_right cnonneg).is_O theorem is_O_with.const_mul_right' {g : α → R} {u : units R} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥(↑u⁻¹:R)∥) f (λ x, ↑u * g x) l := h.trans (is_O_with_self_const_mul' _ _ _) hc' theorem is_O_with.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥c∥⁻¹) f (λ x, c * g x) l := h.trans (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.trans (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_O_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_O f (λ x, c * g x) l ↔ is_O f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_O_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c * g x) l ↔ is_O f g l := is_O_const_mul_right_iff' $ is_unit.mk0 c hc theorem is_o.of_const_mul_right {g : α → R} {c : R} (h : is_o f (λ x, c * g x) l) : is_o f g l := h.trans_is_O (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.trans_is_O (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_o_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_o f (λ x, c * g x) l ↔ is_o f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_o_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c * g x) l ↔ is_o f g l := is_o_const_mul_right_iff' $ is_unit.mk0 c hc /-! ### Multiplication -/ theorem is_O_with.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} {c₁ c₂ : ℝ} (h₁ : is_O_with c₁ f₁ g₁ l) (h₂ : is_O_with c₂ f₂ g₂ l) : is_O_with (c₁ * c₂) (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin filter_upwards [h₁, h₂], simp only [mem_set_of_eq], intros x hx₁ hx₂, apply le_trans (norm_mul_le _ _), convert mul_le_mul hx₁ hx₂ (norm_nonneg _) (le_trans (norm_nonneg _) hx₁) using 1, rw normed_field.norm_mul, ac_refl end theorem is_O.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := let ⟨c, hc⟩ := h₁, ⟨c', hc'⟩ := h₂ in (hc.mul hc').is_O theorem is_O.mul_is_o {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₁.exists_pos with ⟨c', c'pos, hc'⟩, exact (hc'.mul (h₂ (div_pos cpos c'pos))).congr_const (mul_div_cancel' _ (ne_of_gt c'pos)) end theorem is_o.mul_is_O {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₂.exists_pos with ⟨c', c'pos, hc'⟩, exact ((h₁ (div_pos cpos c'pos)).mul hc').congr_const (div_mul_cancel _ (ne_of_gt c'pos)) end theorem is_o.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := h₁.mul_is_O h₂.is_O /-! ### Scalar multiplication -/ section smul_const variables [normed_space 𝕜 E'] theorem is_O_with.const_smul_left (h : is_O_with c f' g l) (c' : 𝕜) : is_O_with (∥c'∥ * c) (λ x, c' • f' x) g l := by refine ((h.norm_left.const_mul_left (∥c'∥)).congr _ _ (λ _, rfl)).of_norm_left; intros; simp only [norm_norm, norm_smul] theorem is_O_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c • f' x) g l ↔ is_O f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left], end theorem is_o_const_smul_left (h : is_o f' g l) (c : 𝕜) : is_o (λ x, c • f' x) g l := begin refine ((h.norm_left.const_mul_left (∥c∥)).congr_left _).of_norm_left, exact λ x, (norm_smul _ _).symm end theorem is_o_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c • f' x) g l ↔ is_o f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end theorem is_O_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c • f' x) l ↔ is_O f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c • f' x) l ↔ is_o f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right_iff cne0, is_o_norm_right] end end smul_const section smul variables [normed_space 𝕜 E'] [normed_space 𝕜 F'] theorem is_O_with.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O_with c k₁ k₂ l) (h₂ : is_O_with c' f' g' l) : is_O_with (c * c') (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr rfl _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_O f' g' l) : is_O (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul_is_o {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_o h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul_is_O {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_O f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_O h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] end smul /-! ### Sum -/ section sum variables {ι : Type*} {A : ι → α → E'} {C : ι → ℝ} {s : finset ι} theorem is_O_with.sum (h : ∀ i ∈ s, is_O_with (C i) (A i) g l) : is_O_with (∑ i in s, C i) (λ x, ∑ i in s, A i x) g l := begin induction s using finset.induction_on with i s is IH, { simp only [is_O_with_zero', finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end theorem is_O.sum (h : ∀ i ∈ s, is_O (A i) g l) : is_O (λ x, ∑ i in s, A i x) g l := begin induction s using finset.induction_on with i s is IH, { simp only [is_O_zero, finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end theorem is_o.sum (h : ∀ i ∈ s, is_o (A i) g' l) : is_o (λ x, ∑ i in s, A i x) g' l := begin induction s using finset.induction_on with i s is IH, { simp only [is_o_zero, finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end end sum /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_0 {f g : α → 𝕜} {l : filter α} (h : is_o f g l) : tendsto (λ x, f x / (g x)) l (𝓝 0) := have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l, from h.mul_is_O (is_O_refl _ _), have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : 𝕜)) l, from is_O_of_le _ (λ x, by by_cases h : ∥g x∥ = 0; simp [h, zero_le_one]), (is_o_one_iff 𝕜).mp (eq₁.trans_is_O eq₂) private theorem is_o_of_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) : is_o f g l := have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : 𝕜)) l, from (is_o_one_iff _).mpr h, have eq₂ : is_o (λ x, f x / g x * g x) g l, by convert eq₁.mul_is_O (is_O_refl _ _); simp, have eq₃ : is_O f (λ x, f x / g x * g x) l, begin refine is_O_of_le _ (λ x, _), by_cases H : g x = 0, { simp only [H, hgf _ H, mul_zero] }, { simp only [div_mul_cancel _ H] } end, eq₃.trans_is_o eq₂ theorem is_o_iff_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := iff.intro is_o.tendsto_0 (is_o_of_tendsto hgf) /-! ### Miscellanous lemmas -/ theorem is_o_pow_pow {m n : ℕ} (h : m < n) : is_o (λ(x : 𝕜), x^n) (λx, x^m) (𝓝 0) := begin let p := n - m, have nmp : n = m + p := (nat.add_sub_cancel' (le_of_lt h)).symm, have : (λ(x : 𝕜), x^m) = (λx, x^m * 1), by simp only [mul_one], simp only [this, pow_add, nmp], refine is_O.mul_is_o (is_O_refl _ _) ((is_o_one_iff _).2 _), convert (continuous_pow p).tendsto (0 : 𝕜), exact (zero_pow (nat.sub_pos_of_lt h)).symm end theorem is_o_pow_id {n : ℕ} (h : 1 < n) : is_o (λ(x : 𝕜), x^n) (λx, x) (𝓝 0) := by { convert is_o_pow_pow h, simp only [pow_one] } theorem is_O_with.right_le_sub_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₂ x - f₁ x) l := mem_sets_of_superset h $ λ x hx, begin simp only [mem_set_of_eq] at hx ⊢, rw [mul_comm, one_div, ← div_eq_mul_inv, le_div_iff, mul_sub, mul_one, mul_comm], { exact le_trans (sub_le_sub_left hx _) (norm_sub_norm_le _ _) }, { exact sub_pos.2 hc } end theorem is_O_with.right_le_add_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₁ x + f₂ x) l := (h.neg_right.right_le_sub_of_lt_1 hc).neg_right.of_neg_left.congr rfl (λ x, rfl) (λ x, by rw [neg_sub, sub_neg_eq_add]) theorem is_o.right_is_O_sub {f₁ f₂ : α → E'} (h : is_o f₁ f₂ l) : is_O f₂ (λx, f₂ x - f₁ x) l := ((h.def' one_half_pos).right_le_sub_of_lt_1 one_half_lt_one).is_O theorem is_o.right_is_O_add {f₁ f₂ : α → E'} (h : is_o f₁ f₂ l) : is_O f₂ (λx, f₁ x + f₂ x) l := ((h.def' one_half_pos).right_le_add_of_lt_1 one_half_lt_one).is_O end asymptotics namespace local_homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `local_homeomorph`. -/ lemma is_O_with_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} {C : ℝ} : is_O_with C f g (𝓝 b) ↔ is_O_with C (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := ⟨λ h, h.comp_tendsto $ by { convert e.continuous_at (e.map_target hb), exact (e.right_inv hb).symm }, λ h, (h.comp_tendsto (e.continuous_at_symm hb)).congr' rfl ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg f hx) ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg g hx)⟩ /-- Transfer `is_O` over a `local_homeomorph`. -/ lemma is_O_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : is_O f g (𝓝 b) ↔ is_O (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := exists_congr $ λ C, e.is_O_with_congr hb /-- Transfer `is_o` over a `local_homeomorph`. -/ lemma is_o_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : is_o f g (𝓝 b) ↔ is_o (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := forall_congr $ λ c, forall_congr $ λ hc, e.is_O_with_congr hb end local_homeomorph namespace homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `homeomorph`. -/ lemma is_O_with_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} {C : ℝ} : is_O_with C f g (𝓝 b) ↔ is_O_with C (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := e.to_local_homeomorph.is_O_with_congr trivial /-- Transfer `is_O` over a `homeomorph`. -/ lemma is_O_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : is_O f g (𝓝 b) ↔ is_O (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := exists_congr $ λ C, e.is_O_with_congr /-- Transfer `is_o` over a `homeomorph`. -/ lemma is_o_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : is_o f g (𝓝 b) ↔ is_o (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := forall_congr $ λ c, forall_congr $ λ hc, e.is_O_with_congr end homeomorph attribute [irreducible] asymptotics.is_o asymptotics.is_O asymptotics.is_O_with
fe19a7a9fd8720fb0b68bb5152d90d0b964846e6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/typevec.lean
6902ed53f84bbb396d9aac2d242ee8cc389dfe85
[]
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
24,216
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fin2 import Mathlib.logic.function.basic import Mathlib.tactic.basic import Mathlib.PostPort universes u_1 u u_2 u_3 u_4 namespace Mathlib /-! # Tuples of types, and their categorical structure. ## Features * `typevec n` - n-tuples of types * `α ⟹ β` - n-tuples of maps * `f ⊚ g` - composition Also, support functions for operating with n-tuples of types, such as: * `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple * `drop α` - drops the last element of an (n+1)-tuple * `last α` - returns the last element of an (n+1)-tuple * `append_fun f g` - appends a function g to an n-tuple of functions * `drop_fun f` - drops the last function from an n+1-tuple * `last_fun f` - returns the last function of a tuple. Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal to it, we need support functions and lemmas to mediate between constructions. -/ /-- n-tuples of types, as a category -/ def typevec (n : ℕ) := fin2 n → Type u_1 protected instance typevec.inhabited {n : ℕ} : Inhabited (typevec n) := { default := fun (_x : fin2 n) => PUnit } namespace typevec /-- arrow in the category of `typevec` -/ def arrow {n : ℕ} (α : typevec n) (β : typevec n) := (i : fin2 n) → α i → β i protected instance arrow.inhabited {n : ℕ} (α : typevec n) (β : typevec n) [(i : fin2 n) → Inhabited (β i)] : Inhabited (arrow α β) := { default := fun (_x : fin2 n) (_x_1 : α _x) => Inhabited.default } /-- identity of arrow composition -/ def id {n : ℕ} {α : typevec n} : arrow α α := fun (i : fin2 n) (x : α i) => x /-- arrow composition in the category of `typevec` -/ def comp {n : ℕ} {α : typevec n} {β : typevec n} {γ : typevec n} (g : arrow β γ) (f : arrow α β) : arrow α γ := fun (i : fin2 n) (x : α i) => g i (f i x) @[simp] theorem id_comp {n : ℕ} {α : typevec n} {β : typevec n} (f : arrow α β) : comp id f = f := rfl @[simp] theorem comp_id {n : ℕ} {α : typevec n} {β : typevec n} (f : arrow α β) : comp f id = f := rfl theorem comp_assoc {n : ℕ} {α : typevec n} {β : typevec n} {γ : typevec n} {δ : typevec n} (h : arrow γ δ) (g : arrow β γ) (f : arrow α β) : comp (comp h g) f = comp h (comp g f) := rfl /-- Support for extending a typevec by one element. -/ def append1 {n : ℕ} (α : typevec n) (β : Type u_1) : typevec (n + 1) := sorry infixl:67 " ::: " => Mathlib.typevec.append1 /-- retain only a `n-length` prefix of the argument -/ def drop {n : ℕ} (α : typevec (n + 1)) : typevec n := fun (i : fin2 n) => α (fin2.fs i) /-- take the last value of a `(n+1)-length` vector -/ def last {n : ℕ} (α : typevec (n + 1)) := α fin2.fz protected instance last.inhabited {n : ℕ} (α : typevec (n + 1)) [Inhabited (α fin2.fz)] : Inhabited (last α) := { default := Inhabited.default } theorem drop_append1 {n : ℕ} {α : typevec n} {β : Type u_1} {i : fin2 n} : drop (α ::: β) i = α i := rfl @[simp] theorem drop_append1' {n : ℕ} {α : typevec n} {β : Type u_1} : drop (α ::: β) = α := funext fun (x : fin2 n) => drop_append1 theorem last_append1 {n : ℕ} {α : typevec n} {β : Type u_1} : last (α ::: β) = β := rfl @[simp] theorem append1_drop_last {n : ℕ} (α : typevec (n + 1)) : drop α ::: last α = α := sorry /-- cases on `(n+1)-length` vectors -/ def append1_cases {n : ℕ} {C : typevec (n + 1) → Sort u} (H : (α : typevec n) → (β : Type u_1) → C (α ::: β)) (γ : typevec (n + 1)) : C γ := eq.mpr sorry (H (drop γ) (last γ)) @[simp] theorem append1_cases_append1 {n : ℕ} {C : typevec (n + 1) → Sort u} (H : (α : typevec n) → (β : Type u_1) → C (α ::: β)) (α : typevec n) (β : Type u_1) : append1_cases H (α ::: β) = H α β := rfl /-- append an arrow and a function for arbitrary source and target type vectors -/ def split_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow (drop α) (drop α')) (g : last α → last α') : arrow α α' := sorry /-- append an arrow and a function as well as their respective source and target types / typevecs -/ def append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow α α') (g : β → β') : arrow (α ::: β) (α' ::: β') := split_fun f g infixl:67 " ::: " => Mathlib.typevec.append_fun /-- split off the prefix of an arrow -/ def drop_fun {n : ℕ} {α : typevec (n + 1)} {β : typevec (n + 1)} (f : arrow α β) : arrow (drop α) (drop β) := fun (i : fin2 n) => f (fin2.fs i) /-- split off the last function of an arrow -/ def last_fun {n : ℕ} {α : typevec (n + 1)} {β : typevec (n + 1)} (f : arrow α β) : last α → last β := f fin2.fz /-- arrow in the category of `0-length` vectors -/ def nil_fun {α : typevec 0} {β : typevec 0} : arrow α β := fun (i : fin2 0) => fin2.elim0 i theorem eq_of_drop_last_eq {n : ℕ} {α : typevec (n + 1)} {β : typevec (n + 1)} {f : arrow α β} {g : arrow α β} (h₀ : drop_fun f = drop_fun g) (h₁ : last_fun f = last_fun g) : f = g := sorry @[simp] theorem drop_fun_split_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow (drop α) (drop α')) (g : last α → last α') : drop_fun (split_fun f g) = f := rfl /-- turn an equality into an arrow -/ def arrow.mp {n : ℕ} {α : typevec n} {β : typevec n} (h : α = β) : arrow α β := sorry /-- turn an equality into an arrow, with reverse direction -/ def arrow.mpr {n : ℕ} {α : typevec n} {β : typevec n} (h : α = β) : arrow β α := sorry /-- decompose a vector into its prefix appended with its last element -/ def to_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : arrow α (drop α ::: last α) := arrow.mpr (append1_drop_last α) /-- stitch two bits of a vector back together -/ def from_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : arrow (drop α ::: last α) α := arrow.mp (append1_drop_last α) @[simp] theorem last_fun_split_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow (drop α) (drop α')) (g : last α → last α') : last_fun (split_fun f g) = g := rfl @[simp] theorem drop_fun_append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow α α') (g : β → β') : drop_fun (f ::: g) = f := rfl @[simp] theorem last_fun_append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow α α') (g : β → β') : last_fun (f ::: g) = g := rfl theorem split_drop_fun_last_fun {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} (f : arrow α α') : split_fun (drop_fun f) (last_fun f) = f := eq_of_drop_last_eq rfl rfl theorem split_fun_inj {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} {f : arrow (drop α) (drop α')} {f' : arrow (drop α) (drop α')} {g : last α → last α'} {g' : last α → last α'} (H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' := sorry theorem append_fun_inj {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} {f : arrow α α'} {f' : arrow α α'} {g : β → β'} {g' : β → β'} : f ::: g = f' ::: g' → f = f' ∧ g = g' := split_fun_inj theorem split_fun_comp {n : ℕ} {α₀ : typevec (n + 1)} {α₁ : typevec (n + 1)} {α₂ : typevec (n + 1)} (f₀ : arrow (drop α₀) (drop α₁)) (f₁ : arrow (drop α₁) (drop α₂)) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : split_fun (comp f₁ f₀) (g₁ ∘ g₀) = comp (split_fun f₁ g₁) (split_fun f₀ g₀) := eq_of_drop_last_eq rfl rfl theorem append_fun_comp_split_fun {n : ℕ} {α : typevec n} {γ : typevec n} {β : Type u_1} {δ : Type u_2} {ε : typevec (n + 1)} (f₀ : arrow (drop ε) α) (f₁ : arrow α γ) (g₀ : last ε → β) (g₁ : β → δ) : comp (f₁ ::: g₁) (split_fun f₀ g₀) = split_fun (comp f₁ f₀) (g₁ ∘ g₀) := Eq.symm (split_fun_comp f₀ f₁ g₀ g₁) theorem append_fun_comp {n : ℕ} {α₀ : typevec n} {α₁ : typevec n} {α₂ : typevec n} {β₀ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : comp f₁ f₀ ::: g₁ ∘ g₀ = comp (f₁ ::: g₁) (f₀ ::: g₀) := eq_of_drop_last_eq rfl rfl theorem append_fun_comp' {n : ℕ} {α₀ : typevec n} {α₁ : typevec n} {α₂ : typevec n} {β₀ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : comp (f₁ ::: g₁) (f₀ ::: g₀) = comp f₁ f₀ ::: g₁ ∘ g₀ := eq_of_drop_last_eq rfl rfl theorem nil_fun_comp {α₀ : typevec 0} (f₀ : arrow α₀ fin2.elim0) : comp nil_fun f₀ = f₀ := funext fun (x : fin2 0) => fin2.elim0 x theorem append_fun_comp_id {n : ℕ} {α : typevec n} {β₀ : Type u_1} {β₁ : Type u_1} {β₂ : Type u_1} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : id ::: g₁ ∘ g₀ = comp (id ::: g₁) (id ::: g₀) := eq_of_drop_last_eq rfl rfl @[simp] theorem drop_fun_comp {n : ℕ} {α₀ : typevec (n + 1)} {α₁ : typevec (n + 1)} {α₂ : typevec (n + 1)} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) : drop_fun (comp f₁ f₀) = comp (drop_fun f₁) (drop_fun f₀) := rfl @[simp] theorem last_fun_comp {n : ℕ} {α₀ : typevec (n + 1)} {α₁ : typevec (n + 1)} {α₂ : typevec (n + 1)} (f₀ : arrow α₀ α₁) (f₁ : arrow α₁ α₂) : last_fun (comp f₁ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl theorem append_fun_aux {n : ℕ} {α : typevec n} {α' : typevec n} {β : Type u_1} {β' : Type u_2} (f : arrow (α ::: β) (α' ::: β')) : drop_fun f ::: last_fun f = f := eq_of_drop_last_eq rfl rfl theorem append_fun_id_id {n : ℕ} {α : typevec n} {β : Type u_1} : id ::: id = id := eq_of_drop_last_eq rfl rfl protected instance subsingleton0 : subsingleton (typevec 0) := subsingleton.intro fun (a b : typevec 0) => funext fun (a_1 : fin2 0) => fin2.elim0 a_1 /-- cases distinction for 0-length type vector -/ protected def cases_nil {β : typevec 0 → Sort u_2} (f : β fin2.elim0) (v : typevec 0) : β v := cast sorry f /-- cases distinction for (n+1)-length type vector -/ protected def cases_cons (n : ℕ) {β : typevec (n + 1) → Sort u_2} (f : (t : Type u_1) → (v : typevec n) → β (v ::: t)) (v : typevec (n + 1)) : β v := cast sorry (f (last v) (drop v)) protected theorem cases_nil_append1 {β : typevec 0 → Sort u_2} (f : β fin2.elim0) : typevec.cases_nil f fin2.elim0 = f := rfl protected theorem cases_cons_append1 (n : ℕ) {β : typevec (n + 1) → Sort u_2} (f : (t : Type u_1) → (v : typevec n) → β (v ::: t)) (v : typevec n) (α : Type u_1) : typevec.cases_cons n f (v ::: α) = f α v := rfl /-- cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₃ {β : (v : typevec 0) → (v' : typevec 0) → arrow v v' → Sort u_3} (f : β fin2.elim0 fin2.elim0 nil_fun) (v : typevec 0) (v' : typevec 0) (fs : arrow v v') : β v v' fs := cast sorry f /-- cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₃ (n : ℕ) {β : (v : typevec (n + 1)) → (v' : typevec (n + 1)) → arrow v v' → Sort u_3} (F : (t : Type u_1) → (t' : Type u_2) → (f : t → t') → (v : typevec n) → (v' : typevec n) → (fs : arrow v v') → β (v ::: t) (v' ::: t') (fs ::: f)) (v : typevec (n + 1)) (v' : typevec (n + 1)) (fs : arrow v v') : β v v' fs := eq.mpr sorry (eq.mpr sorry fun (fs : arrow (drop v ::: last v) (drop v' ::: last v')) => eq.mpr sorry (F (last v) (last v') (last_fun fs) (drop v) (drop v') (drop_fun fs))) /-- specialized cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₂ {β : arrow fin2.elim0 fin2.elim0 → Sort u_3} (f : β nil_fun) : (f : arrow fin2.elim0 fin2.elim0) → β f := fun (g : arrow fin2.elim0 fin2.elim0) => eq.mpr sorry f /-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₂ (n : ℕ) (t : Type u_1) (t' : Type u_2) (v : typevec n) (v' : typevec n) {β : arrow (v ::: t) (v' ::: t') → Sort u_3} (F : (f : t → t') → (fs : arrow v v') → β (fs ::: f)) (fs : arrow (v ::: t) (v' ::: t')) : β fs := eq.mpr sorry (F (last_fun fs) (drop_fun fs)) theorem typevec_cases_nil₂_append_fun {β : arrow fin2.elim0 fin2.elim0 → Sort u_3} (f : β nil_fun) : typevec_cases_nil₂ f nil_fun = f := rfl theorem typevec_cases_cons₂_append_fun (n : ℕ) (t : Type u_1) (t' : Type u_2) (v : typevec n) (v' : typevec n) {β : arrow (v ::: t) (v' ::: t') → Sort u_3} (F : (f : t → t') → (fs : arrow v v') → β (fs ::: f)) (f : t → t') (fs : arrow v v') : typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs := rfl /- for lifting predicates and relations -/ /-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/ def pred_last {n : ℕ} (α : typevec n) {β : Type u_1} (p : β → Prop) {i : fin2 (n + 1)} : append1 α β i → Prop := sorry /-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and all the other elements are equal. -/ def rel_last {n : ℕ} (α : typevec n) {β : Type u_1} {γ : Type u_1} (r : β → γ → Prop) {i : fin2 (n + 1)} : append1 α β i → append1 α γ i → Prop := sorry /-- `repeat n t` is a `n-length` type vector that contains `n` occurences of `t` -/ def repeat (n : ℕ) (t : Type u_1) : typevec n := sorry /-- `prod α β` is the pointwise product of the components of `α` and `β` -/ def prod {n : ℕ} (α : typevec n) (β : typevec n) : typevec n := sorry /-- `const x α` is an arrow that ignores its source and constructs a `typevec` that contains nothing but `x` -/ protected def const {β : Type u_1} (x : β) {n : ℕ} (α : typevec n) : arrow α (repeat n β) := sorry /-- vector of equality on a product of vectors -/ def repeat_eq {n : ℕ} (α : typevec n) : arrow (prod α α) (repeat n Prop) := sorry theorem const_append1 {β : Type u_1} {γ : Type u_2} (x : γ) {n : ℕ} (α : typevec n) : typevec.const x (α ::: β) = typevec.const x α ::: fun (_x : β) => x := sorry theorem eq_nil_fun {α : typevec 0} {β : typevec 0} (f : arrow α β) : f = nil_fun := sorry theorem id_eq_nil_fun {α : typevec 0} : id = nil_fun := sorry theorem const_nil {β : Type u_1} (x : β) (α : typevec 0) : typevec.const x α = nil_fun := sorry theorem repeat_eq_append1 {β : Type u_1} {n : ℕ} (α : typevec n) : repeat_eq (α ::: β) = split_fun (repeat_eq α) (function.uncurry Eq) := sorry theorem repeat_eq_nil (α : typevec 0) : repeat_eq α = nil_fun := sorry /-- predicate on a type vector to constrain only the last object -/ def pred_last' {n : ℕ} (α : typevec n) {β : Type u_1} (p : β → Prop) : arrow (α ::: β) (repeat (n + 1) Prop) := split_fun (typevec.const True α) p /-- predicate on the product of two type vectors to constrain only their last object -/ def rel_last' {n : ℕ} (α : typevec n) {β : Type u_1} (p : β → β → Prop) : arrow (prod (α ::: β) (α ::: β)) (repeat (n + 1) Prop) := split_fun (repeat_eq α) (function.uncurry p) /-- given `F : typevec.{u} (n+1) → Type u`, `curry F : Type u → typevec.{u} → Type u`, i.e. its first argument can be fed in separately from the rest of the vector of arguments -/ def curry {n : ℕ} (F : typevec (n + 1) → Type u_1) (α : Type u) (β : typevec n) := F (β ::: α) protected instance curry.inhabited {n : ℕ} (F : typevec (n + 1) → Type u_1) (α : Type u) (β : typevec n) [I : Inhabited (F (β ::: α))] : Inhabited (curry F α β) := I /-- arrow to remove one element of a `repeat` vector -/ def drop_repeat (α : Type u_1) {n : ℕ} : arrow (drop (repeat (Nat.succ n) α)) (repeat n α) := sorry /-- projection for a repeat vector -/ def of_repeat {α : Type u_1} {n : ℕ} {i : fin2 n} : repeat n α i → α := sorry theorem const_iff_true {n : ℕ} {α : typevec n} {i : fin2 n} {x : α i} {p : Prop} : of_repeat (typevec.const p α i x) ↔ p := sorry -- variables {F : typevec.{u} n → Type*} [mvfunctor F] /-- left projection of a `prod` vector -/ def prod.fst {n : ℕ} {α : typevec n} {β : typevec n} : arrow (prod α β) α := sorry /-- right projection of a `prod` vector -/ def prod.snd {n : ℕ} {α : typevec n} {β : typevec n} : arrow (prod α β) β := sorry /-- introduce a product where both components are the same -/ def prod.diag {n : ℕ} {α : typevec n} : arrow α (prod α α) := sorry /-- constructor for `prod` -/ def prod.mk {n : ℕ} {α : typevec n} {β : typevec n} (i : fin2 n) : α i → β i → prod α β i := sorry @[simp] theorem prod_fst_mk {n : ℕ} {α : typevec n} {β : typevec n} (i : fin2 n) (a : α i) (b : β i) : prod.fst i (prod.mk i a b) = a := sorry @[simp] theorem prod_snd_mk {n : ℕ} {α : typevec n} {β : typevec n} (i : fin2 n) (a : α i) (b : β i) : prod.snd i (prod.mk i a b) = b := sorry /-- `prod` is functorial -/ protected def prod.map {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} : arrow α β → arrow α' β' → arrow (prod α α') (prod β β') := sorry theorem fst_prod_mk {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} (f : arrow α β) (g : arrow α' β') : comp prod.fst (prod.map f g) = comp f prod.fst := sorry theorem snd_prod_mk {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} (f : arrow α β) (g : arrow α' β') : comp prod.snd (prod.map f g) = comp g prod.snd := sorry theorem fst_diag {n : ℕ} {α : typevec n} : comp prod.fst prod.diag = id := sorry theorem snd_diag {n : ℕ} {α : typevec n} : comp prod.snd prod.diag = id := sorry theorem repeat_eq_iff_eq {n : ℕ} {α : typevec n} {i : fin2 n} {x : α i} {y : α i} : of_repeat (repeat_eq α i (prod.mk i x y)) ↔ x = y := sorry /-- given a predicate vector `p` over vector `α`, `subtype_ p` is the type of vectors that contain an `α` that satisfies `p` -/ def subtype_ {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : typevec n := sorry /-- projection on `subtype_` -/ def subtype_val {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : arrow (subtype_ p) α := sorry /-- arrow that rearranges the type of `subtype_` to turn a subtype of vector into a vector of subtypes -/ def to_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : arrow (fun (i : fin2 n) => Subtype fun (x : α i) => of_repeat (p i x)) (subtype_ p) := sorry /-- arrow that rearranges the type of `subtype_` to turn a vector of subtypes into a subtype of vector -/ def of_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : arrow (subtype_ p) fun (i : fin2 n) => Subtype fun (x : α i) => of_repeat (p i x) := sorry /-- similar to `to_subtype` adapted to relations (i.e. predicate on product) -/ def to_subtype' {n : ℕ} {α : typevec n} (p : arrow (prod α α) (repeat n Prop)) : arrow (fun (i : fin2 n) => Subtype fun (x : α i × α i) => of_repeat (p i (prod.mk i (prod.fst x) (prod.snd x)))) (subtype_ p) := sorry /-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/ def of_subtype' {n : ℕ} {α : typevec n} (p : arrow (prod α α) (repeat n Prop)) : arrow (subtype_ p) fun (i : fin2 n) => Subtype fun (x : α i × α i) => of_repeat (p i (prod.mk i (prod.fst x) (prod.snd x))) := sorry /-- similar to `diag` but the target vector is a `subtype_` guaranteeing the equality of the components -/ def diag_sub {n : ℕ} {α : typevec n} : arrow α (subtype_ (repeat_eq α)) := sorry theorem subtype_val_nil {α : typevec 0} (ps : arrow α (repeat 0 Prop)) : subtype_val ps = nil_fun := sorry theorem diag_sub_val {n : ℕ} {α : typevec n} : comp (subtype_val (repeat_eq α)) diag_sub = prod.diag := sorry theorem prod_id {n : ℕ} {α : typevec n} {β : typevec n} : prod.map id id = id := sorry theorem append_prod_append_fun {n : ℕ} {α : typevec n} {α' : typevec n} {β : typevec n} {β' : typevec n} {φ : Type u} {φ' : Type u} {ψ : Type u} {ψ' : Type u} {f₀ : arrow α α'} {g₀ : arrow β β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} : prod.map f₀ g₀ ::: prod.map f₁ g₁ = prod.map (f₀ ::: f₁) (g₀ ::: g₁) := sorry @[simp] theorem drop_fun_diag {n : ℕ} {α : typevec (n + 1)} : drop_fun prod.diag = prod.diag := sorry @[simp] theorem drop_fun_subtype_val {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : drop_fun (subtype_val p) = subtype_val (drop_fun p) := rfl @[simp] theorem last_fun_subtype_val {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : last_fun (subtype_val p) = subtype.val := rfl @[simp] theorem drop_fun_to_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : drop_fun (to_subtype p) = to_subtype fun (i : fin2 n) (x : α (fin2.fs i)) => p (fin2.fs i) x := sorry @[simp] theorem last_fun_to_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : last_fun (to_subtype p) = id := sorry @[simp] theorem drop_fun_of_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : drop_fun (of_subtype p) = of_subtype (drop_fun p) := sorry @[simp] theorem last_fun_of_subtype {n : ℕ} {α : typevec (n + 1)} (p : arrow α (repeat (n + 1) Prop)) : last_fun (of_subtype p) = id := sorry @[simp] theorem drop_fun_rel_last {n : ℕ} {α : typevec n} {β : Type u_1} (R : β → β → Prop) : drop_fun (rel_last' α R) = repeat_eq α := rfl @[simp] theorem drop_fun_prod {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} {β : typevec (n + 1)} {β' : typevec (n + 1)} (f : arrow α β) (f' : arrow α' β') : drop_fun (prod.map f f') = prod.map (drop_fun f) (drop_fun f') := sorry @[simp] theorem last_fun_prod {n : ℕ} {α : typevec (n + 1)} {α' : typevec (n + 1)} {β : typevec (n + 1)} {β' : typevec (n + 1)} (f : arrow α β) (f' : arrow α' β') : last_fun (prod.map f f') = prod.map (last_fun f) (last_fun f') := sorry @[simp] theorem drop_fun_from_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : drop_fun from_append1_drop_last = id := rfl @[simp] theorem last_fun_from_append1_drop_last {n : ℕ} {α : typevec (n + 1)} : last_fun from_append1_drop_last = id := rfl @[simp] theorem drop_fun_id {n : ℕ} {α : typevec (n + 1)} : drop_fun id = id := rfl @[simp] theorem prod_map_id {n : ℕ} {α : typevec n} {β : typevec n} : prod.map id id = id := sorry @[simp] theorem subtype_val_diag_sub {n : ℕ} {α : typevec n} : comp (subtype_val (repeat_eq α)) diag_sub = prod.diag := sorry @[simp] theorem to_subtype_of_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : comp (to_subtype p) (of_subtype p) = id := sorry @[simp] theorem subtype_val_to_subtype {n : ℕ} {α : typevec n} (p : arrow α (repeat n Prop)) : comp (subtype_val p) (to_subtype p) = fun (_x : fin2 n) => subtype.val := sorry @[simp] theorem to_subtype_of_subtype_assoc {n : ℕ} {α : typevec n} {β : typevec n} (p : arrow α (repeat n Prop)) (f : arrow β (subtype_ p)) : comp (to_subtype p) (comp (of_subtype fun (i : fin2 n) (x : α i) => p i x) f) = f := sorry @[simp] theorem to_subtype'_of_subtype' {n : ℕ} {α : typevec n} (r : arrow (prod α α) (repeat n Prop)) : comp (to_subtype' r) (of_subtype' r) = id := sorry theorem subtype_val_to_subtype' {n : ℕ} {α : typevec n} (r : arrow (prod α α) (repeat n Prop)) : comp (subtype_val r) (to_subtype' r) = fun (i : fin2 n) (x : Subtype fun (x : α i × α i) => of_repeat (r i (prod.mk i (prod.fst x) (prod.snd x)))) => prod.mk i (prod.fst (subtype.val x)) (prod.snd (subtype.val x)) := sorry
0bc4992b0fbc4d37532080ed105dfd267308e42d
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Server/Utils.lean
1b6b5392eb4b51eb6184b84251fc3bed2b75d5fd
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
5,512
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Data.Position import Lean.Data.Lsp import Init.System.FilePath namespace IO def throwServerError (err : String) : IO α := throw (userError err) namespace FS.Stream /-- Chains two streams by creating a new stream s.t. writing to it just writes to `a` but reading from it also duplicates the read output into `b`, c.f. `a | tee b` on Unix. NB: if `a` is written to but this stream is never read from, the output will *not* be duplicated. Use this if you only care about the data that was actually read. -/ def chainRight (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { a with flush := a.flush *> b.flush read := fun sz => do let bs ← a.read sz b.write bs if flushEagerly then b.flush pure bs getLine := do let ln ← a.getLine b.putStr ln if flushEagerly then b.flush pure ln } /-- Like `tee a | b` on Unix. See `chainOut`. -/ def chainLeft (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { b with flush := a.flush *> b.flush write := fun bs => do a.write bs if flushEagerly then a.flush b.write bs putStr := fun s => do a.putStr s if flushEagerly then a.flush b.putStr s } /-- Prefixes all written outputs with `pre`. -/ def withPrefix (a : Stream) (pre : String) : Stream := { a with write := fun bs => do a.putStr pre a.write bs putStr := fun s => a.putStr (pre ++ s) } end FS.Stream end IO namespace Lean.Server structure DocumentMeta where uri : Lsp.DocumentUri version : Nat text : FileMap deriving Inhabited def replaceLspRange (text : FileMap) (r : Lsp.Range) (newText : String) : FileMap := let start := text.lspPosToUtf8Pos r.start let «end» := text.lspPosToUtf8Pos r.«end» let pre := text.source.extract 0 start let post := text.source.extract «end» text.source.bsize (pre ++ newText ++ post).toFileMap open IO /-- Duplicates an I/O stream to a log file `fName` in LEAN_SERVER_LOG_DIR if that envvar is set. -/ def maybeTee (fName : String) (isOut : Bool) (h : FS.Stream) : IO FS.Stream := do match (← IO.getEnv "LEAN_SERVER_LOG_DIR") with | none => pure h | some logDir => let hTee ← FS.Handle.mk (System.mkFilePath [logDir, fName]) FS.Mode.write true let hTee := FS.Stream.ofHandle hTee pure $ if isOut then hTee.chainLeft h true else h.chainRight hTee true /-- Transform the given path to a file:// URI. -/ def toFileUri (fname : System.FilePath) : Lsp.DocumentUri := let fname := fname.normalize.toString let fname := if System.Platform.isWindows then fname.map fun c => if c == '\\' then '/' else c else fname -- TODO(WN): URL-encode special characters -- Three slashes denote localhost. "file:///" ++ fname.dropWhile (· == '/') open Lsp /-- Returns the document contents with all changes applied, together with the position of the change which lands earliest in the file. Panics if there are no changes. -/ def foldDocumentChanges (changes : @& Array Lsp.TextDocumentContentChangeEvent) (oldText : FileMap) : FileMap × String.Pos := if changes.isEmpty then panic! "Lean.Server.foldDocumentChanges: empty change array" else let accumulateChanges : FileMap × String.Pos → TextDocumentContentChangeEvent → FileMap × String.Pos := fun ⟨newDocText, minStartOff⟩ change => match change with | TextDocumentContentChangeEvent.rangeChange (range : Range) (newText : String) => let startOff := oldText.lspPosToUtf8Pos range.start let newDocText := replaceLspRange newDocText range newText let minStartOff := minStartOff.min startOff ⟨newDocText, minStartOff⟩ | TextDocumentContentChangeEvent.fullChange (newText : String) => ⟨newText.toFileMap, 0⟩ -- NOTE: We assume Lean files are below 16 EiB. changes.foldl accumulateChanges (oldText, 0xffffffff) def publishDiagnostics (m : DocumentMeta) (diagnostics : Array Lsp.Diagnostic) (hOut : FS.Stream) : IO Unit := hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics : PublishDiagnosticsParams } } def publishMessages (m : DocumentMeta) (msgLog : MessageLog) (hOut : FS.Stream) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) publishDiagnostics m diagnostics.toArray hOut def publishProgress (m : DocumentMeta) (processing : Array LeanFileProgressProcessingInfo) (hOut : FS.Stream) : IO Unit := hOut.writeLspNotification { method := "$/lean/fileProgress" param := { textDocument := { uri := m.uri, version? := m.version } processing : LeanFileProgressParams } } def publishProgressAtPos (m : DocumentMeta) (pos : String.Pos) (hOut : FS.Stream) : IO Unit := publishProgress m #[{ range := ⟨m.text.utf8PosToLspPos pos, m.text.utf8PosToLspPos m.text.source.bsize⟩ }] hOut def publishProgressDone (m : DocumentMeta) (hOut : FS.Stream) : IO Unit := publishProgress m #[] hOut end Lean.Server namespace List universe u def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => if p hd then hd :: takeWhile p tl else [] end List
1c2c4586cc4707e6a6ae72bf841137baf9436635
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/list/perm.lean
8cb4f5691f06939a0e2358fd58768518397cffcf
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,971
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura List permutations. -/ import data.list.basic data.list.set open list setoid nat binary variables {A B : Type} inductive perm : list A → list A → Prop := | nil : perm [] [] | skip : Π (x : A) {l₁ l₂ : list A}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : A) (l : list A), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list A}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ namespace perm infix ~ := perm theorem eq_nil_of_perm_nil {l₁ : list A} (p : [] ~ l₁) : l₁ = [] := have gen : ∀ (l₂ : list A) (p : l₂ ~ l₁), l₂ = [] → l₁ = [], from take l₂ p, perm.induction_on p (λ h, h) (by contradiction) (by contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e, r₂ (r₁ e)), gen [] p rfl theorem not_perm_nil_cons (x : A) (l : list A) : ¬ [] ~ (x::l) := have gen : ∀ (l₁ l₂ : list A) (p : l₁ ~ l₂), l₁ = [] → l₂ = (x::l) → false, from take l₁ l₂ p, perm.induction_on p (by contradiction) (by contradiction) (by contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e₁ e₂, begin rewrite [e₂ at *, e₁ at *], have e₃ : l₂ = [], from eq_nil_of_perm_nil p₁, exact (r₂ e₃ rfl) end), assume p, gen [] (x::l) p rfl rfl protected theorem refl [refl] : ∀ (l : list A), l ~ l | [] := nil | (x::xs) := skip x (refl xs) protected theorem symm [symm] : ∀ {l₁ l₂ : list A}, l₁ ~ l₂ → l₂ ~ l₁ := take l₁ l₂ p, perm.induction_on p nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) attribute perm.trans [trans] theorem eqv (A : Type) : equivalence (@perm A) := mk_equivalence (@perm A) (@perm.refl A) (@perm.symm A) (@perm.trans A) protected definition is_setoid [instance] (A : Type) : setoid (list A) := setoid.mk (@perm A) (perm.eqv A) theorem mem_perm {a : A} {l₁ l₂ : list A} : l₁ ~ l₂ → a ∈ l₁ → a ∈ l₂ := assume p, perm.induction_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite this; apply !mem_cons) (suppose a ∈ l₁, or.inr (r₁ this))) (λ x y l ainyxl, or.elim (eq_or_mem_of_mem_cons ainyxl) (suppose a = y, by rewrite this; exact (or.inr !mem_cons)) (suppose a ∈ x::l, or.elim (eq_or_mem_of_mem_cons this) (suppose a = x, or.inl this) (suppose a ∈ l, or.inr (or.inr this)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem not_mem_perm {a : A} {l₁ l₂ : list A} : l₁ ~ l₂ → a ∉ l₁ → a ∉ l₂ := assume p nainl₁ ainl₂, absurd (mem_perm (perm.symm p) ainl₂) nainl₁ theorem perm_app_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (l₁++t₁) ~ (l₂++t₁) := assume p, perm.induction_on p !perm.refl (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, !swap) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (l++t₁) ~ (l++t₂) := list.induction_on l (λ p, p) (λ x xs r p, skip x (r p)) theorem perm_app [congr] {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁++t₁) ~ (l₂++t₂) := assume p₁ p₂, trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) theorem perm_app_cons (a : A) {h₁ h₂ t₁ t₂ : list A} : h₁ ~ h₂ → t₁ ~ t₂ → (h₁ ++ (a::t₁)) ~ (h₂ ++ (a::t₂)) := assume p₁ p₂, perm_app p₁ (skip a p₂) theorem perm_cons_app (a : A) : ∀ (l : list A), (a::l) ~ (l ++ [a]) | [] := !perm.refl | (x::xs) := calc a::x::xs ~ x::a::xs : swap x a xs ... ~ x::(xs++[a]) : skip x (perm_cons_app xs) theorem perm_cons_app_simp [simp] (a : A) : ∀ (l : list A), (l ++ [a]) ~ (a::l) := take l, perm.symm !perm_cons_app theorem perm_app_comm [simp] {l₁ l₂ : list A} : (l₁++l₂) ~ (l₂++l₁) := list.induction_on l₁ (by rewrite [append_nil_right, append_nil_left]) (λ a t r, calc a::(t++l₂) ~ a::(l₂++t) : skip a r ... ~ l₂++t++[a] : perm_cons_app ... = l₂++(t++[a]) : append.assoc ... ~ l₂++(a::t) : perm_app_right l₂ (perm.symm (perm_cons_app a t))) theorem length_eq_length_of_perm {l₁ l₂ : list A} : l₁ ~ l₂ → length l₁ = length l₂ := assume p, perm.induction_on p rfl (λ x l₁ l₂ p r, by rewrite [*length_cons, r]) (λ x y l, by rewrite *length_cons) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem eq_singleton_of_perm_inv (a : A) {l : list A} : [a] ~ l → l = [a] := have gen : ∀ l₂, perm l₂ l → l₂ = [a] → l = [a], from take l₂, assume p, perm.induction_on p (λ e, e) (λ x l₁ l₂ p r e, begin injection e with e₁ e₂, rewrite [e₁, e₂ at p], have h₁ : l₂ = [], from eq_nil_of_perm_nil p, substvars end) (λ x y l e, by injection e; contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e, r₂ (r₁ e)), assume p, gen [a] p rfl theorem eq_singleton_of_perm (a b : A) : [a] ~ [b] → a = b := assume p, begin injection eq_singleton_of_perm_inv a p with e₁, rewrite e₁ end theorem perm_rev : ∀ (l : list A), l ~ (reverse l) | [] := nil | (x::xs) := calc x::xs ~ xs++[x] : perm_cons_app x xs ... ~ reverse xs ++ [x] : perm_app_left [x] (perm_rev xs) ... = reverse (x::xs) : by rewrite [reverse_cons, concat_eq_append] theorem perm_rev_simp [simp] : ∀ (l : list A), (reverse l) ~ l := take l, perm.symm (perm_rev l) theorem perm_middle (a : A) (l₁ l₂ : list A) : (a::l₁)++l₂ ~ l₁++(a::l₂) := calc (a::l₁) ++ l₂ = a::(l₁++l₂) : rfl ... ~ l₁++l₂++[a] : perm_cons_app ... = l₁++(l₂++[a]) : append.assoc ... ~ l₁++(a::l₂) : perm_app_right l₁ (perm.symm (perm_cons_app a l₂)) theorem perm_middle_simp [simp] (a : A) (l₁ l₂ : list A) : l₁++(a::l₂) ~ (a::l₁)++l₂ := perm.symm !perm_middle theorem perm_cons_app_cons {l l₁ l₂ : list A} (a : A) : l ~ l₁++l₂ → a::l ~ l₁++(a::l₂) := assume p, calc a::l ~ l++[a] : perm_cons_app ... ~ l₁++l₂++[a] : perm_app_left [a] p ... = l₁++(l₂++[a]) : append.assoc ... ~ l₁++(a::l₂) : perm_app_right l₁ (perm.symm (perm_cons_app a l₂)) open decidable theorem perm_erase [H : decidable_eq A] {a : A} : ∀ {l : list A}, a ∈ l → l ~ a::(erase a l) | [] h := absurd h !not_mem_nil | (x::t) h := by_cases (assume aeqx : a = x, by rewrite [aeqx, erase_cons_head]) (assume naeqx : a ≠ x, have aint : a ∈ t, from mem_of_ne_of_mem naeqx h, have aux : t ~ a :: erase a t, from perm_erase aint, calc x::t ~ x::a::(erase a t) : skip x aux ... ~ a::x::(erase a t) : swap ... = a::(erase a (x::t)) : by rewrite [!erase_cons_tail naeqx]) theorem erase_perm_erase_of_perm [congr] [H : decidable_eq A] (a : A) {l₁ l₂ : list A} : l₁ ~ l₂ → erase a l₁ ~ erase a l₂ := assume p, perm.induction_on p nil (λ x t₁ t₂ p r, by_cases (assume aeqx : a = x, by rewrite [aeqx, *erase_cons_head]; exact p) (assume naeqx : a ≠ x, by rewrite [*erase_cons_tail _ naeqx]; exact (skip x r))) (λ x y l, by_cases (assume aeqx : a = x, by_cases (assume aeqy : a = y, by rewrite [-aeqx, -aeqy]) (assume naeqy : a ≠ y, by rewrite [-aeqx, erase_cons_tail _ naeqy, *erase_cons_head])) (assume naeqx : a ≠ x, by_cases (assume aeqy : a = y, by rewrite [-aeqy, erase_cons_tail _ naeqx, *erase_cons_head]) (assume naeqy : a ≠ y, by rewrite[erase_cons_tail _ naeqx, *erase_cons_tail _ naeqy, erase_cons_tail _ naeqx]; exact !swap))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_induction_on {P : list A → list A → Prop} {l₁ l₂ : list A} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l | [] := h₁ | (x::xs) := h₂ x xs xs !perm.refl (P_refl xs), perm.induction_on p h₁ h₂ (λ x y l, h₃ x y l l !perm.refl !P_refl) h₄ theorem xswap {l₁ l₂ : list A} (x y : A) : l₁ ~ l₂ → x::y::l₁ ~ y::x::l₂ := assume p, calc x::y::l₁ ~ y::x::l₁ : swap ... ~ y::x::l₂ : skip y (skip x p) theorem perm_map [congr] (f : A → B) {l₁ l₂ : list A} : l₁ ~ l₂ → map f l₁ ~ map f l₂ := assume p, perm_induction_on p nil (λ x l₁ l₂ p r, skip (f x) r) (λ x y l₁ l₂ p r, xswap (f y) (f x) r) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) lemma perm_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → l₁~a::l₂ := assume q, qeq.induction_on q (λ h, !perm.refl) (λ b t₁ t₂ q₁ r₁, calc b::t₂ ~ b::a::t₁ : skip b r₁ ... ~ a::b::t₁ : swap) /- permutation is decidable if A has decidable equality -/ section dec open decidable variable [Ha : decidable_eq A] include Ha definition decidable_perm_aux : ∀ (n : nat) (l₁ l₂ : list A), length l₁ = n → length l₂ = n → decidable (l₁ ~ l₂) | 0 l₁ l₂ H₁ H₂ := assert l₁n : l₁ = [], from eq_nil_of_length_eq_zero H₁, assert l₂n : l₂ = [], from eq_nil_of_length_eq_zero H₂, by rewrite [l₁n, l₂n]; exact (inl perm.nil) | (n+1) (x::t₁) l₂ H₁ H₂ := by_cases (assume xinl₂ : x ∈ l₂, let t₂ : list A := erase x l₂ in have len_t₁ : length t₁ = n, begin injection H₁ with e, exact e end, assert length t₂ = pred (length l₂), from length_erase_of_mem xinl₂, assert length t₂ = n, by rewrite [this, H₂], match decidable_perm_aux n t₁ t₂ len_t₁ this with | inl p := inl (calc x::t₁ ~ x::(erase x l₂) : skip x p ... ~ l₂ : perm_erase xinl₂) | inr np := inr (λ p : x::t₁ ~ l₂, assert erase x (x::t₁) ~ erase x l₂, from erase_perm_erase_of_perm x p, have t₁ ~ erase x l₂, by rewrite [erase_cons_head at this]; exact this, absurd this np) end) (assume nxinl₂ : x ∉ l₂, inr (λ p : x::t₁ ~ l₂, absurd (mem_perm p !mem_cons) nxinl₂)) definition decidable_perm [instance] : ∀ (l₁ l₂ : list A), decidable (l₁ ~ l₂) := λ l₁ l₂, by_cases (assume eql : length l₁ = length l₂, decidable_perm_aux (length l₂) l₁ l₂ eql rfl) (assume neql : length l₁ ≠ length l₂, inr (λ p : l₁ ~ l₂, absurd (length_eq_length_of_perm p) neql)) end dec -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr {P : Prop} {a b : A} {l₁ l₂ l₃ : list A} : a::l₁ = l₂++(b::l₃) → (l₂ = [] → a = b → l₁ = l₃ → P) → (∀ t, l₂ = a::t → l₁ = t++(b::l₃) → P) → P := match l₂ with | [] := λ e h₁ h₂, by injection e with e₁ e₂; exact h₁ rfl e₁ e₂ | h::t := λ e h₁ h₂, begin injection e with e₁ e₂, rewrite e₁ at h₂, exact h₂ t rfl e₂ end end -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr₂ {P : Prop} {a b c : A} {l₁ l₂ l₃ : list A} : a::b::l₁ = l₂++(c::l₃) → (l₂ = [] → l₃ = b::l₁ → a = c → P) → (l₂ = [a] → b = c → l₁ = l₃ → P) → (∀ t, l₂ = a::b::t → l₁ = t++(c::l₃) → P) → P := match l₂ with | [] := λ e H₁ H₂ H₃, begin injection e with a_eq_c b_l₁_eq_l₃, exact H₁ rfl (eq.symm b_l₁_eq_l₃) a_eq_c end | [h₁] := λ e H₁ H₂ H₃, begin rewrite [append_cons at e, append_nil_left at e], injection e with a_eq_h₁ b_eq_c l₁_eq_l₃, rewrite [a_eq_h₁ at H₂, b_eq_c at H₂, l₁_eq_l₃ at H₂], exact H₂ rfl rfl rfl end | h₁::h₂::t₂ := λ e H₁ H₂ H₃, begin injection e with a_eq_h₁ b_eq_h₂ l₁_eq, rewrite [a_eq_h₁ at H₃, b_eq_h₂ at H₃], exact H₃ t₂ rfl l₁_eq end end /- permutation inversion -/ theorem perm_inv_core {l₁ l₂ : list A} (p' : l₁ ~ l₂) : ∀ {a s₁ s₂}, l₁≈a|s₁ → l₂≈a|s₂ → s₁ ~ s₂ := perm_induction_on p' (λ a s₁ s₂ e₁ e₂, have innil : a ∈ [], from mem_head_of_qeq e₁, absurd innil !not_mem_nil) (λ x t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, obtain (s₁₁ s₁₂ : list A) (C₁₁ : s₁ = s₁₁ ++ s₁₂) (C₁₂ : x::t₁ = s₁₁++(a::s₁₂)), from qeq_split e₁, obtain (s₂₁ s₂₂ : list A) (C₂₁ : s₂ = s₂₁ ++ s₂₂) (C₂₂ : x::t₂ = s₂₁++(a::s₂₂)), from qeq_split e₂, discr C₁₂ (λ (s₁₁_eq : s₁₁ = []) (x_eq_a : x = a) (t₁_eq : t₁ = s₁₂), assert s₁_p : s₁ ~ t₂, from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = t₁ : by rewrite [-t₁_eq, s₁₁_eq, append_nil_left] ... ~ t₂ : p, discr C₂₂ (λ (s₂₁_eq : s₂₁ = []) (x_eq_a : x = a) (t₂_eq: t₂ = s₂₂), proof calc s₁ ~ t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [-t₂_eq, s₂₁_eq, append_nil_left] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ t₂ : s₁_p ... = ts₂₁++(a::s₂₂) : t₂_eq ... ~ (a::ts₂₁)++s₂₂ : !perm_middle ... = s₂₁ ++ s₂₂ : by rewrite [-x_eq_a, -s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed)) (λ (ts₁₁ : list A) (s₁₁_eq : s₁₁ = x::ts₁₁) (t₁_eq : t₁ = ts₁₁++(a::s₁₂)), assert t₁_qeq : t₁ ≈ a|(ts₁₁++s₁₂), by rewrite t₁_eq; exact !qeq_app, assert s₁_eq : s₁ = x::(ts₁₁++s₁₂), from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = x::(ts₁₁++ s₁₂) : by rewrite s₁₁_eq, discr C₂₂ (λ (s₂₁_eq : s₂₁ = []) (x_eq_a : x = a) (t₂_eq: t₂ = s₂₂), proof calc s₁ = a::(ts₁₁++s₁₂) : by rewrite [s₁_eq, x_eq_a] ... ~ ts₁₁++(a::s₁₂) : !perm_middle ... = t₁ : t₁_eq ... ~ t₂ : p ... = s₂ : by rewrite [t₂_eq, C₂₁, s₂₁_eq, append_nil_left] qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), assert t₂_qeq : t₂ ≈ a|(ts₂₁++s₂₂), by rewrite t₂_eq; exact !qeq_app, proof calc s₁ = x::(ts₁₁++s₁₂) : s₁_eq ... ~ x::(ts₂₁++s₂₂) : skip x (r t₁_qeq t₂_qeq) ... = s₂ : by rewrite [-append_cons, -s₂₁_eq, C₂₁] qed))) (λ x y t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, obtain (s₁₁ s₁₂ : list A) (C₁₁ : s₁ = s₁₁ ++ s₁₂) (C₁₂ : y::x::t₁ = s₁₁++(a::s₁₂)), from qeq_split e₁, obtain (s₂₁ s₂₂ : list A) (C₂₁ : s₂ = s₂₁ ++ s₂₂) (C₂₂ : x::y::t₂ = s₂₁++(a::s₂₂)), from qeq_split e₂, discr₂ C₁₂ (λ (s₁₁_eq : s₁₁ = []) (s₁₂_eq : s₁₂ = x::t₁) (y_eq_a : y = a), assert s₁_p : s₁ ~ x::t₂, from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = x::t₁ : by rewrite [s₁₂_eq, s₁₁_eq, append_nil_left] ... ~ x::t₂ : skip x p, discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ ~ x::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [x_eq_a, -y_eq_a, -s₂₂_eq, s₂₁_eq, append_nil_left] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ ~ x::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [t₂_eq, s₂₁_eq, append_cons] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ x::t₂ : s₁_p ... = x::(ts₂₁++(y::s₂₂)) : by rewrite [t₂_eq, -y_eq_a] ... ~ x::y::(ts₂₁++s₂₂) : skip x !perm_middle ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, append_cons] ... = s₂ : by rewrite C₂₁ qed)) (λ (s₁₁_eq : s₁₁ = [y]) (x_eq_a : x = a) (t₁_eq : t₁ = s₁₂), assert s₁_p : s₁ ~ y::t₂, from calc s₁ = y::t₁ : by rewrite [C₁₁, s₁₁_eq, t₁_eq] ... ~ y::t₂ : skip y p, discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ ~ y::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, s₂₂_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ ~ y::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, t₂_eq, y_eq_a, -x_eq_a] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ y::t₂ : s₁_p ... = y::(ts₂₁++(x::s₂₂)) : by rewrite [t₂_eq, -x_eq_a] ... ~ y::x::(ts₂₁++s₂₂) : skip y !perm_middle ... ~ x::y::(ts₂₁++s₂₂) : swap ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed)) (λ (ts₁₁ : list A) (s₁₁_eq : s₁₁ = y::x::ts₁₁) (t₁_eq : t₁ = ts₁₁++(a::s₁₂)), assert s₁_eq : s₁ = y::x::(ts₁₁++s₁₂), by rewrite [C₁₁, s₁₁_eq], discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ = y::a::(ts₁₁++s₁₂) : by rewrite [s₁_eq, x_eq_a] ... ~ y::(ts₁₁++(a::s₁₂)) : skip y !perm_middle ... = y::t₁ : by rewrite t₁_eq ... ~ y::t₂ : skip y p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, s₂₂_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ = y::x::(ts₁₁++s₁₂) : by rewrite s₁_eq ... ~ x::y::(ts₁₁++s₁₂) : swap ... = x::a::(ts₁₁++s₁₂) : by rewrite y_eq_a ... ~ x::(ts₁₁++(a::s₁₂)) : skip x !perm_middle ... = x::t₁ : by rewrite t₁_eq ... ~ x::t₂ : skip x p ... = s₂₁ ++ s₂₂ : by rewrite [t₂_eq, s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), assert t₁_qeq : t₁ ≈ a|(ts₁₁++s₁₂), by rewrite t₁_eq; exact !qeq_app, assert t₂_qeq : t₂ ≈ a|(ts₂₁++s₂₂), by rewrite t₂_eq; exact !qeq_app, assert p_aux : ts₁₁++s₁₂ ~ ts₂₁++s₂₂, from r t₁_qeq t₂_qeq, proof calc s₁ = y::x::(ts₁₁++s₁₂) : by rewrite s₁_eq ... ~ y::x::(ts₂₁++s₂₂) : skip y (skip x p_aux) ... ~ x::y::(ts₂₁++s₂₂) : swap ... = s₂₁ ++ s₂₂ : by rewrite s₂₁_eq ... = s₂ : by rewrite C₂₁ qed))) (λ t₁ t₂ t₃ p₁ p₂ (r₁ : ∀{a s₁ s₂}, t₁ ≈ a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) (r₂ : ∀{a s₁ s₂}, t₂ ≈ a|s₁ → t₃≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, have a ∈ t₁, from mem_head_of_qeq e₁, have a ∈ t₂, from mem_perm p₁ this, obtain (t₂' : list A) (e₂' : t₂≈a|t₂'), from qeq_of_mem this, calc s₁ ~ t₂' : r₁ e₁ e₂' ... ~ s₂ : r₂ e₂' e₂) theorem perm_cons_inv {a : A} {l₁ l₂ : list A} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := assume p, perm_inv_core p (qeq.qhead a l₁) (qeq.qhead a l₂) theorem perm_app_inv {a : A} {l₁ l₂ l₃ l₄ : list A} : l₁++(a::l₂) ~ l₃++(a::l₄) → l₁++l₂ ~ l₃++l₄ := assume p : l₁++(a::l₂) ~ l₃++(a::l₄), have p' : a::(l₁++l₂) ~ a::(l₃++l₄), from calc a::(l₁++l₂) ~ l₁++(a::l₂) : perm_middle ... ~ l₃++(a::l₄) : p ... ~ a::(l₃++l₄) : perm.symm (!perm_middle), perm_cons_inv p' section foldl variables {f : B → A → B} {l₁ l₂ : list A} variable rcomm : right_commutative f include rcomm theorem foldl_eq_of_perm : l₁ ~ l₂ → ∀ b, foldl f b l₁ = foldl f b l₂ := assume p, perm_induction_on p (λ b, by rewrite *foldl_nil) (λ x t₁ t₂ p r b, calc foldl f b (x::t₁) = foldl f (f b x) t₁ : foldl_cons ... = foldl f (f b x) t₂ : r (f b x) ... = foldl f b (x::t₂) : foldl_cons) (λ x y t₁ t₂ p r b, calc foldl f b (y :: x :: t₁) = foldl f (f (f b y) x) t₁ : by rewrite foldl_cons ... = foldl f (f (f b x) y) t₁ : by rewrite rcomm ... = foldl f (f (f b x) y) t₂ : r (f (f b x) y) ... = foldl f b (x :: y :: t₂) : by rewrite foldl_cons) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) end foldl section foldr variables {f : A → B → B} {l₁ l₂ : list A} variable lcomm : left_commutative f include lcomm theorem foldr_eq_of_perm [congr] : l₁ ~ l₂ → ∀ b, foldr f b l₁ = foldr f b l₂ := assume p, perm_induction_on p (λ b, by rewrite *foldl_nil) (λ x t₁ t₂ p r b, calc foldr f b (x::t₁) = f x (foldr f b t₁) : foldr_cons ... = f x (foldr f b t₂) : by rewrite [r b] ... = foldr f b (x::t₂) : foldr_cons) (λ x y t₁ t₂ p r b, calc foldr f b (y :: x :: t₁) = f y (f x (foldr f b t₁)) : by rewrite foldr_cons ... = f x (f y (foldr f b t₁)) : by rewrite lcomm ... = f x (f y (foldr f b t₂)) : by rewrite [r b] ... = foldr f b (x :: y :: t₂) : by rewrite foldr_cons) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) end foldr theorem perm_erase_dup_of_perm [congr] [H : decidable_eq A] {l₁ l₂ : list A} : l₁ ~ l₂ → erase_dup l₁ ~ erase_dup l₂ := assume p, perm_induction_on p nil (λ x t₁ t₂ p r, by_cases (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup xint₁)), by rewrite [erase_dup_cons_of_mem xint₁, erase_dup_cons_of_mem xint₂]; exact r) (λ nxint₁ : x ∉ t₁, assert nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by rewrite [erase_dup_cons_of_not_mem nxint₂, erase_dup_cons_of_not_mem nxint₁]; exact (skip x r))) (λ y x t₁ t₂ p r, by_cases (λ xinyt₁ : x ∈ y::t₁, by_cases (λ yint₁ : y ∈ t₁, assert yint₂ : y ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup yint₁)), assert yinxt₂ : y ∈ x::t₂, from or.inr (yint₂), or.elim (eq_or_mem_of_mem_cons xinyt₁) (λ xeqy : x = y, assert xint₂ : x ∈ t₂, by rewrite [-xeqy at yint₂]; exact yint₂, begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup xint₁)), begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end)) (λ nyint₁ : y ∉ t₁, assert nyint₂ : y ∉ t₂, from assume yint₂ : y ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup yint₂))) nyint₁, by_cases (λ xeqy : x = y, assert nxint₂ : x ∉ t₂, by rewrite [-xeqy at nyint₂]; exact nyint₂, assert yinxt₂ : y ∈ x::t₂, by rewrite [xeqy]; exact !mem_cons, begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂, xeqy], exact skip y r end) (λ xney : x ≠ y, have x ∈ t₁, from or_resolve_right xinyt₁ xney, assert x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup this)), assert y ∉ x::t₂, from suppose y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons this) (λ h, absurd h (ne.symm xney)) (λ h, absurd h nyint₂), begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_not_mem `y ∉ x::t₂`, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_mem `x ∈ t₂`], exact skip y r end))) (λ nxinyt₁ : x ∉ y::t₁, have xney : x ≠ y, from ne_of_not_mem_cons nxinyt₁, have nxint₁ : x ∉ t₁, from not_mem_of_not_mem_cons nxinyt₁, assert nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by_cases (λ yint₁ : y ∈ t₁, assert yinxt₂ : y ∈ x::t₂, from or.inr (mem_of_mem_erase_dup (mem_perm r (mem_erase_dup yint₁))), begin rewrite [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_not_mem nxint₂], exact skip x r end) (λ nyint₁ : y ∉ t₁, assert nyinxt₂ : y ∉ x::t₂, from assume yinxt₂ : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons yinxt₂) (λ h, absurd h (ne.symm xney)) (λ h, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup h))) nyint₁), begin rewrite [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_not_mem nyinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂], exact xswap x y r end))) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂, trans r₁ r₂) section perm_union variable [H : decidable_eq A] include H theorem perm_union_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (union l₁ t₁) ~ (union l₂ t₁) := assume p, perm.induction_on p (by rewrite [nil_union]) (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint₁]; exact r₁) (λ nxint₁ : x ∉ t₁, by rewrite [*union_cons_of_not_mem _ nxint₁]; exact (skip _ r₁))) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint, *union_cons_of_mem _ yint, *union_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*union_cons_of_mem _ yint, *union_cons_of_not_mem _ nxint, union_cons_of_mem _ yint])) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint, *union_cons_of_not_mem _ nyint, union_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*union_cons_of_not_mem _ nxint, *union_cons_of_not_mem _ nyint, union_cons_of_not_mem _ nxint]; exact !swap))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_union_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (union l t₁) ~ (union l t₂) := list.induction_on l (λ p, by rewrite [*union_nil]; exact p) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_perm p xint₁, by rewrite [union_cons_of_mem _ xint₁, union_cons_of_mem _ xint₂]; exact (r p)) (λ nxint₁ : x ∉ t₁, assert nxint₂ : x ∉ t₂, from not_mem_perm p nxint₁, by rewrite [union_cons_of_not_mem _ nxint₁, union_cons_of_not_mem _ nxint₂]; exact (skip _ (r p)))) theorem perm_union [congr] {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (union l₁ t₁) ~ (union l₂ t₂) := assume p₁ p₂, trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) end perm_union section perm_insert variable [H : decidable_eq A] include H theorem perm_insert [congr] (a : A) {l₁ l₂ : list A} : l₁ ~ l₂ → (insert a l₁) ~ (insert a l₂) := assume p, by_cases (λ ainl₁ : a ∈ l₁, assert ainl₂ : a ∈ l₂, from mem_perm p ainl₁, by rewrite [insert_eq_of_mem ainl₁, insert_eq_of_mem ainl₂]; exact p) (λ nainl₁ : a ∉ l₁, assert nainl₂ : a ∉ l₂, from not_mem_perm p nainl₁, by rewrite [insert_eq_of_not_mem nainl₁, insert_eq_of_not_mem nainl₂]; exact (skip _ p)) end perm_insert section perm_inter variable [H : decidable_eq A] include H theorem perm_inter_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (inter l₁ t₁) ~ (inter l₂ t₁) := assume p, perm.induction_on p !perm.refl (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint₁]; exact (skip x r₁)) (λ nxint₁ : x ∉ t₁, by rewrite [*inter_cons_of_not_mem _ nxint₁]; exact r₁)) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint, *inter_cons_of_mem _ yint, *inter_cons_of_mem _ xint]; exact !swap) (λ nxint : x ∉ t₁, by rewrite [*inter_cons_of_mem _ yint, *inter_cons_of_not_mem _ nxint, inter_cons_of_mem _ yint])) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint, *inter_cons_of_not_mem _ nyint, inter_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*inter_cons_of_not_mem _ nxint, *inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nxint]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_inter_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (inter l t₁) ~ (inter l t₂) := list.induction_on l (λ p, by rewrite [*inter_nil]) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_perm p xint₁, by rewrite [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₂]; exact (skip _ (r p))) (λ nxint₁ : x ∉ t₁, assert nxint₂ : x ∉ t₂, from not_mem_perm p nxint₁, by rewrite [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₂]; exact (r p))) theorem perm_inter [congr] {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (inter l₁ t₁) ~ (inter l₂ t₂) := assume p₁ p₂, trans (perm_inter_left t₁ p₁) (perm_inter_right l₂ p₂) end perm_inter /- extensionality -/ section ext open eq.ops theorem perm_ext : ∀ {l₁ l₂ : list A}, nodup l₁ → nodup l₂ → (∀a, a ∈ l₁ ↔ a ∈ l₂) → l₁ ~ l₂ | [] [] d₁ d₂ e := !perm.nil | [] (a₂::t₂) d₁ d₂ e := absurd (iff.mpr (e a₂) !mem_cons) (not_mem_nil a₂) | (a₁::t₁) [] d₁ d₂ e := absurd (iff.mp (e a₁) !mem_cons) (not_mem_nil a₁) | (a₁::t₁) (a₂::t₂) d₁ d₂ e := have a₁ ∈ a₂::t₂, from iff.mp (e a₁) !mem_cons, have ∃ s₁ s₂, a₂::t₂ = s₁++(a₁::s₂), from mem_split this, obtain (s₁ s₂ : list A) (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)), from this, have dt₂' : nodup (a₁::(s₁++s₂)), from nodup_head (by rewrite [t₂_eq at d₂]; exact d₂), have eqv : ∀a, a ∈ t₁ ↔ a ∈ s₁++s₂, from take a, iff.intro (suppose a ∈ t₁, assert a ∈ a₂::t₂, from iff.mp (e a) (mem_cons_of_mem _ this), have a ∈ s₁++(a₁::s₂), by rewrite [t₂_eq at this]; exact this, or.elim (mem_or_mem_of_mem_append this) (suppose a ∈ s₁, mem_append_left s₂ this) (suppose a ∈ a₁::s₂, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, assert a₁ ∉ t₁, from not_mem_of_nodup_cons d₁, by subst a; contradiction) (suppose a ∈ s₂, mem_append_right s₁ this))) (suppose a ∈ s₁ ++ s₂, or.elim (mem_or_mem_of_mem_append this) (suppose a ∈ s₁, have a ∈ a₂::t₂, from by rewrite [t₂_eq]; exact (mem_append_left _ this), have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', assert a₁ ∉ s₁, from not_mem_of_not_mem_append_left this, by subst a; contradiction) (suppose a ∈ t₁, this)) (suppose a ∈ s₂, have a ∈ a₂::t₂, from by rewrite [t₂_eq]; exact (mem_append_right _ (mem_cons_of_mem _ this)), have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', assert a₁ ∉ s₂, from not_mem_of_not_mem_append_right this, by subst a; contradiction) (suppose a ∈ t₁, this))), have ds₁s₂ : nodup (s₁++s₂), from nodup_of_nodup_cons dt₂', have nodup t₁, from nodup_of_nodup_cons d₁, calc a₁::t₁ ~ a₁::(s₁++s₂) : skip a₁ (perm_ext this ds₁s₂ eqv) ... ~ s₁++(a₁::s₂) : !perm_middle ... = a₂::t₂ : by rewrite t₂_eq end ext theorem nodup_of_perm_of_nodup {l₁ l₂ : list A} : l₁ ~ l₂ → nodup l₁ → nodup l₂ := assume h, perm.induction_on h (λ h, h) (λ a l₁ l₂ p ih nd, have nodup l₁, from nodup_of_nodup_cons nd, have nodup l₂, from ih this, have a ∉ l₁, from not_mem_of_nodup_cons nd, have a ∉ l₂, from suppose a ∈ l₂, absurd (mem_perm (perm.symm p) this) `a ∉ l₁`, nodup_cons `a ∉ l₂` `nodup l₂`) (λ x y l₁ nd, have nodup (x::l₁), from nodup_of_nodup_cons nd, have nodup l₁, from nodup_of_nodup_cons this, have x ∉ l₁, from not_mem_of_nodup_cons `nodup (x::l₁)`, have y ∉ x::l₁, from not_mem_of_nodup_cons nd, have x ≠ y, using this, from suppose x = y, begin subst x, exact absurd !mem_cons `y ∉ y::l₁` end, have y ∉ l₁, from not_mem_of_not_mem_cons `y ∉ x::l₁`, have x ∉ y::l₁, from not_mem_cons_of_ne_of_not_mem `x ≠ y` `x ∉ l₁`, have nodup (y::l₁), from nodup_cons `y ∉ l₁` `nodup l₁`, show nodup (x::y::l₁), from nodup_cons `x ∉ y::l₁` `nodup (y::l₁)`) (λ l₁ l₂ l₃ p₁ p₂ ih₁ ih₂ nd, ih₂ (ih₁ nd)) /- product -/ section product theorem perm_product_left {l₁ l₂ : list A} (t₁ : list B) : l₁ ~ l₂ → (product l₁ t₁) ~ (product l₂ t₁) := assume p : l₁ ~ l₂, perm.induction_on p !perm.refl (λ x l₁ l₂ p r, perm_app (perm.refl (map _ t₁)) r) (λ x y l, let m₁ := map (λ b, (x, b)) t₁ in let m₂ := map (λ b, (y, b)) t₁ in let c := product l t₁ in calc m₂ ++ (m₁ ++ c) = (m₂ ++ m₁) ++ c : by rewrite append.assoc ... ~ (m₁ ++ m₂) ++ c : perm_app !perm_app_comm !perm.refl ... = m₁ ++ (m₂ ++ c) : by rewrite append.assoc) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_product_right (l : list A) {t₁ t₂ : list B} : t₁ ~ t₂ → (product l t₁) ~ (product l t₂) := list.induction_on l (λ p, by rewrite [*nil_product]) (λ a t r p, perm_app (perm_map _ p) (r p)) theorem perm_product [congr] {l₁ l₂ : list A} {t₁ t₂ : list B} : l₁ ~ l₂ → t₁ ~ t₂ → (product l₁ t₁) ~ (product l₂ t₂) := assume p₁ p₂, trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) end product /- filter -/ theorem perm_filter [congr] {l₁ l₂ : list A} {p : A → Prop} [decp : decidable_pred p] : l₁ ~ l₂ → (filter p l₁) ~ (filter p l₂) := assume u, perm.induction_on u perm.nil (take x l₁' l₂', assume u' : l₁' ~ l₂', assume u'' : filter p l₁' ~ filter p l₂', decidable.by_cases (suppose p x, by rewrite [*filter_cons_of_pos _ this]; apply perm.skip; apply u'') (suppose ¬ p x, by rewrite [*filter_cons_of_neg _ this]; apply u'')) (take x y l, decidable.by_cases (assume H1 : p x, decidable.by_cases (assume H2 : p y, begin rewrite [filter_cons_of_pos _ H1, *filter_cons_of_pos _ H2, filter_cons_of_pos _ H1], apply perm.swap end) (assume H2 : ¬ p y, by rewrite [filter_cons_of_pos _ H1, *filter_cons_of_neg _ H2, filter_cons_of_pos _ H1])) (assume H1 : ¬ p x, decidable.by_cases (assume H2 : p y, by rewrite [filter_cons_of_neg _ H1, *filter_cons_of_pos _ H2, filter_cons_of_neg _ H1]) (assume H2 : ¬ p y, by rewrite [filter_cons_of_neg _ H1, *filter_cons_of_neg _ H2, filter_cons_of_neg _ H1]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) section count variable [decA : decidable_eq A] include decA theorem count_eq_of_perm {l₁ l₂ : list A} : l₁ ~ l₂ → ∀ a, count a l₁ = count a l₂ := suppose l₁ ~ l₂, perm.induction_on this (λ a, rfl) (λ x l₁ l₂ p h a, by rewrite [*count_cons, *h a]) (λ x y l a, by_cases (suppose a = x, by_cases (suppose a = y, begin subst x, subst y end) (suppose a ≠ y, begin subst x, rewrite [count_cons_of_ne this, *count_cons_eq, count_cons_of_ne this] end)) (suppose a ≠ x, by_cases (suppose a = y, begin subst y, rewrite [count_cons_of_ne this, *count_cons_eq, count_cons_of_ne this] end) (suppose a ≠ y, begin rewrite [count_cons_of_ne `a≠x`, *count_cons_of_ne `a≠y`, count_cons_of_ne `a≠x`] end))) (λ l₁ l₂ l₃ p₁ p₂ h₁ h₂ a, eq.trans (h₁ a) (h₂ a)) end count end perm
af1c5f54a1c31f323f3f3a8ae7b1145b31ebd550
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/punit.lean
35689c5febe359a9c4dbf537014bd758d1c8eea0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,631
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.punit import Mathlib.category_theory.limits.limits import Mathlib.PostPort universes v u_1 namespace Mathlib /-! # `discrete punit` has limits and colimits Mostly for the sake of constructing trivial examples, we show all (co)cones into `discrete punit` are (co)limit (co)cones, and `discrete punit` has all (co)limits. -/ namespace category_theory.limits /-- Any cone over a functor into `punit` is a limit cone. -/ def punit_cone_is_limit {J : Type v} [small_category J] {F : J ⥤ discrete PUnit} {c : cone F} : is_limit c := is_limit.mk sorry /-- Any cocone over a functor into `punit` is a colimit cocone. -/ def punit_cocone_is_colimit {J : Type v} [small_category J] {F : J ⥤ discrete PUnit} {c : cocone F} : is_colimit c := is_colimit.mk sorry protected instance category_theory.discrete.has_limits : has_limits (discrete PUnit) := has_limits.mk fun (J : Type u_1) (𝒥 : small_category J) => has_limits_of_shape.mk fun (F : J ⥤ discrete PUnit) => has_limit.mk' (Nonempty.intro (limit_cone.mk sorry (is_limit.mk sorry))) protected instance category_theory.discrete.has_colimits : has_colimits (discrete PUnit) := has_colimits.mk fun (J : Type u_1) (𝒥 : small_category J) => has_colimits_of_shape.mk fun (F : J ⥤ discrete PUnit) => has_colimit.mk' (Nonempty.intro (colimit_cocone.mk sorry (is_colimit.mk sorry)))
78862c0d122e6c551fc67e65dfe96d4d9bbb7261
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Tactic/NormNum.lean
f9e91b6006ff16ef808dd004e1e7f65bdbbb5577
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
6,456
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Lean.Elab.Tactic.Basic import Mathlib.Algebra.Ring.Basic import Mathlib.Tactic.Core namespace Lean /-- Return true if `e` is one of the following - A nat literal (numeral) - `Nat.zero` - `Nat.succ x` where `isNumeral x` - `OfNat.ofNat _ x _` where `isNumeral x` -/ partial def Expr.numeral? (e : Expr) : Option Nat := if let some n := e.natLit? then n else let f := e.getAppFn if !f.isConst then none else let fName := f.constName! if fName == ``Nat.succ && e.getAppNumArgs == 1 then (numeral? e.appArg!).map Nat.succ else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then numeral? (e.getArg! 1) else if fName == ``Nat.zero && e.getAppNumArgs == 0 then some 0 else none namespace Meta def mkOfNatLit (u : Level) (α sα n : Expr) : Expr := let inst := mkApp3 (mkConst ``Numeric.OfNat [u]) α n sα mkApp3 (mkConst ``OfNat.ofNat [u]) α n inst namespace NormNum def isNat [Semiring α] (a : α) (n : ℕ) := a = OfNat.ofNat n class LawfulOfNat (α) [Semiring α] (n) [OfNat α n] : Prop where isNat_ofNat : isNat (OfNat.ofNat n : α) n instance (α) [Semiring α] : LawfulOfNat α n := ⟨rfl⟩ instance (α) [Semiring α] : LawfulOfNat α (nat_lit 0) := ⟨rfl⟩ instance (α) [Semiring α] : LawfulOfNat α (nat_lit 1) := ⟨rfl⟩ instance : LawfulOfNat Nat n := ⟨rfl⟩ instance : LawfulOfNat Int n := ⟨rfl⟩ theorem isNat_rawNat (n : ℕ) : isNat n n := rfl class LawfulZero (α) [Semiring α] [Zero α] : Prop where isNat_zero : isNat (Zero.zero : α) (nat_lit 0) instance (α) [Semiring α] : LawfulZero α := ⟨rfl⟩ class LawfulOne (α) [Semiring α] [One α] : Prop where isNat_one : isNat (One.one : α) (nat_lit 1) instance (α) [Semiring α] : LawfulOne α := ⟨rfl⟩ theorem isNat_add {α} [Semiring α] : (a b : α) → (a' b' c : Nat) → isNat a a' → isNat b b' → Nat.add a' b' = c → isNat (a + b) c | _, _, _, _, _, rfl, rfl, rfl => ofNat_add.symm theorem isNat_mul {α} [Semiring α] : (a b : α) → (a' b' c : Nat) → isNat a a' → isNat b b' → Nat.mul a' b' = c → isNat (a * b) c | _, _, _, _, _, rfl, rfl, rfl => ofNat_mul.symm theorem isNat_pow {α} [Semiring α] : (a : α) → (b a' b' c : Nat) → isNat a a' → isNat b b' → Nat.pow a' b' = c → isNat (a ^ b) c | _, _, _, _, _, rfl, rfl, rfl => (ofNat_pow _ _).symm def instSemiringNat : Semiring Nat := inferInstance partial def evalIsNat (u : Level) (α sα e : Expr) : MetaM (Expr × Expr) := do let (n, p) ← match e.getAppFnArgs with | (``HAdd.hAdd, #[_, _, _, _, a, b]) => evalBinOp ``NormNum.isNat_add (·+·) a b | (``HMul.hMul, #[_, _, _, _, a, b]) => evalBinOp ``NormNum.isNat_mul (·*·) a b | (``HPow.hPow, #[_, _, _, _, a, b]) => evalPow ``NormNum.isNat_pow (·^·) a b | (``OfNat.ofNat, #[_, ln, inst]) => let some n ← ln.natLit? | throwError "fail" let lawful ← synthInstance (mkApp4 (mkConst ``LawfulOfNat [u]) α sα ln inst) (ln, mkApp5 (mkConst ``LawfulOfNat.isNat_ofNat [u]) α sα ln inst lawful) | (``Zero.zero, #[_, inst]) => let lawful ← synthInstance (mkApp3 (mkConst ``LawfulZero [u]) α sα inst) (mkNatLit 0, mkApp4 (mkConst ``LawfulZero.isNat_zero [u]) α sα inst lawful) | (``One.one, #[_, inst]) => let lawful ← synthInstance (mkApp3 (mkConst ``LawfulOne [u]) α sα inst) (mkNatLit 1, mkApp4 (mkConst ``LawfulOne.isNat_one [u]) α sα inst lawful) | _ => if e.isNatLit then (e, mkApp (mkConst ``isNat_rawNat) e) else throwError "fail" (n, mkApp2 (mkConst ``id [levelZero]) (mkApp4 (mkConst ``isNat [u]) α sα e n) p) where evalBinOp (name : Name) (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Expr × Expr) := do let (la, pa) ← evalIsNat u α sα a let (lb, pb) ← evalIsNat u α sα b let a' := la.natLit! let b' := lb.natLit! let c' := f a' b' let lc := mkRawNatLit c' (lc, mkApp10 (mkConst name [u]) α sα a b la lb lc pa pb (← mkEqRefl lc)) evalPow (name : Name) (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Expr × Expr) := do let (la, pa) ← evalIsNat u α sα a let (lb, pb) ← evalIsNat levelZero (mkConst ``Nat) (mkConst ``instSemiringNat) b let a' := la.natLit! let b' := lb.natLit! let c' := f a' b' let lc := mkRawNatLit c' (lc, mkApp10 (mkConst name [u]) α sα a b la lb lc pa pb (← mkEqRefl lc)) theorem eval_of_isNat {α} [Semiring α] (n) [OfNat α n] [LawfulOfNat α n] : (a : α) → isNat a n → a = OfNat.ofNat n | _, rfl => LawfulOfNat.isNat_ofNat.symm def eval (e : Expr) : MetaM (Expr × Expr) := do let α ← inferType e let Level.succ u _ ← getLevel α | throwError "fail" let sα ← synthInstance (mkApp (mkConst ``Semiring [u]) α) let (ln, p) ← evalIsNat u α sα e let ofNatInst ← synthInstance (mkApp2 (mkConst ``OfNat [u]) α ln) let lawfulInst ← synthInstance (mkApp4 (mkConst ``LawfulOfNat [u]) α sα ln ofNatInst) (mkApp3 (mkConst ``OfNat.ofNat [u]) α ln ofNatInst, mkApp7 (mkConst ``eval_of_isNat [u]) α sα ln ofNatInst lawfulInst e p) theorem eval_eq_of_isNat {α} [Semiring α] : (a b : α) → (n : ℕ) → isNat a n → isNat b n → a = b | _, _, _, rfl, rfl => rfl def evalEq (α a b : Expr) : MetaM Expr := do let Level.succ u _ ← getLevel α | throwError "fail" let sα ← synthInstance (mkApp (mkConst ``Semiring [u]) α) let (ln, pa) ← evalIsNat u α sα a let (ln', pb) ← evalIsNat u α sα b guard (ln.natLit! == ln'.natLit!) mkApp7 (mkConst ``eval_eq_of_isNat [u]) α sα a b ln pa pb end NormNum end Meta namespace Tactic open Lean.Parser.Tactic in syntax (name := normNum) "normNum" (" [" simpArg,* "]")? (ppSpace location)? : tactic open Meta Elab.Tactic in elab_rules : tactic | `(tactic| normNum) => do liftMetaTactic fun g => do let some (α, lhs, rhs) ← matchEq? (← getMVarType g) | throwError "fail" let p ← NormNum.evalEq α lhs rhs assignExprMVar g p pure [] end Tactic end Lean variable (α) [Semiring α] example : (1 + 0 : α) = (0 + 1 : α) := by normNum example : (0 + (2 + 3) + 1 : α) = 6 := by normNum example : (70 * (33 + 2) : α) = 2450 := by normNum example : (8 + 2 ^ 2 * 3 : α) = 20 := by normNum example : ((2 * 1 + 1) ^ 2 : α) = (3 * 3 : α) := by normNum
8b2109023f0872e19bda100f282be90decc7abb3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/mk_dec_eq_instance_auto.lean
1923bc78d53d9238a84f3fe561b8d00b22975212
[]
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
684
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 Helper tactic for showing that a type has decidable equality. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.contradiction_tactic import Mathlib.Lean3Lib.init.meta.constructor_tactic import Mathlib.Lean3Lib.init.meta.injection_tactic import Mathlib.Lean3Lib.init.meta.relation_tactics import Mathlib.Lean3Lib.init.meta.rec_util import Mathlib.Lean3Lib.init.meta.interactive namespace Mathlib namespace tactic /- Retrieve the name of the type we are building a decidable equality proof for. -/ end Mathlib
e3f9a099ae24f3b8cd64480eb064c809e65c3fcd
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_lean_summary/unnamed_269.lean
c40e69afc069514888f92c4d61a7a8f2fe8a5ab8
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
197
lean
variables p q : Prop -- BEGIN example (k : q) : p → q := begin intro h, -- This is equivalent to 'Assume h : p' in mathematics. exact k, -- We close the goal using our proof of q. end -- END
eeb43e7e6d361c24886c042a914c754f517b314f
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/function/ae_measurable_order.lean
11bec09202c340716e673b581107bf9fbd435949
[ "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
6,235
lean
/- Copyright (c) 2021 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 measure_theory.constructions.borel_space /-! # Measurability criterion for ennreal-valued functions Consider a function `f : α → ℝ≥0∞`. If the level sets `{f < p}` and `{q < f}` have measurable supersets which are disjoint up to measure zero when `p` and `q` are finite numbers satisfying `p < q`, then `f` is almost-everywhere measurable. This is proved in `ennreal.ae_measurable_of_exist_almost_disjoint_supersets`, and deduced from an analogous statement for any target space which is a complete linear dense order, called `measure_theory.ae_measurable_of_exist_almost_disjoint_supersets`. Note that it should be enough to assume that the space is a conditionally complete linear order, but the proof would be more painful. Since our only use for now is for `ℝ≥0∞`, we keep it as simple as possible. -/ open measure_theory set topological_space open_locale classical ennreal nnreal /-- If a function `f : α → β` is such that the level sets `{f < p}` and `{q < f}` have measurable supersets which are disjoint up to measure zero when `p < q`, then `f` is almost-everywhere measurable. It is even enough to have this for `p` and `q` in a countable dense set. -/ theorem measure_theory.ae_measurable_of_exist_almost_disjoint_supersets {α : Type*} {m : measurable_space α} (μ : measure α) {β : Type*} [complete_linear_order β] [densely_ordered β] [topological_space β] [order_topology β] [second_countable_topology β] [measurable_space β] [borel_space β] (s : set β) (s_count : s.countable) (s_dense : dense s) (f : α → β) (h : ∀ (p ∈ s) (q ∈ s), p < q → ∃ u v, measurable_set u ∧ measurable_set v ∧ {x | f x < p} ⊆ u ∧ {x | q < f x} ⊆ v ∧ μ (u ∩ v) = 0) : ae_measurable f μ := begin haveI : encodable s := s_count.to_encodable, have h' : ∀ p q, ∃ u v, measurable_set u ∧ measurable_set v ∧ {x | f x < p} ⊆ u ∧ {x | q < f x} ⊆ v ∧ (p ∈ s → q ∈ s → p < q → μ (u ∩ v) = 0), { assume p q, by_cases H : p ∈ s ∧ q ∈ s ∧ p < q, { rcases h p H.1 q H.2.1 H.2.2 with ⟨u, v, hu, hv, h'u, h'v, hμ⟩, exact ⟨u, v, hu, hv, h'u, h'v, λ ps qs pq, hμ⟩ }, { refine ⟨univ, univ, measurable_set.univ, measurable_set.univ, subset_univ _, subset_univ _, λ ps qs pq, _⟩, simp only [not_and] at H, exact (H ps qs pq).elim } }, choose! u v huv using h', let u' : β → set α := λ p, ⋂ (q ∈ s ∩ Ioi p), u p q, have u'_meas : ∀ i, measurable_set (u' i), { assume i, exact measurable_set.bInter (s_count.mono (inter_subset_left _ _)) (λ b hb, (huv i b).1) }, let f' : α → β := λ x, ⨅ (i : s), piecewise (u' i) (λ x, (i : β)) (λ x, (⊤ : β)) x, have f'_meas : measurable f', { apply measurable_infi, exact λ i, measurable.piecewise (u'_meas i) measurable_const measurable_const }, let t := ⋃ (p : s) (q : s ∩ Ioi p), u' p ∩ v p q, have μt : μ t ≤ 0 := calc μ t ≤ ∑' (p : s) (q : s ∩ Ioi p), μ (u' p ∩ v p q) : begin refine (measure_Union_le _).trans _, apply ennreal.tsum_le_tsum (λ p, _), apply measure_Union_le _, exact (s_count.mono (inter_subset_left _ _)).to_encodable, end ... ≤ ∑' (p : s) (q : s ∩ Ioi p), μ (u p q ∩ v p q) : begin apply ennreal.tsum_le_tsum (λ p, _), refine ennreal.tsum_le_tsum (λ q, measure_mono _), exact inter_subset_inter_left _ (bInter_subset_of_mem q.2) end ... = ∑' (p : s) (q : s ∩ Ioi p), (0 : ℝ≥0∞) : by { congr, ext1 p, congr, ext1 q, exact (huv p q).2.2.2.2 p.2 q.2.1 q.2.2 } ... = 0 : by simp only [tsum_zero], have ff' : ∀ᵐ x ∂μ, f x = f' x, { have : ∀ᵐ x ∂μ, x ∉ t, { have : μ t = 0 := le_antisymm μt bot_le, change μ _ = 0, convert this, ext y, simp only [not_exists, exists_prop, mem_set_of_eq, mem_compl_eq, not_not_mem] }, filter_upwards [this] with x hx, apply (infi_eq_of_forall_ge_of_forall_gt_exists_lt _ _).symm, { assume i, by_cases H : x ∈ u' i, swap, { simp only [H, le_top, not_false_iff, piecewise_eq_of_not_mem] }, simp only [H, piecewise_eq_of_mem], contrapose! hx, obtain ⟨r, ⟨xr, rq⟩, rs⟩ : ∃ r, r ∈ Ioo (i : β) (f x) ∩ s := dense_iff_inter_open.1 s_dense (Ioo i (f x)) is_open_Ioo (nonempty_Ioo.2 hx), have A : x ∈ v i r := (huv i r).2.2.2.1 rq, apply mem_Union.2 ⟨i, _⟩, refine mem_Union.2 ⟨⟨r, ⟨rs, xr⟩⟩, _⟩, exact ⟨H, A⟩ }, { assume q hq, obtain ⟨r, ⟨xr, rq⟩, rs⟩ : ∃ r, r ∈ Ioo (f x) q ∩ s := dense_iff_inter_open.1 s_dense (Ioo (f x) q) is_open_Ioo (nonempty_Ioo.2 hq), refine ⟨⟨r, rs⟩, _⟩, have A : x ∈ u' r := mem_bInter (λ i hi, (huv r i).2.2.1 xr), simp only [A, rq, piecewise_eq_of_mem, subtype.coe_mk] } }, exact ⟨f', f'_meas, ff'⟩, end /-- If a function `f : α → ℝ≥0∞` is such that the level sets `{f < p}` and `{q < f}` have measurable supersets which are disjoint up to measure zero when `p` and `q` are finite numbers satisfying `p < q`, then `f` is almost-everywhere measurable. -/ theorem ennreal.ae_measurable_of_exist_almost_disjoint_supersets {α : Type*} {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) (h : ∀ (p : ℝ≥0) (q : ℝ≥0), p < q → ∃ u v, measurable_set u ∧ measurable_set v ∧ {x | f x < p} ⊆ u ∧ {x | (q : ℝ≥0∞) < f x} ⊆ v ∧ μ (u ∩ v) = 0) : ae_measurable f μ := begin obtain ⟨s, s_count, s_dense, s_zero, s_top⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧ 0 ∉ s ∧ ∞ ∉ s := ennreal.exists_countable_dense_no_zero_top, have I : ∀ x ∈ s, x ≠ ∞ := λ x xs hx, s_top (hx ▸ xs), apply measure_theory.ae_measurable_of_exist_almost_disjoint_supersets μ s s_count s_dense _, rintros p hp q hq hpq, lift p to ℝ≥0 using I p hp, lift q to ℝ≥0 using I q hq, exact h p q (ennreal.coe_lt_coe.1 hpq), end
b67d5f19a0bac4d6c15905e69219637707cd4a0b
367134ba5a65885e863bdc4507601606690974c1
/src/order/complete_boolean_algebra.lean
bc430d040f0bd13648b1b2aff3c8e3aae2bb70be
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
4,673
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 Theory of complete Boolean algebras. -/ import order.complete_lattice set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} /-- A complete distributive lattice is a bit stronger than the name might suggest; perhaps completely distributive lattice is more descriptive, as this class includes a requirement that the lattice join distribute over *arbitrary* infima, and similarly for the dual. -/ class complete_distrib_lattice α extends complete_lattice α := (infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s) (inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b)) section complete_distrib_lattice variables [complete_distrib_lattice α] {a b : α} {s t : set α} instance : complete_distrib_lattice (order_dual α) := { infi_sup_le_sup_Inf := complete_distrib_lattice.inf_Sup_le_supr_inf, inf_Sup_le_supr_inf := complete_distrib_lattice.infi_sup_le_sup_Inf, .. order_dual.complete_lattice α } theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) := sup_Inf_le_infi_sup.antisymm (complete_distrib_lattice.infi_sup_le_sup_Inf _ _) theorem Inf_sup_eq : Inf s ⊔ b = (⨅ a ∈ s, a ⊔ b) := by simpa only [sup_comm] using @sup_Inf_eq α _ b s theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) := (complete_distrib_lattice.inf_Sup_le_supr_inf _ _).antisymm supr_inf_le_inf_Sup theorem Sup_inf_eq : Sup s ⊓ b = (⨆ a ∈ s, a ⊓ b) := by simpa only [inf_comm] using @inf_Sup_eq α _ b s theorem supr_inf_eq (f : ι → α) (a : α) : (⨆ i, f i) ⊓ a = ⨆ i, f i ⊓ a := by rw [supr, Sup_inf_eq, supr_range] theorem inf_supr_eq (a : α) (f : ι → α) : a ⊓ (⨆ i, f i) = ⨆ i, a ⊓ f i := by simpa only [inf_comm] using supr_inf_eq f a theorem infi_sup_eq (f : ι → α) (a : α) : (⨅ i, f i) ⊔ a = ⨅ i, f i ⊔ a := @supr_inf_eq (order_dual α) _ _ _ _ theorem sup_infi_eq (a : α) (f : ι → α) : a ⊔ (⨅ i, f i) = ⨅ i, a ⊔ f i := @inf_supr_eq (order_dual α) _ _ _ _ theorem Inf_sup_Inf : Inf s ⊔ Inf t = (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) := begin apply le_antisymm, { finish }, { have : ∀ a ∈ s, (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ a ⊔ Inf t, { assume a ha, have : (⨅p ∈ set.prod s t, ((p : α × α).1 : α) ⊔ p.2) ≤ (⨅p ∈ prod.mk a '' t, (p : α × α).1 ⊔ p.2), { apply infi_le_infi_of_subset, rintros ⟨x, y⟩, simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, exists_imp_distrib], assume x' x't ax x'y, rw [← x'y, ← ax], simp [ha, x't] }, rw [infi_image] at this, simp only at this, rwa ← sup_Inf_eq at this }, calc (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ (⨅a∈s, a ⊔ Inf t) : by simp; exact this ... = Inf s ⊔ Inf t : Inf_sup_eq.symm } end theorem Sup_inf_Sup : Sup s ⊓ Sup t = (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) := @Inf_sup_Inf (order_dual α) _ _ _ lemma supr_disjoint_iff {f : ι → α} : disjoint (⨆ i, f i) a ↔ ∀ i, disjoint (f i) a := by simp only [disjoint_iff, supr_inf_eq, supr_eq_bot] lemma disjoint_supr_iff {f : ι → α} : disjoint a (⨆ i, f i) ↔ ∀ i, disjoint a (f i) := by simpa only [disjoint.comm] using @supr_disjoint_iff _ _ _ a f end complete_distrib_lattice @[priority 100] -- see Note [lower instance priority] instance complete_distrib_lattice.bounded_distrib_lattice [d : complete_distrib_lattice α] : bounded_distrib_lattice α := { le_sup_inf := λ x y z, by rw [← Inf_pair, ← Inf_pair, sup_Inf_eq, ← Inf_image, set.image_pair], ..d } /-- A complete boolean algebra is a completely distributive boolean algebra. -/ class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α section complete_boolean_algebra variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α} theorem compl_infi : (infi f)ᶜ = (⨆i, (f i)ᶜ) := le_antisymm (compl_le_of_compl_le $ le_infi $ assume i, compl_le_of_compl_le $ le_supr (compl ∘ f) i) (supr_le $ assume i, compl_le_compl $ infi_le _ _) theorem compl_supr : (supr f)ᶜ = (⨅i, (f i)ᶜ) := compl_injective (by simp [compl_infi]) theorem compl_Inf : (Inf s)ᶜ = (⨆i∈s, iᶜ) := by simp only [Inf_eq_infi, compl_infi] theorem compl_Sup : (Sup s)ᶜ = (⨅i∈s, iᶜ) := by simp only [Sup_eq_supr, compl_supr] end complete_boolean_algebra
ec4d4e98ed75425e19748fe5904090e8c4644a64
6de8ea38e7f58ace8fbf74ba3ad0bf3b3d1d7ab5
/lab5/code/intro.lean
f80c957c2d0827172296faa9a749ef38bda9b437
[]
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
836
lean
#check "hello world!" /- C-c C-k shows how to type the symbol! C-c C-x executes the entire script C-c ! l shows the interactive panel below -/ theorem t1 (p q : Prop) : p ∧ q → p ∧ q ∧ p := begin intros, apply and.intro, apply and.left a, apply and.intro, apply and.right a, apply and.left a, end theorem t2 (p q : Prop) (hp1: p) (hp2: q) : p ∧ q ∧ p := begin apply and.intro, assumption, apply and.intro, assumption, assumption, end theorem t3 (p q: Prop) : p ∧ q → p ∧ q ∧ p := assume hpq: p ∧ q, have h1: p, from and.left hpq, have h2: q, from and.right hpq, show p ∧ q ∧ p, from and.intro h1 (and.intro h2 h1) theorem t4 (p q: Prop) (h: p ∧ q) : p ∧ q ∧ p := begin have h1: p, from and.left h, have h2: q, from and.right h, apply and.intro h1 (and.intro h2 h1), end
44f1de293e579706106ee0e11d6cbef03847d592
618003631150032a5676f229d13a079ac875ff77
/src/algebra/category/Module/monoidal.lean
319c47a83d6044cf4429c1f8d2bbb1236d2c5bdd
[ "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,571
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Scott Morrison -/ import category_theory.monoidal.category import algebra.category.Module.basic import linear_algebra.tensor_product /-! # The monoidal category structure on R-modules Mostly this uses existing machinery in `linear_algebra.tensor_product`. We just need to provide a few small missing pieces to build the `monoidal_category` instance. If you're happy using the bundled `Module R`, it may be possible to mostly use this as an interface and not need to interact much with the implementation details. -/ universe u open category_theory namespace Module variables {R : Type u} [comm_ring R] namespace monoidal_category -- The definitions inside this namespace are essentially private. -- After we build the `monoidal_category (Module R)` instance, -- you should use that API. open_locale tensor_product /-- (implementation) tensor product of R-modules -/ def tensor_obj (M N : Module R) : Module R := Module.of R (M ⊗[R] N) /-- (implementation) tensor product of morphisms R-modules -/ def tensor_hom {M N M' N' : Module R} (f : M ⟶ N) (g : M' ⟶ N') : tensor_obj M M' ⟶ tensor_obj N N' := tensor_product.map f g lemma tensor_id (M N : Module R) : tensor_hom (𝟙 M) (𝟙 N) = 𝟙 (Module.of R (↥M ⊗ ↥N)) := by tidy lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom f₁ f₂ ≫ tensor_hom g₁ g₂ := by tidy /-- (implementation) the associator for R-modules -/ def associator (M N K : Module R) : tensor_obj (tensor_obj M N) K ≅ tensor_obj M (tensor_obj N K) := linear_equiv.to_Module_iso (tensor_product.assoc R M N K) lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom (tensor_hom f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ tensor_hom f₁ (tensor_hom f₂ f₃) := begin apply tensor_product.ext_threefold, intros x y z, refl end lemma pentagon (W X Y Z : Module R) : tensor_hom (associator W X Y).hom (𝟙 Z) ≫ (associator W (tensor_obj X Y) Z).hom ≫ tensor_hom (𝟙 W) (associator X Y Z).hom = (associator (tensor_obj W X) Y Z).hom ≫ (associator W X (tensor_obj Y Z)).hom := begin apply tensor_product.ext_fourfold, intros w x y z, refl end /-- (implementation) the left unitor for R-modules -/ def left_unitor (M : Module R) : Module.of R (R ⊗[R] M) ≅ M := (linear_equiv.to_Module_iso (tensor_product.lid R M) : of R (R ⊗ M) ≅ of R M).trans (of_self_iso M) lemma left_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom (𝟙 (Module.of R R)) f ≫ (left_unitor N).hom = (left_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.lid_tmul, tensor_product.lid_tmul], rw linear_map.map_smul, refl, end /-- (implementation) the right unitor for R-modules -/ def right_unitor (M : Module R) : Module.of R (M ⊗[R] R) ≅ M := (linear_equiv.to_Module_iso (tensor_product.rid R M) : of R (M ⊗ R) ≅ of R M).trans (of_self_iso M) lemma right_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom f (𝟙 (Module.of R R)) ≫ (right_unitor N).hom = (right_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.rid_tmul, tensor_product.rid_tmul], rw linear_map.map_smul, refl, end lemma triangle (M N : Module R) : (associator M (Module.of R R) N).hom ≫ tensor_hom (𝟙 M) (left_unitor N).hom = tensor_hom (right_unitor M).hom (𝟙 N) := begin apply tensor_product.ext_threefold, intros x y z, change R at y, dsimp [tensor_hom, associator], erw [tensor_product.lid_tmul, tensor_product.rid_tmul], apply (tensor_product.smul_tmul _ _ _).symm end end monoidal_category open monoidal_category instance Module.monoidal_category : monoidal_category (Module.{u} R) := { -- data tensor_obj := tensor_obj, tensor_hom := @tensor_hom _ _, tensor_unit := Module.of R R, associator := associator, left_unitor := left_unitor, right_unitor := right_unitor, -- properties tensor_id' := λ M N, tensor_id M N, tensor_comp' := λ M N K M' N' K' f g h, tensor_comp f g h, associator_naturality' := λ M N K M' N' K' f g h, associator_naturality f g h, left_unitor_naturality' := λ M N f, left_unitor_naturality f, right_unitor_naturality' := λ M N f, right_unitor_naturality f, pentagon' := λ M N K L, pentagon M N K L, triangle' := λ M N, triangle M N, } /-- Remind ourselves that the monoidal unit, being just `R`, is still a commutative ring. -/ instance : comm_ring ((𝟙_ (Module R) : Module R) : Type u) := (by apply_instance : comm_ring R) namespace monoidal_category @[simp] lemma left_unitor_hom {M : Module.{u} R} (r : R) (m : M) : ((λ_ M).hom : 𝟙_ (Module R) ⊗ M ⟶ M) (r ⊗ₜ[R] m) = r • m := tensor_product.lid_tmul m r @[simp] lemma right_unitor_hom {M : Module R} (m : M) (r : R) : ((ρ_ M).hom : M ⊗ 𝟙_ (Module R) ⟶ M) (m ⊗ₜ r) = r • m := tensor_product.rid_tmul m r @[simp] lemma associator_hom {M N K : Module R} (m : M) (n : N) (k : K) : ((α_ M N K).hom : (M ⊗ N) ⊗ K ⟶ M ⊗ (N ⊗ K)) ((m ⊗ₜ n) ⊗ₜ k) = (m ⊗ₜ (n ⊗ₜ k)) := rfl end monoidal_category end Module
f35a5099721e99b58f31bc0e9eb384f483141795
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/periodic.lean
501e32e15a15946681c78bd0ed7176b948c5b478
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
2,169
lean
/- Copyright (c) 2021 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import algebra.periodic import data.nat.count import data.nat.interval /-! # Periodic Functions on ℕ This file identifies a few functions on `ℕ` which are periodic, and also proves a lemma about periodic predicates which helps determine their cardinality when filtering intervals over them. -/ namespace nat open nat function lemma periodic_gcd (a : ℕ) : periodic (gcd a) a := by simp only [forall_const, gcd_add_self_right, eq_self_iff_true, periodic] lemma periodic_coprime (a : ℕ) : periodic (coprime a) a := by simp only [coprime_add_self_right, forall_const, iff_self, eq_iff_iff, periodic] lemma periodic_mod (a : ℕ) : periodic (λ n, n % a) a := by simp only [forall_const, eq_self_iff_true, add_mod_right, periodic] lemma _root_.function.periodic.map_mod_nat {α : Type*} {f : ℕ → α} {a : ℕ} (hf : periodic f a) : ∀ n, f (n % a) = f n := λ n, by conv_rhs { rw [← nat.mod_add_div n a, mul_comm, ← nat.nsmul_eq_mul, hf.nsmul] } section multiset open multiset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ lemma filter_multiset_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [decidable_pred p] (pp : periodic p a) : (filter p (Ico n (n+a))).card = a.count p := begin rw [count_eq_card_filter_range, finset.card, finset.filter_val, finset.range_val, ←multiset_Ico_map_mod n, ←map_count_true_eq_filter_card, ←map_count_true_eq_filter_card, map_map, function.comp], simp only [pp.map_mod_nat], end end multiset section finset open finset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ lemma filter_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [decidable_pred p] (pp : periodic p a) : ((Ico n (n + a)).filter p).card = a.count p := filter_multiset_Ico_card_eq_of_periodic n a p pp end finset end nat
104645520da11df3aa50b970e9a01c56eb91919d
315b4184091c669ce8e5e07f9b24473c4bcfbaaf
/library/system/io_interface.lean
f0b8055302ef8771df1663b17816b38ab2a20a61
[ "Apache-2.0" ]
permissive
haraldschilly/lean
78404910ad4c258cdf84e0509e4348c1525e57a9
d01e2d7ae8250e8f69139d8cb37950079e76ca9d
refs/heads/master
1,619,977,395,095
1,517,501,044,000
1,517,940,670,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,163
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.buffer inductive io.error | other : string → io.error | sys : nat → io.error inductive io.mode | read | write | read_write | append inductive io.process.stdio | piped | inherit | null structure io.process.spawn_args := /- Command name. -/ (cmd : string) /- Arguments for the process -/ (args : list string := []) /- Configuration for the process' stdin handle. -/ (stdin := stdio.inherit) /- Configuration for the process' stdout handle. -/ (stdout := stdio.inherit) /- Configuration for the process' stderr handle. -/ (stderr := stdio.inherit) /- Working directory for the process. -/ (cwd : option string := none) /- Environment variables for the process. -/ (env : list (string × option string) := []) class monad_io (m : Type → Type → Type) := [monad : Π e, monad (m e)] -- TODO(Leo): use monad_except after it is merged (catch : Π e₁ e₂ α, m e₁ α → (e₁ → m e₂ α) → m e₂ α) (fail : Π e α, e → m e α) (iterate : Π e α, α → (α → m e (option α)) → m e α) -- Primitive Types (handle : Type) class monad_io_terminal (m : Type → Type → Type) := (put_str : string → m io.error unit) (get_line : m io.error string) (cmdline_args : list string) open monad_io (handle) class monad_io_file_system (m : Type → Type → Type) [monad_io m] := /- Remark: in Haskell, they also provide (Maybe TextEncoding) and NewlineMode -/ (mk_file_handle : string → io.mode → bool → m io.error (handle m)) (is_eof : (handle m) → m io.error bool) (flush : (handle m) → m io.error unit) (close : (handle m) → m io.error unit) (read : (handle m) → nat → m io.error char_buffer) (write : (handle m) → char_buffer → m io.error unit) (get_line : (handle m) → m io.error char_buffer) (stdin : m io.error (handle m)) (stdout : m io.error (handle m)) (stderr : m io.error (handle m)) class monad_io_environment (m : Type → Type → Type) := (get_env : string → m io.error (option string)) -- we don't provide set_env as it is (thread-)unsafe (at least with glibc) (get_cwd : m io.error string) (set_cwd : string → m io.error unit) class monad_io_process (m : Type → Type → Type) [monad_io m] := (child : Type) (stdin : child → (handle m)) (stdout : child → (handle m)) (stderr : child → (handle m)) (spawn : io.process.spawn_args → m io.error child) (wait : child → m io.error nat) instance monad_io_is_monad (m : Type → Type → Type) (e : Type) [monad_io m] : monad (m e) := monad_io.monad m e instance monad_io_is_monad_fail (m : Type → Type → Type) [monad_io m] : monad_fail (m io.error) := { fail := λ α s, monad_io.fail _ _ _ (io.error.other s) } instance monad_io_is_alternative (m : Type → Type → Type) [monad_io m] : alternative (m io.error) := { orelse := λ α a b, monad_io.catch _ _ _ a (λ _, b), failure := λ α, monad_io.fail _ _ _ (io.error.other "failure") }
80022627a6b0e742f0739ee2329d4d136630b381
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1780.lean
d3345288469d4315971d42d06c885632861857db
[ "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
101
lean
import Lean section open Lean open Meta -- ok end section open Lean hiding Rat open Meta -- ok end
df1b27f043897a7dd7ee5285c4d088f89b9ca237
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/def_brec1.lean
470e1550c998feb3f90ce1c2f273fb76b705adc8
[ "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
410
lean
inductive foo : bool → Type | Z : foo ff | O : foo ff → foo tt | E : foo tt → foo ff open foo definition to_nat : ∀ {b}, foo b → nat | .ff Z := 0 | .tt (O n) := to_nat n + 1 | .ff (E n) := to_nat n + 1 example : to_nat (E (O Z)) = 2 := rfl example : to_nat Z = 0 := rfl example (a : foo ff) : to_nat (O a) = to_nat a + 1 := rfl example (a : foo tt) : to_nat (E a) = to_nat a + 1 := rfl
8ce83be82cc4505ad289a15522a1c3fa9b08c627
4727251e0cd73359b15b664c3170e5d754078599
/src/data/pfunctor/univariate/M.lean
cdcedad8b350e89e26938531521c67c6d08e9c7c
[ "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
21,958
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfunctor.univariate.basic /-! # M-types M types are potentially infinite tree-like structures. They are defined as the greatest fixpoint of a polynomial functor. -/ universes u v w open nat function list (hiding head') variables (F : pfunctor.{u}) local prefix `♯`:0 := cast (by simp [*] <|> cc <|> solve_by_elim) namespace pfunctor namespace approx /-- `cofix_a F n` is an `n` level approximation of a M-type -/ inductive cofix_a : ℕ → Type u | continue : cofix_a 0 | intro {n} : ∀ a, (F.B a → cofix_a n) → cofix_a (succ n) /-- default inhabitant of `cofix_a` -/ protected def cofix_a.default [inhabited F.A] : Π n, cofix_a F n | 0 := cofix_a.continue | (succ n) := cofix_a.intro default $ λ _, cofix_a.default n instance [inhabited F.A] {n} : inhabited (cofix_a F n) := ⟨ cofix_a.default F n ⟩ lemma cofix_a_eq_zero : ∀ x y : cofix_a F 0, x = y | cofix_a.continue cofix_a.continue := rfl variables {F} /-- The label of the root of the tree for a non-trivial approximation of the cofix of a pfunctor. -/ def head' : Π {n}, cofix_a F (succ n) → F.A | n (cofix_a.intro i _) := i /-- for a non-trivial approximation, return all the subtrees of the root -/ def children' : Π {n} (x : cofix_a F (succ n)), F.B (head' x) → cofix_a F n | n (cofix_a.intro a f) := f lemma approx_eta {n : ℕ} (x : cofix_a F (n+1)) : x = cofix_a.intro (head' x) (children' x) := by cases x; refl /-- Relation between two approximations of the cofix of a pfunctor that state they both contain the same data until one of them is truncated -/ inductive agree : ∀ {n : ℕ}, cofix_a F n → cofix_a F (n+1) → Prop | continue (x : cofix_a F 0) (y : cofix_a F 1) : agree x y | intro {n} {a} (x : F.B a → cofix_a F n) (x' : F.B a → cofix_a F (n+1)) : (∀ i : F.B a, agree (x i) (x' i)) → agree (cofix_a.intro a x) (cofix_a.intro a x') /-- Given an infinite series of approximations `approx`, `all_agree approx` states that they are all consistent with each other. -/ def all_agree (x : Π n, cofix_a F n) := ∀ n, agree (x n) (x (succ n)) @[simp] lemma agree_trival {x : cofix_a F 0} {y : cofix_a F 1} : agree x y := by { constructor } lemma agree_children {n : ℕ} (x : cofix_a F (succ n)) (y : cofix_a F (succ n+1)) {i j} (h₀ : i == j) (h₁ : agree x y) : agree (children' x i) (children' y j) := begin cases h₁ with _ _ _ _ _ _ hagree, cases h₀, apply hagree, end /-- `truncate a` turns `a` into a more limited approximation -/ def truncate : ∀ {n : ℕ}, cofix_a F (n+1) → cofix_a F n | 0 (cofix_a.intro _ _) := cofix_a.continue | (succ n) (cofix_a.intro i f) := cofix_a.intro i $ truncate ∘ f lemma truncate_eq_of_agree {n : ℕ} (x : cofix_a F n) (y : cofix_a F (succ n)) (h : agree x y) : truncate y = x := begin induction n generalizing x y; cases x; cases y, { refl }, { cases h with _ _ _ _ _ h₀ h₁, cases h, simp only [truncate, function.comp, true_and, eq_self_iff_true, heq_iff_eq], ext y, apply n_ih, apply h₁ } end variables {X : Type w} variables (f : X → F.obj X) /-- `s_corec f i n` creates an approximation of height `n` of the final coalgebra of `f` -/ def s_corec : Π (i : X) n, cofix_a F n | _ 0 := cofix_a.continue | j (succ n) := cofix_a.intro (f j).1 (λ i, s_corec ((f j).2 i) _) lemma P_corec (i : X) (n : ℕ) : agree (s_corec f i n) (s_corec f i (succ n)) := begin induction n with n generalizing i, constructor, cases h : f i with y g, constructor, introv, apply n_ih, end /-- `path F` provides indices to access internal nodes in `corec F` -/ def path (F : pfunctor.{u}) := list F.Idx instance path.inhabited : inhabited (path F) := ⟨ [] ⟩ open list nat instance : subsingleton (cofix_a F 0) := ⟨ by { intros, casesm* cofix_a F 0, refl } ⟩ lemma head_succ' (n m : ℕ) (x : Π n, cofix_a F n) (Hconsistent : all_agree x) : head' (x (succ n)) = head' (x (succ m)) := begin suffices : ∀ n, head' (x (succ n)) = head' (x 1), { simp [this] }, clear m n, intro, cases h₀ : x (succ n) with _ i₀ f₀, cases h₁ : x 1 with _ i₁ f₁, dsimp only [head'], induction n with n, { rw h₁ at h₀, cases h₀, trivial }, { have H := Hconsistent (succ n), cases h₂ : x (succ n) with _ i₂ f₂, rw [h₀,h₂] at H, apply n_ih (truncate ∘ f₀), rw h₂, cases H with _ _ _ _ _ _ hagree, congr, funext j, dsimp only [comp_app], rw truncate_eq_of_agree, apply hagree } end end approx open approx /-- Internal definition for `M`. It is needed to avoid name clashes between `M.mk` and `M.cases_on` and the declarations generated for the structure -/ structure M_intl := (approx : ∀ n, cofix_a F n) (consistent : all_agree approx) /-- For polynomial functor `F`, `M F` is its final coalgebra -/ def M := M_intl F lemma M.default_consistent [inhabited F.A] : Π n, agree (default : cofix_a F n) default | 0 := agree.continue _ _ | (succ n) := agree.intro _ _ $ λ _, M.default_consistent n instance M.inhabited [inhabited F.A] : inhabited (M F) := ⟨ { approx := λ n, default, consistent := M.default_consistent _ } ⟩ instance M_intl.inhabited [inhabited F.A] : inhabited (M_intl F) := show inhabited (M F), by apply_instance namespace M lemma ext' (x y : M F) (H : ∀ i : ℕ, x.approx i = y.approx i) : x = y := by { cases x, cases y, congr' with n, apply H } variables {X : Type*} variables (f : X → F.obj X) variables {F} /-- Corecursor for the M-type defined by `F`. -/ protected def corec (i : X) : M F := { approx := s_corec f i, consistent := P_corec _ _ } variables {F} /-- given a tree generated by `F`, `head` gives us the first piece of data it contains -/ def head (x : M F) := head' (x.1 1) /-- return all the subtrees of the root of a tree `x : M F` -/ def children (x : M F) (i : F.B (head x)) : M F := let H := λ n : ℕ, @head_succ' _ n 0 x.1 x.2 in { approx := λ n, children' (x.1 _) (cast (congr_arg _ $ by simp only [head,H]; refl) i), consistent := begin intro, have P' := x.2 (succ n), apply agree_children _ _ _ P', transitivity i, apply cast_heq, symmetry, apply cast_heq, end } /-- select a subtree using a `i : F.Idx` or return an arbitrary tree if `i` designates no subtree of `x` -/ def ichildren [inhabited (M F)] [decidable_eq F.A] (i : F.Idx) (x : M F) : M F := if H' : i.1 = head x then children x (cast (congr_arg _ $ by simp only [head,H']; refl) i.2) else default lemma head_succ (n m : ℕ) (x : M F) : head' (x.approx (succ n)) = head' (x.approx (succ m)) := head_succ' n m _ x.consistent lemma head_eq_head' : Π (x : M F) (n : ℕ), head x = head' (x.approx $ n+1) | ⟨x,h⟩ n := head_succ' _ _ _ h lemma head'_eq_head : Π (x : M F) (n : ℕ), head' (x.approx $ n+1) = head x | ⟨x,h⟩ n := head_succ' _ _ _ h lemma truncate_approx (x : M F) (n : ℕ) : truncate (x.approx $ n+1) = x.approx n := truncate_eq_of_agree _ _ (x.consistent _) /-- unfold an M-type -/ def dest : M F → F.obj (M F) | x := ⟨head x,λ i, children x i ⟩ namespace approx /-- generates the approximations needed for `M.mk` -/ protected def s_mk (x : F.obj $ M F) : Π n, cofix_a F n | 0 := cofix_a.continue | (succ n) := cofix_a.intro x.1 (λ i, (x.2 i).approx n) protected lemma P_mk (x : F.obj $ M F) : all_agree (approx.s_mk x) | 0 := by { constructor } | (succ n) := by { constructor, introv, apply (x.2 i).consistent } end approx /-- constructor for M-types -/ protected def mk (x : F.obj $ M F) : M F := { approx := approx.s_mk x, consistent := approx.P_mk x } /-- `agree' n` relates two trees of type `M F` that are the same up to dept `n` -/ inductive agree' : ℕ → M F → M F → Prop | trivial (x y : M F) : agree' 0 x y | step {n : ℕ} {a} (x y : F.B a → M F) {x' y'} : x' = M.mk ⟨a,x⟩ → y' = M.mk ⟨a,y⟩ → (∀ i, agree' n (x i) (y i)) → agree' (succ n) x' y' @[simp] lemma dest_mk (x : F.obj $ M F) : dest (M.mk x) = x := begin funext i, dsimp only [M.mk,dest], cases x with x ch, congr' with i, cases h : ch i, simp only [children,M.approx.s_mk,children',cast_eq], dsimp only [M.approx.s_mk,children'], congr, rw h, end @[simp] lemma mk_dest (x : M F) : M.mk (dest x) = x := begin apply ext', intro n, dsimp only [M.mk], induction n with n, { apply subsingleton.elim }, dsimp only [approx.s_mk,dest,head], cases h : x.approx (succ n) with _ hd ch, have h' : hd = head' (x.approx 1), { rw [← head_succ' n,h,head'], apply x.consistent }, revert ch, rw h', intros, congr, { ext a, dsimp only [children], h_generalize! hh : a == a'', rw h, intros, cases hh, refl }, end lemma mk_inj {x y : F.obj $ M F} (h : M.mk x = M.mk y) : x = y := by rw [← dest_mk x,h,dest_mk] /-- destructor for M-types -/ protected def cases {r : M F → Sort w} (f : ∀ (x : F.obj $ M F), r (M.mk x)) (x : M F) : r x := suffices r (M.mk (dest x)), by { haveI := classical.prop_decidable, haveI := inhabited.mk x, rw [← mk_dest x], exact this }, f _ /-- destructor for M-types -/ protected def cases_on {r : M F → Sort w} (x : M F) (f : ∀ (x : F.obj $ M F), r (M.mk x)) : r x := M.cases f x /-- destructor for M-types, similar to `cases_on` but also gives access directly to the root and subtrees on an M-type -/ protected def cases_on' {r : M F → Sort w} (x : M F) (f : ∀ a f, r (M.mk ⟨a,f⟩)) : r x := M.cases_on x (λ ⟨a,g⟩, f a _) lemma approx_mk (a : F.A) (f : F.B a → M F) (i : ℕ) : (M.mk ⟨a, f⟩).approx (succ i) = cofix_a.intro a (λ j, (f j).approx i) := rfl @[simp] lemma agree'_refl {n : ℕ} (x : M F) : agree' n x x := by { induction n generalizing x; induction x using pfunctor.M.cases_on'; constructor; try { refl }, intros, apply n_ih } lemma agree_iff_agree' {n : ℕ} (x y : M F) : agree (x.approx n) (y.approx $ n+1) ↔ agree' n x y := begin split; intros h, { induction n generalizing x y, constructor, { induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on', simp only [approx_mk] at h, cases h with _ _ _ _ _ _ hagree, constructor; try { refl }, intro i, apply n_ih, apply hagree } }, { induction n generalizing x y, constructor, { cases h, induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on', simp only [approx_mk], have h_a_1 := mk_inj ‹M.mk ⟨x_a, x_f⟩ = M.mk ⟨h_a, h_x⟩›, cases h_a_1, replace h_a_2 := mk_inj ‹M.mk ⟨y_a, y_f⟩ = M.mk ⟨h_a, h_y⟩›, cases h_a_2, constructor, intro i, apply n_ih, simp * } }, end @[simp] lemma cases_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π (x : F.obj $ M F), r (M.mk x)) : pfunctor.M.cases f (M.mk x) = f x := begin dsimp only [M.mk,pfunctor.M.cases,dest,head,approx.s_mk,head'], cases x, dsimp only [approx.s_mk], apply eq_of_heq, apply rec_heq_of_heq, congr' with x, dsimp only [children,approx.s_mk,children'], cases h : x_snd x, dsimp only [head], congr' with n, change (x_snd (x)).approx n = _, rw h end @[simp] lemma cases_on_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π x : F.obj $ M F, r (M.mk x)) : pfunctor.M.cases_on (M.mk x) f = f x := cases_mk x f @[simp] lemma cases_on_mk' {r : M F → Sort*} {a} (x : F.B a → M F) (f : Π a (f : F.B a → M F), r (M.mk ⟨a,f⟩)) : pfunctor.M.cases_on' (M.mk ⟨a,x⟩) f = f a x := cases_mk ⟨_,x⟩ _ /-- `is_path p x` tells us if `p` is a valid path through `x` -/ inductive is_path : path F → M F → Prop | nil (x : M F) : is_path [] x | cons (xs : path F) {a} (x : M F) (f : F.B a → M F) (i : F.B a) : x = M.mk ⟨a,f⟩ → is_path xs (f i) → is_path (⟨a,i⟩ :: xs) x lemma is_path_cons {xs : path F} {a a'} {f : F.B a → M F} {i : F.B a'} : is_path (⟨a',i⟩ :: xs) (M.mk ⟨a,f⟩) → a = a' := begin generalize h : (M.mk ⟨a,f⟩) = x, rintro (_ | ⟨_, _, _, _, _, rfl, _⟩), cases mk_inj h, refl end lemma is_path_cons' {xs : path F} {a} {f : F.B a → M F} {i : F.B a} : is_path (⟨a,i⟩ :: xs) (M.mk ⟨a,f⟩) → is_path xs (f i) := begin generalize h : (M.mk ⟨a,f⟩) = x, rintro (_ | ⟨_, _, _, _, _, rfl, hp⟩), cases mk_inj h, exact hp end /-- follow a path through a value of `M F` and return the subtree found at the end of the path if it is a valid path for that value and return a default tree -/ def isubtree [decidable_eq F.A] [inhabited (M F)] : path F → M F → M F | [] x := x | (⟨a, i⟩ :: ps) x := pfunctor.M.cases_on' x (λ a' f, (if h : a = a' then isubtree ps (f $ cast (by rw h) i) else default : (λ x, M F) (M.mk ⟨a',f⟩))) /-- similar to `isubtree` but returns the data at the end of the path instead of the whole subtree -/ def iselect [decidable_eq F.A] [inhabited (M F)] (ps : path F) : M F → F.A := λ (x : M F), head $ isubtree ps x lemma iselect_eq_default [decidable_eq F.A] [inhabited (M F)] (ps : path F) (x : M F) (h : ¬ is_path ps x) : iselect ps x = head default := begin induction ps generalizing x, { exfalso, apply h, constructor }, { cases ps_hd with a i, induction x using pfunctor.M.cases_on', simp only [iselect,isubtree] at ps_ih ⊢, by_cases h'' : a = x_a, subst x_a, { simp only [dif_pos, eq_self_iff_true, cases_on_mk'], rw ps_ih, intro h', apply h, constructor; try { refl }, apply h' }, { simp * } } end @[simp] lemma head_mk (x : F.obj (M F)) : head (M.mk x) = x.1 := eq.symm $ calc x.1 = (dest (M.mk x)).1 : by rw dest_mk ... = head (M.mk x) : by refl lemma children_mk {a} (x : F.B a → (M F)) (i : F.B (head (M.mk ⟨a,x⟩))) : children (M.mk ⟨a,x⟩) i = x (cast (by rw head_mk) i) := by apply ext'; intro n; refl @[simp] lemma ichildren_mk [decidable_eq F.A] [inhabited (M F)] (x : F.obj (M F)) (i : F.Idx) : ichildren i (M.mk x) = x.iget i := by { dsimp only [ichildren,pfunctor.obj.iget], congr' with h, apply ext', dsimp only [children',M.mk,approx.s_mk], intros, refl } @[simp] lemma isubtree_cons [decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i : F.B a} : isubtree (⟨_,i⟩ :: ps) (M.mk ⟨a,f⟩) = isubtree ps (f i) := by simp only [isubtree,ichildren_mk,pfunctor.obj.iget,dif_pos,isubtree,M.cases_on_mk']; refl @[simp] lemma iselect_nil [decidable_eq F.A] [inhabited (M F)] {a} (f : F.B a → M F) : iselect nil (M.mk ⟨a,f⟩) = a := by refl @[simp] lemma iselect_cons [decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i} : iselect (⟨a,i⟩ :: ps) (M.mk ⟨a,f⟩) = iselect ps (f i) := by simp only [iselect,isubtree_cons] lemma corec_def {X} (f : X → F.obj X) (x₀ : X) : M.corec f x₀ = M.mk (M.corec f <$> f x₀) := begin dsimp only [M.corec,M.mk], congr' with n, cases n with n, { dsimp only [s_corec,approx.s_mk], refl, }, { dsimp only [s_corec,approx.s_mk], cases h : (f x₀), dsimp only [(<$>),pfunctor.map], congr, } end lemma ext_aux [inhabited (M F)] [decidable_eq F.A] {n : ℕ} (x y z : M F) (hx : agree' n z x) (hy : agree' n z y) (hrec : ∀ (ps : path F), n = ps.length → iselect ps x = iselect ps y) : x.approx (n+1) = y.approx (n+1) := begin induction n with n generalizing x y z, { specialize hrec [] rfl, induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on', simp only [iselect_nil] at hrec, subst hrec, simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq], apply subsingleton.elim }, { cases hx, cases hy, induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on', subst z, iterate 3 { have := mk_inj ‹_›, repeat { cases this } }, simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq], ext i, apply n_ih, { solve_by_elim }, { solve_by_elim }, introv h, specialize hrec (⟨_,i⟩ :: ps) (congr_arg _ h), simp only [iselect_cons] at hrec, exact hrec } end open pfunctor.approx variables {F} local attribute [instance, priority 0] classical.prop_decidable lemma ext [inhabited (M F)] (x y : M F) (H : ∀ (ps : path F), iselect ps x = iselect ps y) : x = y := begin apply ext', intro i, induction i with i, { cases x.approx 0, cases y.approx 0, constructor }, { apply ext_aux x y x, { rw ← agree_iff_agree', apply x.consistent }, { rw [← agree_iff_agree',i_ih], apply y.consistent }, introv H', dsimp only [iselect] at H, cases H', apply H ps } end section bisim variable (R : M F → M F → Prop) local infix ` ~ `:50 := R /-- Bisimulation is the standard proof technique for equality between infinite tree-like structures -/ structure is_bisimulation : Prop := (head : ∀ {a a'} {f f'}, M.mk ⟨a,f⟩ ~ M.mk ⟨a',f'⟩ → a = a') (tail : ∀ {a} {f f' : F.B a → M F}, M.mk ⟨a,f⟩ ~ M.mk ⟨a,f'⟩ → (∀ (i : F.B a), f i ~ f' i) ) theorem nth_of_bisim [inhabited (M F)] (bisim : is_bisimulation R) (s₁ s₂) (ps : path F) : s₁ ~ s₂ → is_path ps s₁ ∨ is_path ps s₂ → iselect ps s₁ = iselect ps s₂ ∧ ∃ a (f f' : F.B a → M F), isubtree ps s₁ = M.mk ⟨a,f⟩ ∧ isubtree ps s₂ = M.mk ⟨a,f'⟩ ∧ ∀ (i : F.B a), f i ~ f' i := begin intros h₀ hh, induction s₁ using pfunctor.M.cases_on' with a f, induction s₂ using pfunctor.M.cases_on' with a' f', obtain rfl : a = a' := bisim.head h₀, induction ps with i ps generalizing a f f', { existsi [rfl,a,f,f',rfl,rfl], apply bisim.tail h₀ }, cases i with a' i, obtain rfl : a = a', { cases hh; cases is_path_cons hh; refl }, dsimp only [iselect] at ps_ih ⊢, have h₁ := bisim.tail h₀ i, induction h : (f i) using pfunctor.M.cases_on' with a₀ f₀, induction h' : (f' i) using pfunctor.M.cases_on' with a₁ f₁, simp only [h,h',isubtree_cons] at ps_ih ⊢, rw [h,h'] at h₁, obtain rfl : a₀ = a₁ := bisim.head h₁, apply (ps_ih _ _ _ h₁), rw [← h,← h'], apply or_of_or_of_imp_of_imp hh is_path_cons' is_path_cons' end theorem eq_of_bisim [nonempty (M F)] (bisim : is_bisimulation R) : ∀ s₁ s₂, s₁ ~ s₂ → s₁ = s₂ := begin inhabit (M F), introv Hr, apply ext, introv, by_cases h : is_path ps s₁ ∨ is_path ps s₂, { have H := nth_of_bisim R bisim _ _ ps Hr h, exact H.left }, { rw not_or_distrib at h, cases h with h₀ h₁, simp only [iselect_eq_default,*,not_false_iff] } end end bisim universes u' v' /-- corecursor for `M F` with swapped arguments -/ def corec_on {X : Type*} (x₀ : X) (f : X → F.obj X) : M F := M.corec f x₀ variables {P : pfunctor.{u}} {α : Type u} lemma dest_corec (g : α → P.obj α) (x : α) : M.dest (M.corec g x) = M.corec g <$> g x := by rw [corec_def,dest_mk] lemma bisim (R : M P → M P → Prop) (h : ∀ x y, R x y → ∃ a f f', M.dest x = ⟨a, f⟩ ∧ M.dest y = ⟨a, f'⟩ ∧ ∀ i, R (f i) (f' i)) : ∀ x y, R x y → x = y := begin introv h', haveI := inhabited.mk x.head, apply eq_of_bisim R _ _ _ h', clear h' x y, split; introv ih; rcases h _ _ ih with ⟨ a'', g, g', h₀, h₁, h₂ ⟩; clear h, { replace h₀ := congr_arg sigma.fst h₀, replace h₁ := congr_arg sigma.fst h₁, simp only [dest_mk] at h₀ h₁, rw [h₀,h₁], }, { simp only [dest_mk] at h₀ h₁, cases h₀, cases h₁, apply h₂, }, end theorem bisim' {α : Type*} (Q : α → Prop) (u v : α → M P) (h : ∀ x, Q x → ∃ a f f', M.dest (u x) = ⟨a, f⟩ ∧ M.dest (v x) = ⟨a, f'⟩ ∧ ∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') : ∀ x, Q x → u x = v x := λ x Qx, let R := λ w z : M P, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in @M.bisim P R (λ x y ⟨x', Qx', xeq, yeq⟩, let ⟨a, f, f', ux'eq, vx'eq, h'⟩ := h x' Qx' in ⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩) _ _ ⟨x, Qx, rfl, rfl⟩ -- for the record, show M_bisim follows from _bisim' theorem bisim_equiv (R : M P → M P → Prop) (h : ∀ x y, R x y → ∃ a f f', M.dest x = ⟨a, f⟩ ∧ M.dest y = ⟨a, f'⟩ ∧ ∀ i, R (f i) (f' i)) : ∀ x y, R x y → x = y := λ x y Rxy, let Q : M P × M P → Prop := λ p, R p.fst p.snd in bisim' Q prod.fst prod.snd (λ p Qp, let ⟨a, f, f', hx, hy, h'⟩ := h p.fst p.snd Qp in ⟨a, f, f', hx, hy, λ i, ⟨⟨f i, f' i⟩, h' i, rfl, rfl⟩⟩) ⟨x, y⟩ Rxy theorem corec_unique (g : α → P.obj α) (f : α → M P) (hyp : ∀ x, M.dest (f x) = f <$> (g x)) : f = M.corec g := begin ext x, apply bisim' (λ x, true) _ _ _ _ trivial, clear x, intros x _, cases gxeq : g x with a f', have h₀ : M.dest (f x) = ⟨a, f ∘ f'⟩, { rw [hyp, gxeq, pfunctor.map_eq] }, have h₁ : M.dest (M.corec g x) = ⟨a, M.corec g ∘ f'⟩, { rw [dest_corec, gxeq, pfunctor.map_eq], }, refine ⟨_, _, _, h₀, h₁, _⟩, intro i, exact ⟨f' i, trivial, rfl, rfl⟩ end /-- corecursor where the state of the computation can be sent downstream in the form of a recursive call -/ def corec₁ {α : Type u} (F : Π X, (α → X) → α → P.obj X) : α → M P := M.corec (F _ id) /-- corecursor where it is possible to return a fully formed value at any point of the computation -/ def corec' {α : Type u} (F : Π {X : Type u}, (α → X) → α → M P ⊕ P.obj X) (x : α) : M P := corec₁ (λ X rec (a : M P ⊕ α), let y := a >>= F (rec ∘ sum.inr) in match y with | sum.inr y := y | sum.inl y := (rec ∘ sum.inl) <$> M.dest y end ) (@sum.inr (M P) _ x) end M end pfunctor
d8e508de8832eeade1b6f1884edfe556faf860d5
7c4610454cf55b49f0c3cdaeb6b856eb3249cb2d
/src/mathlib_lemmas.lean
09be408d2db26de6792401e5af0fede0ea6ad1d1
[]
no_license
101damnations/fg_over_pid
097be43e11c3680a3fd4b6de2265de393cf4d4ef
a1a587c455a54a802f6ff61b07bb033701e451a7
refs/heads/master
1,669,708,904,636
1,597,259,770,000
1,597,259,770,000
287,097,363
0
0
null
null
null
null
UTF-8
Lean
false
false
871
lean
import linear_algebra.finsupp open linear_map variables {R : Type*} {M : Type*} {M₂ : Type*} {M₃ : Type*} variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables {α : Type*} (v : α → M) /-- Given 2 surjective R-module homs `f : M →ₗ[R] M₂, g : M₂ →ₗ[R] M₃`, `g ∘ f` is surjective. -/ theorem range_eq_top_comp {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} (hf : range f = ⊤) (hg : range g = ⊤) : range (g.comp f) = ⊤ := by rw [range_comp, hf, ←hg]; refl /-- Given 2 injective R-module homs `f : M →ₗ[R] M₂, g : M₂ →ₗ[R] M₃`, `g ∘ f` is injective.-/ theorem ker_eq_bot_comp {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} (hf : f.ker = ⊥) (hg : g.ker = ⊥) : ker (g.comp f) = ⊥ := by rw [ker_comp, hg, ←hf]; refl
0d1ff2657867a428841614d1274a629c2693b3e3
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/ring_theory/localization.lean
c7439b0c5e39ab324f13da8a598c2ff544f31dce
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,875
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin -/ import ring_theory.ideal_operations universes u v local attribute [instance, priority 10] is_ring_hom.comp namespace localization variables (α : Type u) [comm_ring α] (S : set α) def r (x y : α × S) : Prop := ∃ t ∈ S, ((x.2 : α) * y.1 - y.2 * x.1) * t = 0 local infix ≈ := r α S theorem symm (x y : α × S) : x ≈ y → y ≈ x := λ ⟨t, hts, ht⟩, ⟨t, hts, by rw [← neg_sub, ← neg_mul_eq_neg_mul, ht, neg_zero]⟩ variable [is_submonoid S] section variables {α S} theorem r_of_eq {a₀ a₁ : α × S} (h : (a₀.2 : α) * a₁.1 = a₁.2 * a₀.1) : a₀ ≈ a₁ := ⟨1, is_submonoid.one_mem, by rw [h, sub_self, mul_one]⟩ end theorem refl (x : α × S) : x ≈ x := r_of_eq rfl theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩, ⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts, calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) = t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') : by ring ... = 0 : by simp only [subtype.coe_mk] at ht ht'; rw [ht, ht']; simp⟩ instance : setoid (α × S) := ⟨r α S, refl α S, symm α S, trans α S⟩ end localization /-- The localization of a ring at a submonoid: the elements of the submonoid become invertible in the localization.-/ def localization (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] := quotient $ localization.setoid α S namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] instance : has_add (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.2 * y.1 + y.2 * x.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) = s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₆, ht₅]; simp⟩⟩ instance : has_neg (localization α S) := ⟨quotient.lift (λ x : α × S, (⟦⟨-x.1, x.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, quotient.sound ⟨t, hts, calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring ... = 0 : by simp only [subtype.coe_mk] at ht; rw ht; simp⟩⟩ instance : has_mul (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.1 * y.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) = t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ : by ring ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₅, ht₆]; simp⟩⟩ variables {α S} def mk (r : α) (s : S) : localization α S := ⟦(r, s)⟧ /-- The natural map from the ring to the localization.-/ def of (r : α) : localization α S := mk r 1 instance : comm_ring (localization α S) := by refine { add := has_add.add, add_assoc := λ m n k, quotient.induction_on₃ m n k _, zero := of 0, zero_add := quotient.ind _, add_zero := quotient.ind _, neg := has_neg.neg, add_left_neg := quotient.ind _, add_comm := quotient.ind₂ _, mul := has_mul.mul, mul_assoc := λ m n k, quotient.induction_on₃ m n k _, one := of 1, one_mul := quotient.ind _, mul_one := quotient.ind _, left_distrib := λ m n k, quotient.induction_on₃ m n k _, right_distrib := λ m n k, quotient.induction_on₃ m n k _, mul_comm := quotient.ind₂ _ }; { intros, try {rcases a with ⟨r₁, s₁, hs₁⟩}, try {rcases b with ⟨r₂, s₂, hs₂⟩}, try {rcases c with ⟨r₃, s₃, hs₃⟩}, refine (quotient.sound $ r_of_eq _), simp only [is_submonoid.coe_mul, is_submonoid.coe_one, subtype.coe_mk], ring } instance : inhabited (localization α S) := ⟨0⟩ instance of.is_ring_hom : is_ring_hom (of : α → localization α S) := { map_add := λ x y, quotient.sound $ by simp [add_comm], map_mul := λ x y, quotient.sound $ by simp [add_comm], map_one := rfl } variables {S} instance : has_coe_t α (localization α S) := ⟨of⟩ -- note [use has_coe_t] instance coe.is_ring_hom : is_ring_hom (coe : α → localization α S) := localization.of.is_ring_hom /-- The natural map from the submonoid to the unit group of the localization.-/ def to_units (s : S) : units (localization α S) := { val := s, inv := mk 1 s, val_inv := quotient.sound $ r_of_eq $ mul_assoc _ _ _, inv_val := quotient.sound $ r_of_eq $ show s.val * 1 * 1 = 1 * (1 * s.val), by simp } @[simp] lemma to_units_coe (s : S) : ((to_units s) : localization α S) = ((s : α) : localization α S) := rfl section variables (α S) (x y : α) (n : ℕ) @[simp] lemma of_zero : (of 0 : localization α S) = 0 := rfl @[simp] lemma of_one : (of 1 : localization α S) = 1 := rfl @[simp] lemma of_add : (of (x + y) : localization α S) = of x + of y := by apply is_ring_hom.map_add @[simp] lemma of_sub : (of (x - y) : localization α S) = of x - of y := by apply is_ring_hom.map_sub @[simp] lemma of_mul : (of (x * y) : localization α S) = of x * of y := by apply is_ring_hom.map_mul @[simp] lemma of_neg : (of (-x) : localization α S) = -of x := by apply is_ring_hom.map_neg @[simp] lemma of_pow : (of (x ^ n) : localization α S) = (of x) ^ n := by apply is_semiring_hom.map_pow @[simp] lemma of_is_unit' (s ∈ S) : is_unit (of s : localization α S) := is_unit_unit $ to_units ⟨s, ‹s ∈ S›⟩ @[simp] lemma of_is_unit (s : S) : is_unit (of s : localization α S) := is_unit_unit $ to_units s @[simp] lemma coe_zero : ((0 : α) : localization α S) = 0 := rfl @[simp] lemma coe_one : ((1 : α) : localization α S) = 1 := rfl @[simp] lemma coe_add : (↑(x + y) : localization α S) = x + y := of_add _ _ _ _ @[simp] lemma coe_sub : (↑(x - y) : localization α S) = x - y := of_sub _ _ _ _ @[simp] lemma coe_mul : (↑(x * y) : localization α S) = x * y := of_mul _ _ _ _ @[simp] lemma coe_neg : (↑(-x) : localization α S) = -x := of_neg _ _ _ @[simp] lemma coe_pow : (↑(x ^ n) : localization α S) = x ^ n := of_pow _ _ _ _ @[simp] lemma coe_is_unit' (s ∈ S) : is_unit ((s : α) : localization α S) := of_is_unit' _ _ _ ‹s ∈ S› @[simp] lemma coe_is_unit (s : S) : is_unit ((s : α) : localization α S) := of_is_unit _ _ _ end lemma mk_self {x : α} {hx : x ∈ S} : (mk x ⟨x, hx⟩ : localization α S) = 1 := quotient.sound ⟨1, is_submonoid.one_mem, by simp only [subtype.coe_mk, is_submonoid.coe_one, mul_one, one_mul, sub_self]⟩ lemma mk_self' {s : S} : (mk s s : localization α S) = 1 := by cases s; exact mk_self lemma mk_self'' {s : S} : (mk s.1 s : localization α S) = 1 := mk_self' -- This lemma does not apply with simp, since (mk r s) simplifies to (r * s⁻¹). -- However, it could apply with dsimp. @[simp, nolint simp_nf] lemma coe_mul_mk (x y : α) (s : S) : ↑x * mk y s = mk (x * y) s := quotient.sound $ r_of_eq $ by rw one_mul lemma mk_eq_mul_mk_one (r : α) (s : S) : mk r s = r * mk 1 s := by rw [coe_mul_mk, mul_one] -- This lemma does not apply with simp, since (mk r s) simplifies to (r * s⁻¹). -- However, it could apply with dsimp. @[simp, nolint simp_nf] lemma mk_mul_mk (x y : α) (s t : S) : mk x s * mk y t = mk (x * y) (s * t) := rfl lemma mk_mul_cancel_left (r : α) (s : S) : mk (↑s * r) s = r := by rw [mk_eq_mul_mk_one, mul_comm ↑s, coe_mul, mul_assoc, ← mk_eq_mul_mk_one, mk_self', mul_one] lemma mk_mul_cancel_right (r : α) (s : S) : mk (r * s) s = r := by rw [mul_comm, mk_mul_cancel_left] @[simp] lemma mk_eq (r : α) (s : S) : mk r s = r * ((to_units s)⁻¹ : units _) := quotient.sound $ by simp @[elab_as_eliminator] protected theorem induction_on {C : localization α S → Prop} (x : localization α S) (ih : ∀ r s, C (mk r s : localization α S)) : C x := by rcases x with ⟨r, s⟩; exact ih r s section variables {β : Type v} [comm_ring β] {T : set β} [is_submonoid T] (f : α → β) [is_ring_hom f] @[elab_with_expected_type] def lift' (g : S → units β) (hg : ∀ s, (g s : β) = f s) (x : localization α S) : β := quotient.lift_on x (λ p, f p.1 * ((g p.2)⁻¹ : units β)) $ λ ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨t, hts, ht⟩, show f r₁ * ↑(g s₁)⁻¹ = f r₂ * ↑(g s₂)⁻¹, from calc f r₁ * ↑(g s₁)⁻¹ = (f r₁ * g s₂ + ((g s₁ * f r₂ - g s₂ * f r₁) * g ⟨t, hts⟩) * ↑(g ⟨t, hts⟩)⁻¹) * ↑(g s₁)⁻¹ * ↑(g s₂)⁻¹ : by simp only [hg, subtype.coe_mk, (is_ring_hom.map_mul f).symm, (is_ring_hom.map_sub f).symm, ht, is_ring_hom.map_zero f, zero_mul, add_zero]; rw [is_ring_hom.map_mul f, ← hg, mul_right_comm, mul_assoc (f r₁), ← units.coe_mul, mul_inv_self]; rw [units.coe_one, mul_one] ... = f r₂ * ↑(g s₂)⁻¹ : by rw [mul_assoc, mul_assoc, ← units.coe_mul, mul_inv_self, units.coe_one, mul_one, mul_comm ↑(g s₂), add_sub_cancel'_right]; rw [mul_comm ↑(g s₁), ← mul_assoc, mul_assoc (f r₂), ← units.coe_mul, mul_inv_self, units.coe_one, mul_one] instance lift'.is_ring_hom (g : S → units β) (hg : ∀ s, (g s : β) = f s) : is_ring_hom (localization.lift' f g hg) := { map_one := have g 1 = 1, from units.ext (by rw hg; exact is_ring_hom.map_one f), show f 1 * ↑(g 1)⁻¹ = 1, by rw [this, one_inv, units.coe_one, mul_one, is_ring_hom.map_one f], map_mul := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = (_ * _) * (_ * _), by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; rw [is_ring_hom.map_mul f, units.coe_mul, ← mul_assoc, ← mul_assoc]; simp only [mul_right_comm], map_add := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = _ * _ + _ * _, by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; simp only [is_ring_hom.map_mul f, is_ring_hom.map_add f, add_mul, (hg _).symm]; simp only [mul_assoc, mul_comm, mul_left_comm, (units.coe_mul _ _).symm]; rw [mul_inv_cancel_left, mul_left_comm, ← mul_assoc, mul_inv_cancel_right, add_comm] } noncomputable def lift (h : ∀ s ∈ S, is_unit (f s)) : localization α S → β := localization.lift' f (λ s, classical.some $ h s.1 s.2) (λ s, by rw [← classical.some_spec (h s.1 s.2)]; refl) instance lift.is_ring_hom (h : ∀ s ∈ S, is_unit (f s)) : is_ring_hom (lift f h) := lift'.is_ring_hom _ _ _ -- This lemma does not apply with simp, since (mk r s) simplifies to (r * s⁻¹). -- However, it could apply with dsimp. @[simp, nolint simp_nf] lemma lift'_mk (g : S → units β) (hg : ∀ s, (g s : β) = f s) (r : α) (s : S) : lift' f g hg (mk r s) = f r * ↑(g s)⁻¹ := rfl @[simp] lemma lift'_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg (of a) = f a := have g 1 = 1, from units.ext_iff.2 $ by simp [hg, is_ring_hom.map_one f], by simp [lift', quotient.lift_on_beta, of, mk, this] @[simp] lemma lift'_coe (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg a = f a := lift'_of _ _ _ _ @[simp] lemma lift_of (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h (of a) = f a := lift'_of _ _ _ _ @[simp] lemma lift_coe (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h a = f a := lift'_of _ _ _ _ @[simp] lemma lift'_comp_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' f g hg ∘ of = f := funext $ λ a, lift'_of _ _ _ a @[simp] lemma lift_comp_of (h : ∀ s ∈ S, is_unit (f s)) : lift f h ∘ of = f := lift'_comp_of _ _ _ @[simp] lemma lift'_apply_coe (f : localization α S → β) [is_ring_hom f] (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' (λ a : α, f a) g hg = f := have g = (λ s, (units.map' f : units (localization α S) → units β) (to_units s)), from funext $ λ x, units.ext $ (hg x).symm ▸ rfl, funext $ λ x, localization.induction_on x (λ r s, by subst this; rw [lift'_mk, ← (units.map' f).map_inv, units.coe_map']; simp [is_ring_hom.map_mul f]) @[simp] lemma lift_apply_coe (f : localization α S → β) [is_ring_hom f] : lift (λ a : α, f a) (λ s hs, is_unit.map' f (is_unit_unit (to_units ⟨s, hs⟩))) = f := by rw [lift, lift'_apply_coe] /-- Function extensionality for localisations: two functions are equal if they agree on elements that are coercions.-/ protected lemma funext (f g : localization α S → β) [is_ring_hom f] [is_ring_hom g] (h : ∀ a : α, f a = g a) : f = g := begin rw [← lift_apply_coe f, ← lift_apply_coe g], congr' 1, exact funext h end variables {α S T} def map (hf : ∀ s ∈ S, f s ∈ T) : localization α S → localization β T := lift' (of ∘ f) (to_units ∘ subtype.map f hf) (λ s, rfl) instance map.is_ring_hom (hf : ∀ s ∈ S, f s ∈ T) : is_ring_hom (map f hf) := lift'.is_ring_hom _ _ _ @[simp] lemma map_of (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf (of a) = of (f a) := lift'_of _ _ _ _ @[simp] lemma map_coe (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf a = (f a) := lift'_of _ _ _ _ @[simp] lemma map_comp_of (hf : ∀ s ∈ S, f s ∈ T) : map f hf ∘ of = of ∘ f := funext $ λ a, map_of _ _ _ @[simp] lemma map_id : map id (λ s (hs : s ∈ S), hs) = id := localization.funext _ _ $ map_coe _ _ lemma map_comp_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) : map g hg ∘ map f hf = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) := localization.funext _ _ $ by simp lemma map_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) (x) : map g hg (map f hf x) = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) x := congr_fun (map_comp_map _ _ _ _ _) x def equiv_of_equiv (h₁ : α ≃+* β) (h₂ : h₁ '' S = T) : localization α S ≃+* localization β T := { to_fun := map h₁ $ λ s hs, h₂ ▸ set.mem_image_of_mem _ hs, inv_fun := map h₁.symm $ λ t ht, by simp [h₁.image_eq_preimage, set.preimage, set.ext_iff, *] at *, left_inv := λ _, by simp only [map_map, h₁.symm_apply_apply]; erw map_id; refl, right_inv := λ _, by simp only [map_map, h₁.apply_symm_apply]; erw map_id; refl, map_mul' := λ _ _, is_ring_hom.map_mul _, map_add' := λ _ _, is_ring_hom.map_add _ } end section away variables {β : Type v} [comm_ring β] (f : α → β) [is_ring_hom f] @[reducible] def away (x : α) := localization α (powers x) @[simp] def away.inv_self (x : α) : away x := mk 1 ⟨x, 1, pow_one x⟩ @[elab_with_expected_type] noncomputable def away.lift {x : α} (hfx : is_unit (f x)) : away x → β := localization.lift' f (λ s, classical.some hfx ^ classical.some s.2) $ λ s, by rw [units.coe_pow, ← classical.some_spec hfx, ← is_semiring_hom.map_pow f, classical.some_spec s.2]; refl instance away.lift.is_ring_hom {x : α} (hfx : is_unit (f x)) : is_ring_hom (localization.away.lift f hfx) := lift'.is_ring_hom _ _ _ @[simp] lemma away.lift_of {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx (of a) = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_coe {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx a = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_comp_of {x : α} (hfx : is_unit (f x)) : away.lift f hfx ∘ of = f := lift'_comp_of _ _ _ noncomputable def away_to_away_right (x y : α) : away x → away (x * y) := localization.away.lift coe $ is_unit_of_mul_eq_one x (y * away.inv_self (x * y)) $ by rw [away.inv_self, coe_mul_mk, coe_mul_mk, mul_one, mk_self] instance away_to_away_right.is_ring_hom (x y : α) : is_ring_hom (away_to_away_right x y) := away.lift.is_ring_hom _ _ end away section at_prime variables (P : ideal α) [hp : ideal.is_prime P] include hp instance prime.is_submonoid : is_submonoid (-P : set α) := { one_mem := P.ne_top_iff_one.1 hp.1, mul_mem := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } @[reducible] def at_prime := localization α (-P) instance at_prime.local_ring : local_ring (at_prime P) := local_of_nonunits_ideal (λ hze, let ⟨t, hts, ht⟩ := quotient.exact hze in hts $ have htz : t = 0, by simpa using ht, suffices (0:α) ∈ P, by rwa htz, P.zero_mem) (begin rintro ⟨⟨r₁, s₁, hs₁⟩⟩ ⟨⟨r₂, s₂, hs₂⟩⟩ hx hy hu, rcases is_unit_iff_exists_inv.1 hu with ⟨⟨⟨r₃, s₃, hs₃⟩⟩, hz⟩, rcases quotient.exact hz with ⟨t, hts, ht⟩, simp at ht, have : ∀ {r s hs}, (⟦⟨r, s, hs⟩⟧ : at_prime P) ∈ nonunits (at_prime P) → r ∈ P, { haveI := classical.dec, exact λ r s hs, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨⟦⟨s, r, nr⟩⟧, quotient.sound $ r_of_eq $ by simp [mul_comm]⟩) }, have hr₃ := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right hts, have := (ideal.add_mem_iff_left _ _).1 hr₃, { exact not_or (mt hp.mem_or_mem (not_or hs₁ hs₂)) hs₃ (hp.mem_or_mem this) }, { exact P.neg_mem (P.mul_mem_right (P.add_mem (P.mul_mem_left (this hy)) (P.mul_mem_left (this hx)))) } end) end at_prime variable (α) def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0} instance non_zero_divisors.is_submonoid : is_submonoid (non_zero_divisors α) := { one_mem := λ z hz, by rwa mul_one at hz, mul_mem := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } @[simp] lemma non_zero_divisors_one_val : (1 : non_zero_divisors α).val = 1 := rfl /-- The field of fractions of an integral domain.-/ @[reducible] def fraction_ring := localization α (non_zero_divisors α) namespace fraction_ring open function variables {β : Type u} [integral_domain β] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} : x ≠ 0 → y * x = 0 → y = 0 := λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : β} : x ∈ non_zero_divisors β ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ variables (β) [de : decidable_eq β] include de def inv_aux (x : β × (non_zero_divisors β)) : fraction_ring β := if h : x.1 = 0 then 0 else ⟦⟨x.2, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ instance : has_inv (fraction_ring β) := ⟨quotient.lift (inv_aux β) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, begin have hrs : s₁ * r₂ = 0 + s₂ * r₁, from sub_eq_iff_eq_add.1 (hts _ ht), by_cases hr₁ : r₁ = 0; by_cases hr₂ : r₂ = 0; simp [hr₁, hr₂] at hrs; simp only [inv_aux, hr₁, hr₂, dif_pos, dif_neg, not_false_iff, subtype.coe_mk, quotient.eq], { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₁ hrs }, { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₂ hrs }, { apply r_of_eq, simpa [mul_comm] using hrs.symm } end⟩ lemma mk_inv {r s} : (mk r s : fraction_ring β)⁻¹ = if h : r = 0 then 0 else ⟦⟨s, r, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ := rfl lemma mk_inv' : ∀ (x : β × (non_zero_divisors β)), (⟦x⟧⁻¹ : fraction_ring β) = if h : x.1 = 0 then 0 else ⟦⟨x.2.val, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ | ⟨r,s,hs⟩ := rfl instance : decidable_eq (fraction_ring β) := @quotient.decidable_eq (β × non_zero_divisors β) (localization.setoid β (non_zero_divisors β)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, show decidable (∃ t ∈ non_zero_divisors β, (s₁ * r₂ - s₂ * r₁) * t = 0), from decidable_of_iff (s₁ * r₂ - s₂ * r₁ = 0) ⟨λ H, ⟨1, λ y, (mul_one y).symm ▸ id, H.symm ▸ zero_mul _⟩, λ ⟨t, ht1, ht2⟩, or.resolve_right (mul_eq_zero.1 ht2) $ λ ht, one_ne_zero (ht1 1 ((one_mul t).symm ▸ ht))⟩ instance : field (fraction_ring β) := by refine { inv := has_inv.inv, zero_ne_one := λ hzo, let ⟨t, hts, ht⟩ := quotient.exact hzo in zero_ne_one (by simpa using hts _ ht : 0 = 1), mul_inv_cancel := quotient.ind _, inv_zero := dif_pos rfl, .. localization.comm_ring }; { intros x hnx, rcases x with ⟨x, z, hz⟩, have : x ≠ 0, from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]), simp only [has_inv.inv, inv_aux, quotient.lift_beta, dif_neg this], exact (quotient.sound $ r_of_eq $ by simp [mul_comm]) } lemma mk_eq_div {r s} : (mk r s : fraction_ring β) = (r / s : fraction_ring β) := by simp [div_eq_mul_inv] variables {β} @[simp] lemma mk_eq_div' (x : β × (non_zero_divisors β)) : (⟦x⟧ : fraction_ring β) = ((x.1) / ((x.2).val) : fraction_ring β) := by erw ← mk_eq_div; cases x; refl lemma eq_zero_of (x : β) (h : (of x : fraction_ring β) = 0) : x = 0 := begin rcases quotient.exact h with ⟨t, ht, ht'⟩, simpa [mem_non_zero_divisors_iff_ne_zero.mp ht] using ht' end omit de lemma of.injective : function.injective (of : β → fraction_ring β) := (is_add_group_hom.injective_iff _).mpr $ by { classical, exact eq_zero_of } section map open function is_ring_hom variables {A : Type u} [integral_domain A] variables {B : Type v} [integral_domain B] variables (f : A → B) [is_ring_hom f] def map (hf : injective f) : fraction_ring A → fraction_ring B := localization.map f $ λ s h, by rw [mem_non_zero_divisors_iff_ne_zero, ← map_zero f, ne.def, hf.eq_iff]; exact mem_non_zero_divisors_iff_ne_zero.1 h @[simp] lemma map_of (hf : injective f) (a : A) : map f hf (of a) = of (f a) := localization.map_of _ _ _ @[simp] lemma map_coe (hf : injective f) (a : A) : map f hf a = f a := localization.map_coe _ _ _ @[simp] lemma map_comp_of (hf : injective f) : map f hf ∘ (of : A → fraction_ring A) = (of : B → fraction_ring B) ∘ f := localization.map_comp_of _ _ instance map.is_ring_hom (hf : injective f) : is_ring_hom (map f hf) := localization.map.is_ring_hom _ _ def equiv_of_equiv (h : A ≃+* B) : fraction_ring A ≃+* fraction_ring B := localization.equiv_of_equiv h begin ext b, rw [h.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero, ne.def], exact h.symm.map_ne_zero_iff end end map end fraction_ring section ideals theorem map_comap (J : ideal (localization α S)) : ideal.map (ring_hom.of coe) (ideal.comap (ring_hom.of (coe : α → localization α S)) J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x, localization.induction_on x $ λ r s hJ, (submodule.mem_coe _).2 $ mul_one r ▸ coe_mul_mk r 1 s ▸ (ideal.mul_mem_right _ $ ideal.mem_map_of_mem $ have _ := @ideal.mul_mem_left (localization α S) _ _ s _ hJ, by rwa [coe_coe, coe_mul_mk, mk_mul_cancel_left] at this) def le_order_embedding : ((≤) : ideal (localization α S) → ideal (localization α S) → Prop) ≼o ((≤) : ideal α → ideal α → Prop) := { to_fun := λ J, ideal.comap (ring_hom.of coe) J, inj := function.injective_of_left_inverse (map_comap α), ord := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, map_comap α J₁ ▸ map_comap α J₂ ▸ ideal.map_mono hJ⟩ } end ideals section module /-! ### `module` section Localizations form an algebra over `α` induced by the embedding `coe : α → localization α S`. -/ variables (α S) instance : algebra α (localization α S) := (ring_hom.of coe).to_algebra lemma of_smul (c x : α) : (of (c • x) : localization α S) = c • of x := by { simp, refl } lemma coe_smul (c x : α) : (coe (c • x) : localization α S) = c • coe x := of_smul α S c x lemma coe_mul_eq_smul (c : α) (x : localization α S) : coe c * x = c • x := rfl lemma mul_coe_eq_smul (c : α) (x : localization α S) : x * coe c = c • x := mul_comm x (coe c) /-- The embedding `coe : α → localization α S` induces a linear map. -/ def lin_coe : α →ₗ[α] localization α S := ⟨coe, coe_add α S, coe_smul α S⟩ @[simp] lemma lin_coe_apply (a : α) : lin_coe α S a = coe a := rfl instance coe_submodules : has_coe (ideal α) (submodule α (localization α S)) := ⟨submodule.map (lin_coe _ _)⟩ @[simp] lemma of_id (a : α) : (algebra.of_id α (localization α S) : α → localization α S) a = ↑a := rfl end module section is_integer /-- `a : localization α S` is an integer if it is an element of the original ring `α` -/ def is_integer (S : set α) [is_submonoid S] (a : localization α S) : Prop := a ∈ set.range (coe : α → localization α S) lemma is_integer_coe (a : α) : is_integer α S a := ⟨a, rfl⟩ lemma is_integer_add {a b} (ha : is_integer α S a) (hb : is_integer α S b) : is_integer α S (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [coe_add, ha, hb] end lemma is_integer_mul {a b} (ha : is_integer α S a) (hb : is_integer α S b) : is_integer α S (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [coe_mul, ha, hb] end lemma is_integer_smul {a : α} {b} (hb : is_integer α S b) : is_integer α S (a • b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, ←coe_smul, smul_eq_mul] end end is_integer end localization
8aad83c4d88d6a240bc2cc00d191131f2d281dfc
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/char_p/two.lean
f2a0f581812fecb9950827bd1e6f934948d214c5
[ "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
3,056
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.char_p.basic /-! # Lemmas about rings of characteristic two This file contains results about `char_p R 2`, in the `char_two` namespace. The lemmas in this file with a `_sq` suffix are just special cases of the `_pow_char` lemmas elsewhere, with a shorter name for ease of discovery, and no need for a `[fact (prime 2)]` argument. -/ variables {R ι : Type*} namespace char_two section semiring variables [semiring R] [char_p R 2] lemma two_eq_zero : (2 : R) = 0 := by rw [← nat.cast_two, char_p.cast_eq_zero] lemma add_self_eq_zero (x : R) : x + x = 0 := by rw [←two_smul R x, two_eq_zero, zero_smul] lemma bit0_eq_zero (x : R) : (bit0 x : R) = 0 := add_self_eq_zero x lemma bit1_eq_one (x : R) : (bit1 x : R) = 1 := by rw [bit1, bit0_eq_zero, zero_add] end semiring section ring variables [ring R] [char_p R 2] lemma neg_eq (x : R) : -x = x := by rw [neg_eq_iff_add_eq_zero, ←two_smul R x, two_eq_zero, zero_smul] lemma neg_eq' : has_neg.neg = (id : R → R) := funext neg_eq lemma sub_eq_add (x y : R) : x - y = x + y := by rw [sub_eq_add_neg, neg_eq] lemma sub_eq_add' : has_sub.sub = ((+) : R → R → R) := funext $ λ x, funext $ λ y, sub_eq_add x y end ring section comm_semiring variables [comm_semiring R] [char_p R 2] lemma add_sq (x y : R) : (x + y) ^ 2 = x ^ 2 + y ^ 2 := add_pow_char _ _ _ lemma add_mul_self (x y : R) : (x + y) * (x + y) = x * x + y * y := by rw [←pow_two, ←pow_two, ←pow_two, add_sq] open_locale big_operators lemma list_sum_sq (l : list R) : l.sum ^ 2 = (l.map (^ 2)).sum := list_sum_pow_char _ _ lemma list_sum_mul_self (l : list R) : l.sum * l.sum = (list.map (λ x, x * x) l).sum := by simp_rw [←pow_two, list_sum_sq] lemma multiset_sum_sq (l : multiset R) : l.sum ^ 2 = (l.map (^ 2)).sum := multiset_sum_pow_char _ _ lemma multiset_sum_mul_self (l : multiset R) : l.sum * l.sum = (multiset.map (λ x, x * x) l).sum := by simp_rw [←pow_two, multiset_sum_sq] lemma sum_sq (s : finset ι) (f : ι → R) : (∑ i in s, f i) ^ 2 = ∑ i in s, f i ^ 2 := sum_pow_char _ _ _ lemma sum_mul_self (s : finset ι) (f : ι → R) : (∑ i in s, f i) * (∑ i in s, f i) = ∑ i in s, f i * f i := by simp_rw [←pow_two, sum_sq] end comm_semiring end char_two section ring_char variables [ring R] lemma neg_one_eq_one_iff [nontrivial R]: (-1 : R) = 1 ↔ ring_char R = 2 := begin refine ⟨λ h, _, λ h, @@char_two.neg_eq _ (ring_char.of_eq h) 1⟩, rw [eq_comm, ←sub_eq_zero, sub_neg_eq_add, ← nat.cast_one, ← nat.cast_add] at h, exact ((nat.dvd_prime nat.prime_two).mp (ring_char.dvd h)).resolve_left char_p.ring_char_ne_one end @[simp] lemma order_of_neg_one [nontrivial R] : order_of (-1 : R) = if ring_char R = 2 then 1 else 2 := begin split_ifs, { rw [neg_one_eq_one_iff.2 h, order_of_one] }, apply order_of_eq_prime, { simp }, simpa [neg_one_eq_one_iff] using h end end ring_char
b994f5543bd61fa13d04c8620ce817de2be9ae38
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/preadditive/projective.lean
bcb2d2dd16182aaaa5369cafe366a28b532af117
[ "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
6,540
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 -/ import algebra.homology.exact import category_theory.types import category_theory.limits.shapes.biproducts /-! # Projective objects and categories with enough projectives An object `P` is called projective if every morphism out of `P` factors through every epimorphism. A category `C` has enough projectives if every object admits an epimorphism from some projective object. `projective.over X` picks an arbitrary such projective object, and `projective.π X : projective.over X ⟶ X` is the corresponding epimorphism. Given a morphism `f : X ⟶ Y`, `projective.left f` is a projective object over `kernel f`, and `projective.d f : projective.left f ⟶ X` is the morphism `π (kernel f) ≫ kernel.ι f`. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] /-- An object `P` is called projective if every morphism out of `P` factors through every epimorphism. -/ class projective (P : C) : Prop := (factors : ∀ {E X : C} (f : P ⟶ X) (e : E ⟶ X) [epi e], ∃ f', f' ≫ e = f) section /-- A projective presentation of an object `X` consists of an epimorphism `f : P ⟶ X` from some projective object `P`. -/ @[nolint has_inhabited_instance] structure projective_presentation (X : C) := (P : C) (projective : projective P . tactic.apply_instance) (f : P ⟶ X) (epi : epi f . tactic.apply_instance) variables (C) /-- A category "has enough projectives" if for every object `X` there is a projective object `P` and an epimorphism `P ↠ X`. -/ class enough_projectives : Prop := (presentation : ∀ (X : C), nonempty (projective_presentation X)) end namespace projective /-- An arbitrarily chosen factorisation of a morphism out of a projective object through an epimorphism. -/ def factor_thru {P X E : C} [projective P] (f : P ⟶ X) (e : E ⟶ X) [epi e] : P ⟶ E := (projective.factors f e).some @[simp] lemma factor_thru_comp {P X E : C} [projective P] (f : P ⟶ X) (e : E ⟶ X) [epi e] : factor_thru f e ≫ e = f := (projective.factors f e).some_spec section open_locale zero_object instance zero_projective [has_zero_object C] [has_zero_morphisms C] : projective (0 : C) := { factors := λ E X f e epi, by { use 0, ext, }} end lemma of_iso {P Q : C} (i : P ≅ Q) (hP : projective P) : projective Q := begin fsplit, introsI E X f e e_epi, obtain ⟨f', hf'⟩ := projective.factors (i.hom ≫ f) e, exact ⟨i.inv ≫ f', by simp [hf']⟩ end lemma iso_iff {P Q : C} (i : P ≅ Q) : projective P ↔ projective Q := ⟨of_iso i, of_iso i.symm⟩ /-- The axiom of choice says that every type is a projective object in `Type`. -/ instance (X : Type u) : projective X := { factors := λ E X' f e epi, ⟨λ x, ((epi_iff_surjective _).mp epi (f x)).some, by { ext x, exact ((epi_iff_surjective _).mp epi (f x)).some_spec, }⟩ } instance Type.enough_projectives : enough_projectives (Type u) := { presentation := λ X, ⟨{ P := X, f := 𝟙 X, }⟩, } instance {P Q : C} [has_binary_coproduct P Q] [projective P] [projective Q] : projective (P ⨿ Q) := { factors := λ E X' f e epi, by exactI ⟨coprod.desc (factor_thru (coprod.inl ≫ f) e) (factor_thru (coprod.inr ≫ f) e), by tidy⟩, } section local attribute [tidy] tactic.discrete_cases instance {β : Type v} (g : β → C) [has_coproduct g] [∀ b, projective (g b)] : projective (∐ g) := { factors := λ E X' f e epi, by exactI ⟨sigma.desc (λ b, factor_thru (sigma.ι g b ≫ f) e), by tidy⟩, } end instance {P Q : C} [has_zero_morphisms C] [has_binary_biproduct P Q] [projective P] [projective Q] : projective (P ⊞ Q) := { factors := λ E X' f e epi, by exactI ⟨biprod.desc (factor_thru (biprod.inl ≫ f) e) (factor_thru (biprod.inr ≫ f) e), by tidy⟩, } instance {β : Type v} (g : β → C) [has_zero_morphisms C] [has_biproduct g] [∀ b, projective (g b)] : projective (⨁ g) := { factors := λ E X' f e epi, by exactI ⟨biproduct.desc (λ b, factor_thru (biproduct.ι g b ≫ f) e), by tidy⟩, } section enough_projectives variables [enough_projectives C] /-- `projective.over X` provides an arbitrarily chosen projective object equipped with an epimorphism `projective.π : projective.over X ⟶ X`. -/ def over (X : C) : C := (enough_projectives.presentation X).some.P instance projective_over (X : C) : projective (over X) := (enough_projectives.presentation X).some.projective /-- The epimorphism `projective.π : projective.over X ⟶ X` from the arbitrarily chosen projective object over `X`. -/ def π (X : C) : over X ⟶ X := (enough_projectives.presentation X).some.f instance π_epi (X : C) : epi (π X) := (enough_projectives.presentation X).some.epi section variables [has_zero_morphisms C] {X Y : C} (f : X ⟶ Y) [has_kernel f] /-- When `C` has enough projectives, the object `projective.syzygies f` is an arbitrarily chosen projective object over `kernel f`. -/ @[derive projective] def syzygies : C := over (kernel f) /-- When `C` has enough projectives, `projective.d f : projective.syzygies f ⟶ X` is the composition `π (kernel f) ≫ kernel.ι f`. (When `C` is abelian, we have `exact (projective.d f) f`.) -/ abbreviation d : syzygies f ⟶ X := π (kernel f) ≫ kernel.ι f end end enough_projectives end projective open projective section variables [has_zero_morphisms C] [has_equalizers C] [has_images C] /-- Given a projective object `P` mapping via `h` into the middle object `R` of a pair of exact morphisms `f : Q ⟶ R` and `g : R ⟶ S`, such that `h ≫ g = 0`, there is a lift of `h` to `Q`. -/ def exact.lift {P Q R S : C} [projective P] (h : P ⟶ R) (f : Q ⟶ R) (g : R ⟶ S) (hfg : exact f g) (w : h ≫ g = 0) : P ⟶ Q := factor_thru (factor_thru (factor_thru_kernel_subobject g h w) (image_to_kernel f g hfg.w)) (factor_thru_image_subobject f) @[simp] lemma exact.lift_comp {P Q R S : C} [projective P] (h : P ⟶ R) (f : Q ⟶ R) (g : R ⟶ S) (hfg : exact f g) (w : h ≫ g = 0) : exact.lift h f g hfg w ≫ f = h := begin simp [exact.lift], conv_lhs { congr, skip, rw ← image_subobject_arrow_comp f, }, rw [←category.assoc, factor_thru_comp, ←image_to_kernel_arrow, ←category.assoc, category_theory.projective.factor_thru_comp, factor_thru_kernel_subobject_comp_arrow], end end end category_theory
737e7728f6c0d5e0f8de5ccbd917df5e078e870c
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/basic.lean
399c92ae73de50de64c2d4f4af9ffd496ec277f6
[ "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
74,093
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import order.filter.small_sets import algebra.support /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter `nhds x` of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`; * `𝓝[≤] x`: the filter `nhds_within x (set.Iic x)` of left-neighborhoods of `x`; * `𝓝[≥] x`: the filter `nhds_within x (set.Ici x)` of right-neighborhoods of `x`; * `𝓝[<] x`: the filter `nhds_within x (set.Iio x)` of punctured left-neighborhoods of `x`; * `𝓝[>] x`: the filter `nhds_within x (set.Ioi x)` of punctured right-neighborhoods of `x`; * `𝓝[≠] x`: the filter `nhds_within x {x}ᶜ` of punctured neighborhoods of `x`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable theory open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa only [compl_inter] using union_mem sᶜ hs tᶜ ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ t : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [topological_space α] /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open ‹_› s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ _ lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter _ 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 _ s h end lemma topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : s.finite) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : s.finite) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open.inter /-- A set is closed if its complement is open -/ class is_closed (s : set α) : Prop := (is_open_compl : is_open sᶜ) @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := ⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set α) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ } lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) : is_closed (⋂ i ∈ s, f i) := is_closed_Inter $ λ i, is_closed_Inter $ h i @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ := is_closed_compl_iff.2 hs lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open.inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ } lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) := is_closed.inter h₁ (is_closed_compl_iff.mpr h₂) lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : s.finite) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_sUnion, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma subset_interior_iff {s t : set α} : t ⊆ interior s ↔ ∃ U, is_open U ∧ t ⊆ U ∧ U ⊆ s := ⟨λ h, ⟨interior s, is_open_interior, h, interior_subset⟩, λ ⟨U, hU, htU, hUs⟩, htU.trans (interior_maximal hUs hU)⟩ @[mono] lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_eq_univ {s : set α} : interior s = univ ↔ s = univ := ⟨λ h, univ_subset_iff.mp $ h.symm.trans_le interior_subset, λ h, h.symm ▸ interior_univ⟩ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open.inter is_open_interior is_open_interior) @[simp] lemma finset.interior_Inter {ι : Type*} (s : finset ι) (f : ι → set α) : interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma interior_Inter_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) : interior (⋂ i, f i) = ⋂ i, interior (f i) := by { convert finset.univ.interior_Inter f; simp, } lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open.sdiff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] lemma interior_Inter_subset (s : ι → set α) : interior (⋂ i, s i) ⊆ ⋂ i, interior (s i) := subset_Inter $ λ i, interior_mono $ Inter_subset _ _ lemma interior_Inter₂_subset (p : ι → Sort*) (s : Π i, p i → set α) : interior (⋂ i j, s i j) ⊆ ⋂ i j, interior (s i j) := (interior_Inter_subset _).trans $ Inter_mono $ λ i, interior_Inter_subset _ lemma interior_sInter_subset (S : set (set α)) : interior (⋂₀ S) ⊆ ⋂ s ∈ S, interior s := calc interior (⋂₀ S) = interior (⋂ s ∈ S, s) : by rw sInter_eq_bInter ... ⊆ ⋂ s ∈ S, interior s : interior_Inter₂_subset _ _ /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma not_mem_of_not_mem_closure {s : set α} {P : α} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma disjoint.closure_left {s t : set α} (hd : disjoint s t) (ht : is_open t) : disjoint (closure s) t := disjoint_compl_left.mono_left $ closure_minimal hd.subset_compl_right ht.is_closed_compl lemma disjoint.closure_right {s t : set α} (hd : disjoint s t) (hs : is_open s) : disjoint s (closure t) := (hd.symm.closure_left hs).symm lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma is_closed.mem_iff_closure_subset {α : Type*} [topological_space α] {U : set α} (hU : is_closed U) {x : α} : x ∈ U ↔ closure ({x} : set α) ⊆ U := (hU.closure_subset_iff.trans set.singleton_subset_iff).symm @[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma diff_subset_closure_iff {s t : set α} : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed.union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) @[simp] lemma finset.closure_bUnion {ι : Type*} (s : finset ι) (f : ι → set α) : closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma closure_Union_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) : closure (⋃ i, f i) = ⋃ i, closure (f i) := by { convert finset.univ.closure_bUnion f; simp, } lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h lemma interior_eq_empty_iff_dense_compl {s : set α} : interior s = ∅ ↔ dense sᶜ := by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff] lemma dense.interior_compl {s : set α} (h : dense s) : interior sᶜ = ∅ := interior_eq_empty_iff_dense_compl.2 $ by rwa compl_compl /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.exists_mem_open {s : set α} (hs : dense s) {U : set α} (ho : is_open U) (hne : U.nonempty) : ∃ x ∈ s, x ∈ U := let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne in ⟨x, hx.2, hx.1⟩ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-- Complement to a singleton is dense if and only if the singleton is not an open set. -/ lemma dense_compl_singleton_iff_not_open {x : α} : dense ({x}ᶜ : set α) ↔ ¬is_open ({x} : set α) := begin fsplit, { intros hd ho, exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) }, { refine λ ho, dense_iff_inter_open.2 (λ U hU hne, inter_compl_nonempty_iff.2 $ λ hUx, _), obtain rfl : U = {x}, from eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩, exact ho hU } end /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s @[simp] lemma closure_diff_interior (s : set α) : closure s \ interior s = frontier s := rfl @[simp] lemma closure_diff_frontier (s : set α) : closure s \ frontier s = interior s := by rw [frontier, diff_diff_right_self, inter_eq_self_of_subset_right interior_subset_closure] @[simp] lemma self_diff_frontier (s : set α) : s \ frontier s = interior s := by rw [frontier, diff_diff_right, diff_eq_empty.2 subset_closure, inter_eq_self_of_subset_right interior_subset, empty_union] lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _ lemma is_closed.frontier_subset (hs : is_closed s) : frontier s ⊆ s := frontier_subset_closure.trans hs.closure_eq.subset lemma frontier_closure_subset {s : set α} : frontier (closure s) ⊆ frontier s := diff_subset_diff closure_closure.subset $ interior_mono subset_closure lemma frontier_interior_subset {s : set α} : frontier (interior s) ⊆ frontier s := diff_subset_diff (closure_mono interior_subset) interior_interior.symm.subset /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier] @[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm lemma disjoint.frontier_left (ht : is_open t) (hd : disjoint s t) : disjoint (frontier s) t := subset_compl_iff_disjoint_right.1 $ frontier_subset_closure.trans $ closure_minimal (disjoint_left.1 hd) $ is_closed_compl_iff.2 ht lemma disjoint.frontier_right (hs : is_open s) (hd : disjoint s t) : disjoint s (frontier t) := (hd.symm.frontier_left hs).symm lemma frontier_eq_inter_compl_interior {s : set α} : frontier s = (interior s)ᶜ ∩ (interior (sᶜ))ᶜ := by { rw [←frontier_compl, ←closure_compl], refl } lemma compl_frontier_eq_union_interior {s : set α} : (frontier s)ᶜ = interior s ∪ interior sᶜ := begin rw frontier_eq_inter_compl_interior, simp only [compl_inter, compl_compl], end /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space localized "notation `𝓝[≠] ` x:100 := nhds_within x {x}ᶜ" in topological_space localized "notation `𝓝[≥] ` x:100 := nhds_within x (set.Ici x)" in topological_space localized "notation `𝓝[≤] ` x:100 := nhds_within x (set.Iic x)" in topological_space localized "notation `𝓝[>] ` x:100 := nhds_within x (set.Ioi x)" in topological_space localized "notation `𝓝[<] ` x:100 := nhds_within x (set.Iio x)" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds lemma nhds_def' (a : α) : 𝓝 a = ⨅ (s : set α) (hs : is_open s) (ha : a ∈ s), 𝓟 s := by simp only [nhds_def, mem_set_of_eq, and_comm (a ∈ _), infi_and] /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ s, s) := begin rw nhds_def, exact has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end lemma nhds_basis_closeds (a : α) : (𝓝 a).has_basis (λ s : set α, a ∉ s ∧ is_closed s) compl := ⟨λ t, (nhds_basis_opens a).mem_iff.trans $ compl_surjective.exists.trans $ by simp only [is_open_compl_iff, mem_compl_iff]⟩ /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃ t ⊆ s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_mem_nhds h lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.mem_nhds_iff {a : α} {s : set α} (hs : is_open s) : s ∈ 𝓝 a ↔ a ∈ s := ⟨mem_of_mem_nhds, λ ha, mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩⟩ lemma is_closed.compl_mem_nhds {a : α} {s : set α} (hs : is_closed s) (ha : a ∉ s) : sᶜ ∈ 𝓝 a := hs.is_open_compl.mem_nhds (mem_compl ha) lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := is_open.mem_nhds hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, exact and.congr_left_iff.2 is_open.mem_nhds_iff end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := begin have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx), choose! Z hZ hZU using this, choose hZmem hZo using hZ, exact ⟨⋃ x ∈ s, Z x, λ x hx, mem_bUnion hx (hZmem x hx), is_open_bUnion hZo, Union₂_subset hZU⟩ end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma eventually_mem_nhds {s : set α} {a : α} : (∀ᶠ x in 𝓝 a, s ∈ 𝓝 x) ↔ s ∈ 𝓝 a := eventually_eventually_nhds @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_at_top_nhds [nonempty β] [semilattice_sup β] {f : β → α} {a : α} : (tendsto f at_top (𝓝 a)) ↔ ∀ U : set α, a ∈ U → is_open U → ∃ N, ∀ n, N ≤ n → f n ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens a)).trans $ by simp only [and_imp, exists_prop, true_and, mem_Ici, ge_iff_le] lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem' $ assume _, ha lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure.2 $ mem_of_mem_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [partial_order α] [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α} {pF : ιF → Prop} {sF : ιF → set α} {F : filter α} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set α} {a : α} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_of_superset h interior_subset, λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma is_open_singleton_iff_nhds_eq_pure {α : Type*} [topological_space α] (a : α) : is_open ({a} : set α) ↔ 𝓝 a = pure a := begin split, { intros h, apply le_antisymm _ (pure_le_nhds a), rw le_pure_iff, exact h.mem_nhds (mem_singleton a) }, { intros h, simp [is_open_iff_nhds, h] } end lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ ne_bot (𝓝[s] x) := mem_closure_iff_cluster_pt /-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole space. -/ lemma dense_compl_singleton (x : α) [ne_bot (𝓝[≠] x)] : dense ({x}ᶜ : set α) := begin intro y, unfreezingI { rcases eq_or_ne y x with rfl|hne }, { rwa mem_closure_iff_nhds_within_ne_bot }, { exact subset_closure hne } end /-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole space. -/ @[simp] lemma closure_compl_singleton (x : α) [ne_bot (𝓝[≠] x)] : closure {x}ᶜ = (univ : set α) := (dense_compl_singleton x).closure_eq /-- If `x` is not an isolated point of a topological space, then the interior of `{x}` is empty. -/ @[simp] lemma interior_singleton (x : α) [ne_bot (𝓝[≠] x)] : interior {x} = (∅ : set α) := interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x) lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis' {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := begin rintro a ⟨hs, ht⟩, have : s ∈ 𝓝 a := is_open.mem_nhds h hs, rw mem_closure_iff_nhds_ne_bot at ht ⊢, rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)], end lemma closure_inter_open' {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm] using closure_inter_open h lemma dense.open_subset_closure_inter {s t : set α} (hs : dense s) (ht : is_open t) : t ⊆ closure (t ∩ s) := calc t = t ∩ closure s : by rw [hs.closure_eq, inter_univ] ... ⊆ closure (t ∩ s) : closure_inter_open ht lemma mem_closure_of_mem_closure_union {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ := begin rw mem_closure_iff_nhds_ne_bot at *, rwa ← calc 𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal ... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : inf_sup_left ... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot.mpr h₁ ... = 𝓝 x ⊓ principal s₂ : bot_sup_eq end /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩ lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ closure s := filter.frequently.mem_closure $ hf.frequently h lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := mem_closure_of_frequently_of_tendsto h.frequently hf /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, {i | (f i ∩ t).nonempty}.finite lemma locally_finite.point_finite {f : β → set α} (hf : locally_finite f) (x : α) : {b | x ∈ f b}.finite := let ⟨t, hxt, ht⟩ := hf x in ht.subset $ λ b hb, ⟨x, hb, mem_of_mem_nhds hxt⟩ lemma locally_finite_of_finite [finite β] (f : β → set α) : locally_finite f := assume x, ⟨univ, univ_mem, to_finite _⟩ lemma locally_finite.subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma locally_finite.comp_injective {ι} {f : β → set α} {g : ι → β} (hf : locally_finite f) (hg : function.injective g) : locally_finite (f ∘ g) := λ x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩ lemma locally_finite.eventually_finite {f : β → set α} (hf : locally_finite f) (x : α) : ∀ᶠ s in (𝓝 x).small_sets, {i | (f i ∩ s).nonempty}.finite := eventually_small_sets.2 $ let ⟨s, hsx, hs⟩ := hf x in ⟨s, hsx, λ t hts, hs.subset $ λ i hi, hi.out.mono $ inter_subset_inter_right _ hts⟩ lemma locally_finite.sum_elim {γ} {f : β → set α} {g : γ → set α} (hf : locally_finite f) (hg : locally_finite g) : locally_finite (sum.elim f g) := begin intro x, obtain ⟨s, hsx, hsf, hsg⟩ : ∃ s, s ∈ 𝓝 x ∧ {i | (f i ∩ s).nonempty}.finite ∧ {j | (g j ∩ s).nonempty}.finite, from ((𝓝 x).frequently_small_sets_mem.and_eventually ((hf.eventually_finite x).and (hg.eventually_finite x))).exists, refine ⟨s, hsx, _⟩, convert (hsf.image sum.inl).union (hsg.image sum.inr) using 1, ext (i|j); simp end lemma locally_finite.closure {f : β → set α} (hf : locally_finite f) : locally_finite (λ i, closure (f i)) := begin intro x, rcases hf x with ⟨s, hsx, hsf⟩, refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ λ i hi, _⟩, exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono (inter_subset_inter_right _ interior_subset) end lemma locally_finite.is_closed_Union {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := begin simp only [← is_open_compl_iff, compl_Union, is_open_iff_mem_nhds, mem_Inter], intros a ha, replace ha : ∀ i, (f i)ᶜ ∈ 𝓝 a := λ i, (h₂ i).is_open_compl.mem_nhds (ha i), rcases h₁ a with ⟨t, h_nhds, h_fin⟩, have : t ∩ (⋂ i ∈ {i | (f i ∩ t).nonempty}, (f i)ᶜ) ∈ 𝓝 a, from inter_mem h_nhds ((bInter_mem h_fin).2 (λ i _, ha i)), filter_upwards [this], simp only [mem_inter_eq, mem_Inter], rintros b ⟨hbt, hn⟩ i hfb, exact hn i ⟨b, hfb, hbt⟩ hfb, end lemma locally_finite.closure_Union {f : β → set α} (h : locally_finite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := subset.antisymm (closure_minimal (Union_mono $ λ _, subset_closure) $ h.closure.is_closed_Union $ λ _, is_closed_closure) (Union_subset $ λ i, closure_mono $ subset_Union _ _) end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h lemma continuous.congr {f g : α → β} (h : continuous f) (h' : ∀ x, f x = g x) : continuous g := by { convert h, ext, rw h' } /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_def {f : α → β} {x : α} : continuous_at f x ↔ ∀ A ∈ 𝓝 (f x), f ⁻¹' A ∈ 𝓝 x := iff.rfl lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} : f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) := by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ /-- See also `interior_preimage_subset_preimage_interior`. -/ lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, is_open.mem_nhds hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := tendsto_const_nhds lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma filter.eventually_eq.continuous_at {x : α} {f : α → β} {y : β} (h : f =ᶠ[𝓝 x] (λ _, y)) : continuous_at f x := (continuous_at_congr h).2 tendsto_const_nhds lemma continuous_of_const {f : α → β} (h : ∀ x y, f x = f y) : continuous f := continuous_iff_continuous_at.mpr $ λ x, filter.eventually_eq.continuous_at $ eventually_of_forall (λ y, h y x) lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma locally_finite.preimage_continuous {ι} {f : ι → set α} {g : β → α} (hf : locally_finite f) (hg : continuous g) : locally_finite (λ i, g ⁻¹' (f i)) := λ x, let ⟨s, hsx, hs⟩ := hf (g x) in ⟨g ⁻¹' s, hg.continuous_at hsx, hs.subset $ λ i ⟨y, hy⟩, ⟨g y, hy⟩⟩ lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma mem_closure_image {f : α → β} {x : α} {s : set α} (hf : continuous_at f x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_frequently_of_tendsto ((mem_closure_iff_frequently.1 hx).mono (λ x, mem_image_of_mem _)) hf lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] lemma continuous.closure_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : closure (f ⁻¹' t) ⊆ f ⁻¹' (closure t) := begin rw ← (is_closed_closure.preimage hf).closure_eq, exact closure_mono (preimage_mono subset_closure), end lemma continuous.frontier_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : frontier (f ⁻¹' t) ⊆ f ⁻¹' (frontier t) := diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf) /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) : closure s ⊆ f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma dense.dense_range_coe {s : set α} (h : dense s) : dense_range (coe : s → α) := by simpa only [dense_range, subtype.range_coe_subtype] lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the preimage of `s` under `f` is dense in `s`. -/ lemma dense_range.subset_closure_image_preimage_of_is_open (hf : dense_range f) {s : set β} (hs : is_open s) : s ⊆ closure (f '' (f ⁻¹' s)) := by { rw image_preimage_eq_inter_range, exact hf.open_subset_closure_inter hs } /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ lemma dense_range.exists_mem_open (hf : dense_range f) {s : set β} (ho : is_open s) (hs : s.nonempty) : ∃ a, f a ∈ s := exists_range_iff.1 $ hf.exists_mem_open ho hs lemma dense_range.mem_nhds {f : κ → β} (h : dense_range f) {b : β} {U : set β} (U_in : U ∈ 𝓝 b) : ∃ a, f a ∈ U := let ⟨a, ha⟩ := h.exists_mem_open is_open_interior ⟨b, mem_interior_iff_mem_nhds.2 U_in⟩ in ⟨a, interior_subset ha⟩ end dense_range end continuous /-- The library contains many lemmas stating that functions/operations are continuous. There are many ways to formulate the continuity of operations. Some are more convenient than others. Note: for the most part this note also applies to other properties (`measurable`, `differentiable`, `continuous_on`, ...). ### The traditional way As an example, let's look at addition `(+) : M → M → M`. We can state that this is continuous in different definitionally equal ways (omitting some typing information) * `continuous (λ p, p.1 + p.2)`; * `continuous (function.uncurry (+))`; * `continuous ↿(+)`. (`↿` is notation for recursively uncurrying a function) However, lemmas with this conclusion are not nice to use in practice because 1. They confuse the elaborator. The following two examples fail, because of limitations in the elaboration process. ``` variables {M : Type*} [has_add M] [topological_space M] [has_continuous_add M] example : continuous (λ x : M, x + x) := continuous_add.comp _ example : continuous (λ x : M, x + x) := continuous_add.comp (continuous_id.prod_mk continuous_id) ``` The second is a valid proof, which is accepted if you write it as `continuous_add.comp (continuous_id.prod_mk continuous_id : _)` 2. If the operation has more than 2 arguments, they are impractical to use, because in your application the arguments in the domain might be in a different order or associated differently. ### The convenient way A much more convenient way to write continuity lemmas is like `continuous.add`: ``` continuous.add {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λ x, f x + g x) ``` The conclusion can be `continuous (f + g)`, which is definitionally equal. This has the following advantages * It supports projection notation, so is shorter to write. * `continuous.add _ _` is recognized correctly by the elaborator and gives useful new goals. * It works generally, since the domain is a variable. As an example for an unary operation, we have `continuous.neg`. ``` continuous.neg {f : α → G} (hf : continuous f) : continuous (λ x, -f x) ``` For unary functions, the elaborator is not confused when applying the traditional lemma (like `continuous_neg`), but it's still convenient to have the short version available (compare `hf.neg.neg.neg` with `continuous_neg.comp $ continuous_neg.comp $ continuous_neg.comp hf`). As a harder example, consider an operation of the following type: ``` def strans {x : F} (γ γ' : path x x) (t₀ : I) : path x x ``` The precise definition is not important, only its type. The correct continuity principle for this operation is something like this: ``` {f : X → F} {γ γ' : ∀ x, path (f x) (f x)} {t₀ s : X → I} (hγ : continuous ↿γ) (hγ' : continuous ↿γ') (ht : continuous t₀) (hs : continuous s) : continuous (λ x, strans (γ x) (γ' x) (t x) (s x)) ``` Note that *all* arguments of `strans` are indexed over `X`, even the basepoint `x`, and the last argument `s` that arises since `path x x` has a coercion to `I → F`. The paths `γ` and `γ'` (which are unary functions from `I`) become binary functions in the continuity lemma. ### Summary * Make sure that your continuity lemmas are stated in the most general way, and in a convenient form. That means that: - The conclusion has a variable `X` as domain (not something like `Y × Z`); - Wherever possible, all point arguments `c : Y` are replaced by functions `c : X → Y`; - All `n`-ary function arguments are replaced by `n+1`-ary functions (`f : Y → Z` becomes `f : X → Y → Z`); - All (relevant) arguments have continuity assumptions, and perhaps there are additional assumptions needed to make the operation continuous; - The function in the conclusion is fully applied. * These remarks are mostly about the format of the *conclusion* of a continuity lemma. In assumptions it's fine to state that a function with more than 1 argument is continuous using `↿` or `function.uncurry`. ### Functions with discontinuities In some cases, you want to work with discontinuous functions, and in certain expressions they are still continuous. For example, consider the fractional part of a number, `fract : ℝ → ℝ`. In this case, you want to add conditions to when a function involving `fract` is continuous, so you get something like this: (assumption `hf` could be weakened, but the important thing is the shape of the conclusion) ``` lemma continuous_on.comp_fract {X Y : Type*} [topological_space X] [topological_space Y] {f : X → ℝ → Y} {g : X → ℝ} (hf : continuous ↿f) (hg : continuous g) (h : ∀ s, f s 0 = f s 1) : continuous (λ x, f x (fract (g x))) ``` With `continuous_at` you can be even more precise about what to prove in case of discontinuities, see e.g. `continuous_at.comp_div_cases`. -/ library_note "continuity lemma statement"
a090bb2a16e4878f8c2598f08123a5405102224c
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/pi_tensor_product.lean
9e0ef6666844bbd98dbbc95348574f86314344b2
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
24,927
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis, Eric Wieser -/ import group_theory.congruence import linear_algebra.multilinear.tensor_product /-! # Tensor product of an indexed family of modules over commutative semirings We define the tensor product of an indexed family `s : ι → Type*` of modules over commutative semirings. We denote this space by `⨂[R] i, s i` and define it as `free_add_monoid (R × Π i, s i)` quotiented by the appropriate equivalence relation. The treatment follows very closely that of the binary tensor product in `linear_algebra/tensor_product.lean`. ## Main definitions * `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. * `tprod R f` with `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`. This is bundled as a multilinear map from `Π i, s i` to `⨂[R] i, s i`. * `lift_add_hom` constructs an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. * `lift φ` with `φ : multilinear_map R s E` is the corresponding linear map `(⨂[R] i, s i) →ₗ[R] E`. This is bundled as a linear equivalence. * `pi_tensor_product.reindex e` re-indexes the components of `⨂[R] i : ι, M` along `e : ι ≃ ι₂`. * `pi_tensor_product.tmul_equiv` equivalence between a `tensor_product` of `pi_tensor_product`s and a single `pi_tensor_product`. ## Notations * `⨂[R] i, s i` is defined as localized notation in locale `tensor_product` * `⨂ₜ[R] i, f i` with `f : Π i, f i` is defined globally as the tensor product of all the `f i`'s. ## Implementation notes * We define it via `free_add_monoid (R × Π i, s i)` with the `R` representing a "hidden" tensor factor, rather than `free_add_monoid (Π i, s i)` to ensure that, if `ι` is an empty type, the space is isomorphic to the base ring `R`. * We have not restricted the index type `ι` to be a `fintype`, as nothing we do here strictly requires it. However, problems may arise in the case where `ι` is infinite; use at your own caution. * Instead of requiring `decidable_eq ι` as an argument to `pi_tensor_product` itself, we include it as an argument in the constructors of the relation. A decidability isntance still has to come from somewhere due to the use of `function.update`, but this hides it from the downstream user. See the implementation notes for `multilinear_map` for an extended discussion of this choice. ## TODO * Define tensor powers, symmetric subspace, etc. * API for the various ways `ι` can be split into subsets; connect this with the binary tensor product. * Include connection with holors. * Port more of the API from the binary tensor product over to this case. ## Tags multilinear, tensor, tensor product -/ open function section semiring variables {ι ι₂ ι₃ : Type*} variables {R : Type*} [comm_semiring R] variables {R₁ R₂ : Type*} variables {s : ι → Type*} [∀ i, add_comm_monoid (s i)] [∀ i, module R (s i)] variables {M : Type*} [add_comm_monoid M] [module R M] variables {E : Type*} [add_comm_monoid E] [module R E] variables {F : Type*} [add_comm_monoid F] namespace pi_tensor_product include R variables (R) (s) /-- The relation on `free_add_monoid (R × Π i, s i)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (R × Π i, s i) → free_add_monoid (R × Π i, s i) → Prop | of_zero : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), eqv (free_add_monoid.of (r, f)) 0 | of_zero_scalar : ∀ (f : Π i, s i), eqv (free_add_monoid.of (0, f)) 0 | of_add : ∀ (inst : decidable_eq ι) (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), eqv (free_add_monoid.of (r, update f i m₁) + free_add_monoid.of (r, update f i m₂)) (free_add_monoid.of (r, update f i (m₁ + m₂))) | of_add_scalar : ∀ (r r' : R) (f : Π i, s i), eqv (free_add_monoid.of (r, f) + free_add_monoid.of (r', f)) (free_add_monoid.of (r + r', f)) | of_smul : ∀ (inst : decidable_eq ι) (r : R) (f : Π i, s i) (i : ι) (r' : R), eqv (free_add_monoid.of (r, update f i (r' • (f i)))) (free_add_monoid.of (r' * r, f)) | add_comm : ∀ x y, eqv (x + y) (y + x) end pi_tensor_product variables (R) (s) /-- `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. -/ def pi_tensor_product : Type* := (add_con_gen (pi_tensor_product.eqv R s)).quotient variables {R} /- This enables the notation `⨂[R] i : ι, s i` for the pi tensor product, given `s : ι → Type*`. -/ localized "notation (name := pi_tensor_product) `⨂[`:100 R `] ` binders `, ` r:(scoped:67 f, pi_tensor_product R f) := r" in tensor_product open_locale tensor_product namespace pi_tensor_product section module instance : add_comm_monoid (⨂[R] i, s i) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (pi_tensor_product.eqv R s)).add_monoid } instance : inhabited (⨂[R] i, s i) := ⟨0⟩ variables (R) {s} /-- `tprod_coeff R r f` with `r : R` and `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`, multiplied by the coefficient `r`. Note that this is meant as an auxiliary definition for this file alone, and that one should use `tprod` defined below for most purposes. -/ def tprod_coeff (r : R) (f : Π i, s i) : ⨂[R] i, s i := add_con.mk' _ $ free_add_monoid.of (r, f) variables {R} lemma zero_tprod_coeff (f : Π i, s i) : tprod_coeff R 0 f = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_scalar _ lemma zero_tprod_coeff' (z : R) (f : Π i, s i) (i : ι) (hf: f i = 0) : tprod_coeff R z f = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero _ _ i hf lemma add_tprod_coeff [decidable_eq ι] (z : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i) : tprod_coeff R z (update f i m₁) + tprod_coeff R z (update f i m₂) = tprod_coeff R z (update f i (m₁ + m₂)) := quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add _ z f i m₁ m₂) lemma add_tprod_coeff' (z₁ z₂ : R) (f : Π i, s i) : tprod_coeff R z₁ f + tprod_coeff R z₂ f = tprod_coeff R (z₁ + z₂) f := quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add_scalar z₁ z₂ f) lemma smul_tprod_coeff_aux [decidable_eq ι] (z : R) (f : Π i, s i) (i : ι) (r : R) : tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r * z) f := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _ _ _ lemma smul_tprod_coeff [decidable_eq ι] (z : R) (f : Π i, s i) (i : ι) (r : R₁) [has_smul R₁ R] [is_scalar_tower R₁ R R] [has_smul R₁ (s i)] [is_scalar_tower R₁ R (s i)] : tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r • z) f := begin have h₁ : r • z = (r • (1 : R)) * z := by rw [smul_mul_assoc, one_mul], have h₂ : r • (f i) = (r • (1 : R)) • f i := (smul_one_smul _ _ _).symm, rw [h₁, h₂], exact smul_tprod_coeff_aux z f i _, end /-- Construct an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. -/ def lift_add_hom (φ : (R × Π i, s i) → F) (C0 : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), φ (r, f) = 0) (C0' : ∀ (f : Π i, s i), φ (0, f) = 0) (C_add : ∀ [decidable_eq ι] (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), by exactI φ (r, update f i m₁) + φ (r, update f i m₂) = φ (r, update f i (m₁ + m₂))) (C_add_scalar : ∀ (r r' : R) (f : Π i, s i), φ (r , f) + φ (r', f) = φ (r + r', f)) (C_smul : ∀ [decidable_eq ι] (r : R) (f : Π i, s i) (i : ι) (r' : R), by exactI φ (r, update f i (r' • (f i))) = φ (r' * r, f)) : (⨂[R] i, s i) →+ F := (add_con_gen (pi_tensor_product.eqv R s)).lift (free_add_monoid.lift φ) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero r' f i hf) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C0 r' f i hf] | _, _, (eqv.of_zero_scalar f) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C0'] | _, _, (eqv.of_add inst z f i m₁ m₂) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, @C_add inst] | _, _, (eqv.of_add_scalar z₁ z₂ f) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_add_scalar] | _, _, (eqv.of_smul inst z f i r') := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, @C_smul inst] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end @[elab_as_eliminator] protected theorem induction_on' {C : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (C1 : ∀ {r : R} {f : Π i, s i}, C (tprod_coeff R r f)) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := begin have C0 : C 0, { have h₁ := @C1 0 0, rwa [zero_tprod_coeff] at h₁ }, refine add_con.induction_on z (λ x, free_add_monoid.rec_on x C0 _), simp_rw add_con.coe_add, refine λ f y ih, Cp _ ih, convert @C1 f.1 f.2, simp only [prod.mk.eta], end section distrib_mul_action variables [monoid R₁] [distrib_mul_action R₁ R] [smul_comm_class R₁ R R] variables [monoid R₂] [distrib_mul_action R₂ R] [smul_comm_class R₂ R R] -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance has_smul' : has_smul R₁ (⨂[R] i, s i) := ⟨λ r, lift_add_hom (λ f : R × Π i, s i, tprod_coeff R (r • f.1) f.2) (λ r' f i hf, by simp_rw [zero_tprod_coeff' _ f i hf]) (λ f, by simp [zero_tprod_coeff]) (λ r' f i m₁ m₂, by simp [add_tprod_coeff]) (λ r' r'' f, by simp [add_tprod_coeff', mul_add]) (λ z f i r', by simp [smul_tprod_coeff, mul_smul_comm])⟩ instance : has_smul R (⨂[R] i, s i) := pi_tensor_product.has_smul' lemma smul_tprod_coeff' (r : R₁) (z : R) (f : Π i, s i) : r • (tprod_coeff R z f) = tprod_coeff R (r • z) f := rfl protected theorem smul_add (r : R₁) (x y : ⨂[R] i, s i) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ instance distrib_mul_action' : distrib_mul_action R₁ (⨂[R] i, s i) := { smul := (•), smul_add := λ r x y, add_monoid_hom.map_add _ _ _, mul_smul := λ r r' x, pi_tensor_product.induction_on' x (λ r'' f, by simp [smul_tprod_coeff', smul_smul]) (λ x y ihx ihy, by simp_rw [pi_tensor_product.smul_add, ihx, ihy]), one_smul := λ x, pi_tensor_product.induction_on' x (λ f, by simp [smul_tprod_coeff' _ _]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy]), smul_zero := λ r, add_monoid_hom.map_zero _ } instance smul_comm_class' [smul_comm_class R₁ R₂ R] : smul_comm_class R₁ R₂ (⨂[R] i, s i) := ⟨λ r' r'' x, pi_tensor_product.induction_on' x (λ xr xf, by simp only [smul_tprod_coeff', smul_comm]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy])⟩ instance is_scalar_tower' [has_smul R₁ R₂] [is_scalar_tower R₁ R₂ R] : is_scalar_tower R₁ R₂ (⨂[R] i, s i) := ⟨λ r' r'' x, pi_tensor_product.induction_on' x (λ xr xf, by simp only [smul_tprod_coeff', smul_assoc]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy])⟩ end distrib_mul_action -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance module' [semiring R₁] [module R₁ R] [smul_comm_class R₁ R R] : module R₁ (⨂[R] i, s i) := { smul := (•), add_smul := λ r r' x, pi_tensor_product.induction_on' x (λ r f, by simp [smul_tprod_coeff' _ _, add_smul, add_tprod_coeff']) (λ x y ihx ihy, by simp [pi_tensor_product.smul_add, ihx, ihy, add_add_add_comm]), zero_smul := λ x, pi_tensor_product.induction_on' x (λ r f, by { simp_rw [smul_tprod_coeff' _ _, zero_smul], exact zero_tprod_coeff _ }) (λ x y ihx ihy, by rw [pi_tensor_product.smul_add, ihx, ihy, add_zero]), ..pi_tensor_product.distrib_mul_action' } -- shortcut instances instance : module R (⨂[R] i, s i) := pi_tensor_product.module' instance : smul_comm_class R R (⨂[R] i, s i) := pi_tensor_product.smul_comm_class' instance : is_scalar_tower R R (⨂[R] i, s i) := pi_tensor_product.is_scalar_tower' variables {R} variables (R) /-- The canonical `multilinear_map R s (⨂[R] i, s i)`. -/ def tprod : multilinear_map R s (⨂[R] i, s i) := { to_fun := tprod_coeff R 1, map_add' := λ _ f i x y, by exactI (add_tprod_coeff (1 : R) f i x y).symm, map_smul' := λ _ f i r x, by resetI; simp_rw [smul_tprod_coeff', ←smul_tprod_coeff (1 : R) _ i, update_idem, update_same] } variables {R} notation `⨂ₜ[`:100 R`] ` binders `, ` r:(scoped:67 f, tprod R f) := r @[simp] lemma tprod_coeff_eq_smul_tprod (z : R) (f : Π i, s i) : tprod_coeff R z f = z • tprod R f := begin have : z = z • (1 : R) := by simp only [mul_one, algebra.id.smul_eq_mul], conv_lhs { rw this }, rw ←smul_tprod_coeff', refl, end @[elab_as_eliminator] protected theorem induction_on {C : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (C1 : ∀ {r : R} {f : Π i, s i}, C (r • (tprod R f))) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := begin simp_rw ←tprod_coeff_eq_smul_tprod at C1, exact pi_tensor_product.induction_on' z @C1 @Cp, end @[ext] theorem ext {φ₁ φ₂ : (⨂[R] i, s i) →ₗ[R] E} (H : φ₁.comp_multilinear_map (tprod R) = φ₂.comp_multilinear_map (tprod R)) : φ₁ = φ₂ := begin refine linear_map.ext _, refine λ z, (pi_tensor_product.induction_on' z _ (λ x y hx hy, by rw [φ₁.map_add, φ₂.map_add, hx, hy])), { intros r f, rw [tprod_coeff_eq_smul_tprod, φ₁.map_smul, φ₂.map_smul], apply _root_.congr_arg, exact multilinear_map.congr_fun H f } end end module section multilinear open multilinear_map variables {s} /-- Auxiliary function to constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear map R s E` with the property that its composition with the canonical `multilinear_map R s (⨂[R] i, s i)` is the given multilinear map. -/ def lift_aux (φ : multilinear_map R s E) : (⨂[R] i, s i) →+ E := lift_add_hom (λ (p : R × Π i, s i), p.1 • (φ p.2)) (λ z f i hf, by rw [map_coord_zero φ i hf, smul_zero]) (λ f, by rw [zero_smul]) (λ _ z f i m₁ m₂, by { resetI, rw [←smul_add, φ.map_add] }) (λ z₁ z₂ f, by rw [←add_smul]) (λ _ z f i r, by { resetI, simp [φ.map_smul, smul_smul, mul_comm] }) lemma lift_aux_tprod (φ : multilinear_map R s E) (f : Π i, s i) : lift_aux φ (tprod R f) = φ f := by simp only [lift_aux, lift_add_hom, tprod, multilinear_map.coe_mk, tprod_coeff, free_add_monoid.lift_eval_of, one_smul, add_con.lift_mk'] lemma lift_aux_tprod_coeff (φ : multilinear_map R s E) (z : R) (f : Π i, s i) : lift_aux φ (tprod_coeff R z f) = z • φ f := by simp [lift_aux, lift_add_hom, tprod_coeff, free_add_monoid.lift_eval_of] lemma lift_aux.smul {φ : multilinear_map R s E} (r : R) (x : ⨂[R] i, s i) : lift_aux φ (r • x) = r • lift_aux φ x := begin refine pi_tensor_product.induction_on' x _ _, { intros z f, rw [smul_tprod_coeff' r z f, lift_aux_tprod_coeff, lift_aux_tprod_coeff, smul_assoc] }, { intros z y ihz ihy, rw [smul_add, (lift_aux φ).map_add, ihz, ihy, (lift_aux φ).map_add, smul_add] } end /-- Constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear_map R s E` with the property that its composition with the canonical `multilinear_map R s E` is the given multilinear map `φ`. -/ def lift : (multilinear_map R s E) ≃ₗ[R] ((⨂[R] i, s i) →ₗ[R] E) := { to_fun := λ φ, { map_smul' := lift_aux.smul, .. lift_aux φ }, inv_fun := λ φ', φ'.comp_multilinear_map (tprod R), left_inv := λ φ, by { ext, simp [lift_aux_tprod, linear_map.comp_multilinear_map] }, right_inv := λ φ, by { ext, simp [lift_aux_tprod] }, map_add' := λ φ₁ φ₂, by { ext, simp [lift_aux_tprod] }, map_smul' := λ r φ₂, by { ext, simp [lift_aux_tprod] } } variables {φ : multilinear_map R s E} @[simp] lemma lift.tprod (f : Π i, s i) : lift φ (tprod R f) = φ f := lift_aux_tprod φ f theorem lift.unique' {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : φ'.comp_multilinear_map (tprod R) = φ) : φ' = lift φ := ext $ H.symm ▸ (lift.symm_apply_apply φ).symm theorem lift.unique {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : ∀ f, φ' (tprod R f) = φ f) : φ' = lift φ := lift.unique' (multilinear_map.ext H) @[simp] theorem lift_symm (φ' : (⨂[R] i, s i) →ₗ[R] E) : lift.symm φ' = φ'.comp_multilinear_map (tprod R) := rfl @[simp] theorem lift_tprod : lift (tprod R : multilinear_map R s _) = linear_map.id := eq.symm $ lift.unique' rfl section variables (R M) /-- Re-index the components of the tensor power by `e`. For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components. -/ def reindex (e : ι ≃ ι₂) : ⨂[R] i : ι, M ≃ₗ[R] ⨂[R] i : ι₂, M := linear_equiv.of_linear (lift (dom_dom_congr e.symm (tprod R : multilinear_map R _ (⨂[R] i : ι₂, M)))) (lift (dom_dom_congr e (tprod R : multilinear_map R _ (⨂[R] i : ι, M)))) (by { ext, simp only [linear_map.comp_apply, linear_map.id_apply, lift_tprod, linear_map.comp_multilinear_map_apply, lift.tprod, dom_dom_congr_apply, equiv.apply_symm_apply] }) (by { ext, simp only [linear_map.comp_apply, linear_map.id_apply, lift_tprod, linear_map.comp_multilinear_map_apply, lift.tprod, dom_dom_congr_apply, equiv.symm_apply_apply] }) end @[simp] lemma reindex_tprod (e : ι ≃ ι₂) (f : Π i, M) : reindex R M e (tprod R f) = tprod R (λ i, f (e.symm i)) := lift_aux_tprod _ f @[simp] lemma reindex_comp_tprod (e : ι ≃ ι₂) : (reindex R M e : ⨂[R] i : ι, M →ₗ[R] ⨂[R] i : ι₂, M).comp_multilinear_map (tprod R) = (tprod R : multilinear_map R (λ i, M) _).dom_dom_congr e.symm := multilinear_map.ext $ reindex_tprod e @[simp] lemma lift_comp_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _ : ι₂, M) E) : (lift φ) ∘ₗ ↑(reindex R M e) = lift (φ.dom_dom_congr e.symm) := by { ext, simp, } @[simp] lemma lift_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _, M) E) (x : ⨂[R] i, M) : lift φ (reindex R M e x) = lift (φ.dom_dom_congr e.symm) x := linear_map.congr_fun (lift_comp_reindex e φ) x @[simp] lemma reindex_trans (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) : (reindex R M e).trans (reindex R M e') = reindex R M (e.trans e') := begin apply linear_equiv.to_linear_map_injective, ext f, simp only [linear_equiv.trans_apply, linear_equiv.coe_coe, reindex_tprod, linear_map.coe_comp_multilinear_map, function.comp_app, multilinear_map.dom_dom_congr_apply, reindex_comp_tprod], congr, end @[simp] lemma reindex_reindex (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) (x : ⨂[R] i, M) : reindex R M e' (reindex R M e x) = reindex R M (e.trans e') x := linear_equiv.congr_fun (reindex_trans e e' : _ = reindex R M (e.trans e')) x @[simp] lemma reindex_symm (e : ι ≃ ι₂) : (reindex R M e).symm = reindex R M e.symm := rfl @[simp] lemma reindex_refl : reindex R M (equiv.refl ι) = linear_equiv.refl R _ := begin apply linear_equiv.to_linear_map_injective, ext1, rw [reindex_comp_tprod, linear_equiv.refl_to_linear_map, equiv.refl_symm], refl, end variables (ι) /-- The tensor product over an empty index type `ι` is isomorphic to the base ring. -/ @[simps symm_apply] def is_empty_equiv [is_empty ι] : ⨂[R] i : ι, M ≃ₗ[R] R := { to_fun := lift (const_of_is_empty R _ 1), inv_fun := λ r, r • tprod R (@is_empty_elim _ _ _), left_inv := λ x, by { apply x.induction_on, { intros r f, have := subsingleton.elim f is_empty_elim, simp [this], }, { simp only, intros x y hx hy, simp [add_smul, hx, hy] }}, right_inv := λ t, by simp only [mul_one, algebra.id.smul_eq_mul, const_of_is_empty_apply, linear_map.map_smul, pi_tensor_product.lift.tprod], map_add' := linear_map.map_add _, map_smul' := linear_map.map_smul _, } @[simp] lemma is_empty_equiv_apply_tprod [is_empty ι] (f : ι → M) : is_empty_equiv ι (tprod R f) = 1 := lift.tprod _ variables {ι} /-- The tensor product over an single index is isomorphic to the module -/ @[simps symm_apply] def subsingleton_equiv [subsingleton ι] (i₀ : ι) : ⨂[R] i : ι, M ≃ₗ[R] M := { to_fun := lift (multilinear_map.of_subsingleton R M i₀), inv_fun := λ m, tprod R (λ v, m), left_inv := λ x, by { dsimp only, have : ∀ (f : ι → M) (z : M), (λ i : ι, z) = update f i₀ z, { intros f z, ext i, rw [subsingleton.elim i i₀, function.update_same] }, apply x.induction_on, { intros r f, simp only [linear_map.map_smul, lift.tprod, of_subsingleton_apply, function.eval, this f, multilinear_map.map_smul, update_eq_self], }, { intros x y hx hy, simp only [multilinear_map.map_add, this 0 (_ + _), linear_map.map_add, ←this 0 (lift _ _), hx, hy] } }, right_inv := λ t, by simp only [of_subsingleton_apply, lift.tprod, function.eval_apply], map_add' := linear_map.map_add _, map_smul' := linear_map.map_smul _, } @[simp] lemma subsingleton_equiv_apply_tprod [subsingleton ι] (i : ι) (f : ι → M) : subsingleton_equiv i (tprod R f) = f i := lift.tprod _ section tmul /-- Collapse a `tensor_product` of `pi_tensor_product`s. -/ private def tmul : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) →ₗ[R] ⨂[R] i : ι ⊕ ι₂, M := tensor_product.lift { to_fun := λ a, pi_tensor_product.lift $ pi_tensor_product.lift (multilinear_map.curry_sum_equiv R _ _ M _ (tprod R)) a, map_add' := λ a b, by simp only [linear_equiv.map_add, linear_map.map_add], map_smul' := λ r a, by simp only [linear_equiv.map_smul, linear_map.map_smul, ring_hom.id_apply], } private lemma tmul_apply (a : ι → M) (b : ι₂ → M) : tmul ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i := begin erw [tensor_product.lift.tmul, pi_tensor_product.lift.tprod, pi_tensor_product.lift.tprod], refl end /-- Expand `pi_tensor_product` into a `tensor_product` of two factors. -/ private def tmul_symm : ⨂[R] i : ι ⊕ ι₂, M →ₗ[R] (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) := -- by using tactic mode, we avoid the need for a lot of `@`s and `_`s pi_tensor_product.lift $ by apply multilinear_map.dom_coprod; [exact tprod R, exact tprod R] private lemma tmul_symm_apply (a : ι ⊕ ι₂ → M) : tmul_symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) := pi_tensor_product.lift.tprod _ variables (R M) local attribute [ext] tensor_product.ext /-- Equivalence between a `tensor_product` of `pi_tensor_product`s and a single `pi_tensor_product` indexed by a `sum` type. For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components. -/ def tmul_equiv : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) ≃ₗ[R] ⨂[R] i : ι ⊕ ι₂, M := linear_equiv.of_linear tmul tmul_symm (by { ext x, show tmul (tmul_symm (tprod R x)) = tprod R x, -- Speed up the call to `simp`. simp only [tmul_symm_apply, tmul_apply, sum.elim_comp_inl_inr], }) (by { ext x y, show tmul_symm (tmul (tprod R x ⊗ₜ[R] tprod R y)) = tprod R x ⊗ₜ[R] tprod R y, simp only [tmul_apply, tmul_symm_apply, sum.elim_inl, sum.elim_inr], }) @[simp] lemma tmul_equiv_apply (a : ι → M) (b : ι₂ → M) : tmul_equiv R M ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i := tmul_apply a b @[simp] lemma tmul_equiv_symm_apply (a : ι ⊕ ι₂ → M) : (tmul_equiv R M).symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) := tmul_symm_apply a end tmul end multilinear end pi_tensor_product end semiring section ring namespace pi_tensor_product open pi_tensor_product open_locale tensor_product variables {ι : Type*} {R : Type*} [comm_ring R] variables {s : ι → Type*} [∀ i, add_comm_group (s i)] [∀ i, module R (s i)] /- Unlike for the binary tensor product, we require `R` to be a `comm_ring` here, otherwise this is false in the case where `ι` is empty. -/ instance : add_comm_group (⨂[R] i, s i) := module.add_comm_monoid_to_add_comm_group R end pi_tensor_product end ring
80260aa3dba8ea635231e00fa8f34d729bda5f8c
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/playground/task_test.lean
06b85d2457c4a9581f23b378922af492120be6fe
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
494
lean
def g (x : Nat) : Nat := dbgTrace ("g: " ++ toString x) $ λ _, x + 1 def f1 (x : Nat) : Nat := dbgSleep 1000 $ λ _, dbgTrace ("f1: " ++ toString x) $ λ _, g (x + 1) def f2 (x : Nat) : Nat := dbgSleep 100 $ λ _, dbgTrace ("f2: " ++ toString x) $ λ _, g x def main (xs : List String) : IO UInt32 := let t1 := Task.mk $ (λ _, f1 xs.head.toNat) in let t2 := Task.mk $ (λ _, f2 xs.head.toNat) in dbgSleep 1000 $ λ _, IO.println (toString t1.get ++ " " ++ toString t2.get) *> pure 0
ef5067da2087aa25270acd3f827f135ce2270c87
7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a
/src/seul/tab.lean
c025782233d33c1ef9c01b695166f6660a0f6f3d
[]
no_license
jesse-michael-han/hanoi-lean-2019
ea2f0e04f81093373c48447065765a964ee82262
a5a9f368e394d563bfcc13e3773863924505b1ce
refs/heads/master
1,591,320,223,247
1,561,022,886,000
1,561,022,886,000
192,264,820
1
1
null
null
null
null
UTF-8
Lean
false
false
4,088
lean
/- Propositional tableaux prover from Jeremy Avigad's lecture notes. -/ open expr tactic classical variables {p q r s : Prop} variables {a b c d e : Prop} section local attribute [instance] classical.prop_decidable theorem not_or_of_imp (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := ⟨not_or_of_imp, or.neg_resolve_left⟩ theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem not_not : ¬¬a ↔ a := iff.intro by_contradiction not_not_intro theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩, λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb) theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩ end meta def normalize : tactic unit := `[ try { simp only [ not_or_distrib, not_and_distrib, not_not, imp_iff_not_or, not_true_iff, not_false_iff, iff_def ] at * } ] meta def find_conj : list expr → tactic expr | [] := failed | (e :: es) := do t ← infer_type e, match t with | `(%%a ∧ %%b) := return e | _ := find_conj es end meta def find_disj : list expr → tactic expr | [] := failed | (e :: es) := do t ← infer_type e, match t with | `(%%a ∨ %%b) := return e | _ := find_disj es end meta def split_conj : tactic unit := do l ← local_context, e ← find_conj l, cases e, skip meta def split_conjs : tactic unit := repeat split_conj meta def split_disj : tactic unit := do l ← local_context, e ← find_disj l, cases e, skip meta def proof_by_contradiction : tactic unit := do refine ``(classical.by_contradiction _), intro `_, skip meta def tab_aux : tactic unit := do split_conjs, contradiction <|> (split_disj >> tab_aux >> tab_aux) meta def tab : tactic unit := do proof_by_contradiction, normalize, tab_aux example : a ∧ b → b ∧ a := by tab example : a ∧ (a → b) → b := by tab -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := by tab example : p ∨ q ↔ q ∨ p := by tab -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := by tab example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := by tab -- distributivity example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by tab example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := by tab -- other properties example : (p → (q → r)) ↔ (p ∧ q → r) := by tab example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := by tab example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := by tab example : ¬p ∨ ¬q → ¬(p ∧ q) := by tab example : ¬(p ∧ ¬p) := by tab example : p ∧ ¬q → ¬(p → q) := by tab example : ¬p → (p → q) := by tab example : (¬p ∨ q) → (p → q) := by tab example : p ∨ false ↔ p := by tab example : p ∧ false ↔ false := by tab example : ¬(p ↔ ¬p) := by tab example : (p → q) → (¬q → ¬p) := by tab example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := by tab example : ¬(p ∧ q) → ¬p ∨ ¬q := by tab example : ¬(p → q) → p ∧ ¬q := by tab example : (p → q) → (¬p ∨ q) := by tab example : (¬q → ¬p) → (p → q) := by tab example : p ∨ ¬p := by tab example : (((p → q) → p) → p) := by tab example (h₁ : a ∧ b) (h₂ : b ∧ ¬ c) : a ∨ c := by tab example (h₁ : a ∧ b) (h₂ : b ∧ ¬ c) : a ∧ ¬ c := by tab example : ((a → b) → a) → a := by tab example : (a → b) ∧ (b → c) → a → c := by tab example (α : Type) (x y z w : α) : x = y ∧ (x = y → z = w) → z = w := by tab example : ¬ (a ↔ ¬ a) := by tab
029bfde0ba26b9af7af4f5821dbaa66ac8c4f09e
50b3917f95cf9fe84639812ea0461b38f8f0dbe1
/M1F/room_342_group_projects/rational_powers/rational_powers.lean
0c2100a83c130797f8812798fadf96669e0ed62f
[]
no_license
roro47/xena
6389bcd7dcf395656a2c85cfc90a4366e9b825bb
237910190de38d6ff43694ffe3a9b68f79363e6c
refs/heads/master
1,598,570,061,948
1,570,052,567,000
1,570,052,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,923
lean
-- let's define the real numbers to be a number system which satisfies -- the basic properties of the real numbers which we will need. noncomputable theory constant real : Type @[instance] constant real_field : linear_ordered_field real -- This piece of magic means that "real" now behaves a lot like -- the real numbers. In particular we now have a bunch -- of theorems: example : ∀ x y : real, x * y = y * x := mul_comm variable x : real variable n : nat -- We do _not_ have powers though. So we need to make them. open nat noncomputable definition natural_power : real → nat → real | x 0 := 1 | x (succ n) := (natural_power x n) * x -- Proof by Eduard Oravkin theorem T1 : ∀ x:real, ∀ m n:nat, natural_power x (m+n) = natural_power x m *natural_power x n := begin intro x, intro m, intro n, induction n with s H1, have H : natural_power x 0 = 1, refl, rw [add_zero, H , mul_one], unfold natural_power, rw [← mul_assoc, H1], end -- Proof by Chris Hughes theorem T2 : ∀ x: real, ∀ m n : nat, natural_power (natural_power x m) n = natural_power x (m*n) := begin assume x m n, induction n with n H, unfold natural_power, rw [mul_zero, eq_comm], unfold natural_power, rw [succ_eq_add_one,mul_add,mul_one,add_one], unfold natural_power, rw [T1,H] end -- Proof by Ali Barkhordarian theorem T3 : ∀ x y: real, ∀ n : nat, natural_power x n * natural_power y n = natural_power (x*y) n := begin assume x y n, induction n with n H, unfold natural_power, exact one_mul 1, unfold natural_power, rw [mul_assoc], rw [← mul_assoc x], rw [mul_comm x], rw [mul_assoc, ←mul_assoc], rw [H] end constant nth_root (x : real) (n : nat) : (x>0) → (n>0) → real axiom is_nth_root (x : real) (n : nat) (Hx : x>0) (Hn : n>0) : natural_power (nth_root x n Hx Hn) n = x definition rational_power_v0 (x : real) (n : nat) (d : nat) (Hx : x > 0) (Hd : d > 0) : real := natural_power (nth_root x d Hx Hd) n
3a44212fbf001ee2ec94187ae7016bd08ca3efc6
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/dedekind_domain/integral_closure.lean
8116312cb9f077844a0124537804294ff721c3dc
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
13,403
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import linear_algebra.free_module.pid import ring_theory.dedekind_domain.basic import ring_theory.localization.module import ring_theory.trace /-! # Integral closure of Dedekind domains This file shows the integral closure of a Dedekind domain (in particular, the ring of integers of a number field) is a Dedekind domain. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors polynomial variables [is_domain A] section is_integral_closure /-! ### `is_integral_closure` section We show that an integral closure of a Dedekind domain in a finite separable field extension is again a Dedekind domain. This implies the ring of integers of a number field is a Dedekind domain. -/ open algebra open_locale big_operators variables (A K) [algebra A K] [is_fraction_ring A K] variables (L : Type*) [field L] (C : Type*) [comm_ring C] variables [algebra K L] [algebra A L] [is_scalar_tower A K L] variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L] /- If `L` is a separable extension of `K = Frac(A)` and `L` has no zero smul divisors by `A`, then `L` is the localization of the integral closure `C` of `A` in `L` at `A⁰`. -/ lemma is_integral_closure.is_localization [is_separable K L] [no_zero_smul_divisors A L] : is_localization (algebra.algebra_map_submonoid C A⁰) L := begin haveI : is_domain C := (is_integral_closure.equiv A C L (integral_closure A L)).to_ring_equiv.is_domain (integral_closure A L), haveI : no_zero_smul_divisors A C := is_integral_closure.no_zero_smul_divisors A L, refine ⟨_, λ z, _, λ x y, ⟨λ h, ⟨1, _⟩, _⟩⟩, { rintros ⟨_, x, hx, rfl⟩, rw [is_unit_iff_ne_zero, map_ne_zero_iff _ (is_integral_closure.algebra_map_injective C A L), subtype.coe_mk, map_ne_zero_iff _ (no_zero_smul_divisors.algebra_map_injective A C)], exact mem_non_zero_divisors_iff_ne_zero.mp hx, }, { obtain ⟨m, hm⟩ := is_integral.exists_multiple_integral_of_is_localization A⁰ z (is_separable.is_integral K z), obtain ⟨x, hx⟩ : ∃ x, algebra_map C L x = m • z := is_integral_closure.is_integral_iff.mp hm, refine ⟨⟨x, algebra_map A C m, m, set_like.coe_mem m, rfl⟩, _⟩, rw [subtype.coe_mk, ← is_scalar_tower.algebra_map_apply, hx, mul_comm, submonoid.smul_def, smul_def], }, { simp only [is_integral_closure.algebra_map_injective C A L h], }, { rintros ⟨⟨_, m, hm, rfl⟩, h⟩, refine congr_arg (algebra_map C L) ((mul_right_inj' _).mp h), rw [subtype.coe_mk, map_ne_zero_iff _ (no_zero_smul_divisors.algebra_map_injective A C)], exact mem_non_zero_divisors_iff_ne_zero.mp hm, }, end variable [finite_dimensional K L] variables {A K L} lemma is_integral_closure.range_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : ((algebra.linear_map C L).restrict_scalars A).range ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, rintros _ ⟨x, rfl⟩, simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply], have hx : is_integral A (algebra_map C L x) := (is_integral_closure.is_integral A L x).algebra_map, rsuffices ⟨c, x_eq⟩ : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i, { rw x_eq, refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)), rw set.mem_range, exact ⟨i, rfl⟩ }, suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i), { obtain ⟨c, hc, hx⟩ := this, have hc' : ∀ i, is_localization.is_integer A (c i) := λ i, is_integrally_closed.is_integral_iff.mp (hc i), use λ i, classical.some (hc' i), refine hx.trans (finset.sum_congr rfl (λ i _, _)), conv_lhs { rw [← classical.some_spec (hc' i)] }, rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] }, refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩, rw bilin_form.dual_basis_repr_apply, exact is_integral_trace (is_integral_mul hx (hb_int i)) end lemma integral_closure_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : (integral_closure A L).to_submodule ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int), intros x hx, exact ⟨⟨x, hx⟩, rfl⟩ end variables (A) (K) include K /-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R` to `(y : R) • x ∈ integral_closure R L`. -/ lemma exists_integral_multiples (s : finset L) : ∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) := begin haveI := classical.dec_eq L, refine s.induction _ _, { use [1, one_ne_zero], rintros x ⟨⟩ }, { rintros x s hx ⟨y, hy, hs⟩, obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple ((is_fraction_ring.is_algebraic_iff A K L).mpr (is_algebraic_of_finite _ _ x)) ((injective_iff_map_eq_zero (algebra_map A L)).mp _), refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩, rcases finset.mem_insert.mp hx'' with (rfl | hx''), { rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'], exact is_integral_mul is_integral_algebra_map x'.2 }, { rw [mul_comm, mul_smul, algebra.smul_def], exact is_integral_mul is_integral_algebra_map (hs _ hx'') }, { rw is_scalar_tower.algebra_map_eq A K L, apply (algebra_map K L).injective.comp, exact is_fraction_ring.injective _ _ } } end variables (L) /-- If `L` is a finite extension of `K = Frac(A)`, then `L` has a basis over `A` consisting of integral elements. -/ lemma finite_dimensional.exists_is_basis_integral : ∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) := begin letI := classical.dec_eq L, letI : is_noetherian K L := is_noetherian.iff_fg.2 infer_instance, let s' := is_noetherian.finset_basis_index K L, let bs' := is_noetherian.finset_basis K L, obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'), have hy' : algebra_map A L y ≠ 0, { refine mt ((injective_iff_map_eq_zero (algebra_map A L)).mp _ _) hy, rw is_scalar_tower.algebra_map_eq A K L, exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) }, refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x, inv_fun := λ x, (algebra_map A L y)⁻¹ * x, left_inv := _, right_inv := _, .. algebra.lmul _ _ (algebra_map A L y) }, _⟩, { intros x, simp only [inv_mul_cancel_left₀ hy'] }, { intros x, simp only [mul_inv_cancel_left₀ hy'] }, { rintros ⟨x', hx'⟩, simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his', simp only [basis.map_apply, linear_equiv.coe_mk], exact his' _ ⟨_, rfl⟩ } end variables (A K L) [is_separable K L] include L /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian over `A`. -/ lemma is_integral_closure.is_noetherian [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian A C := begin haveI := classical.dec_eq L, obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L, let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, letI := is_noetherian_span_of_finite A (set.finite_range b'), let f : C →ₗ[A] submodule.span A (set.range b') := (submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp ((algebra.linear_map C L).restrict_scalars A).range_restrict, refine is_noetherian_of_ker_bot f _, rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict], exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L) end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian. -/ lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring C := is_noetherian_ring_iff.mpr $ is_noetherian_of_tower A (is_integral_closure.is_noetherian A K L C) /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a principal ring and `L` has no zero smul divisors by `A`, the integral closure `C` of `A` in `L` is a free `A`-module. -/ lemma is_integral_closure.module_free [no_zero_smul_divisors A L] [is_principal_ideal_ring A] : module.free A C := begin haveI : no_zero_smul_divisors A C := is_integral_closure.no_zero_smul_divisors A L, haveI : is_noetherian A C := is_integral_closure.is_noetherian A K L _, exact module.free_of_finite_type_torsion_free', end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a principal ring and `L` has no zero smul divisors by `A`, the `A`-rank of the integral closure `C` of `A` in `L` is equal to the `K`-rank of `L`. -/ lemma is_integral_closure.rank [is_principal_ideal_ring A] [no_zero_smul_divisors A L] : finite_dimensional.finrank A C = finite_dimensional.finrank K L := begin haveI : module.free A C := is_integral_closure.module_free A K L C, haveI : is_noetherian A C := is_integral_closure.is_noetherian A K L C, haveI : is_localization (algebra.algebra_map_submonoid C A⁰) L := is_integral_closure.is_localization A K L C, let b := basis.localization_localization K A⁰ L (module.free.choose_basis A C), rw [finite_dimensional.finrank_eq_card_choose_basis_index, finite_dimensional.finrank_eq_card_basis b], end variables {A K} /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure of `A` in `L` is Noetherian. -/ lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring (integral_closure A L) := is_integral_closure.is_noetherian_ring A K L (integral_closure A L) variables (A K) [is_domain C] /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure `C` of `A` in `L` is a Dedekind domain. Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A` and `C := integral_closure A L`. -/ lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain C := begin haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C, exact ⟨is_integral_closure.is_noetherian_ring A K L C, h.dimension_le_one.is_integral_closure _ L _, (is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x (is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx), is_integral_closure.algebra_map_mk' _ _ _⟩)⟩ end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. Can't be an instance since `K` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`. -/ lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := is_integral_closure.is_dedekind_domain A K L (integral_closure A L) omit K variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L] variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L] /- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. See also the lemma `integral_closure.is_dedekind_domain` where you can choose the field of fractions yourself. -/ instance integral_closure.is_dedekind_domain_fraction_ring [is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := integral_closure.is_dedekind_domain A (fraction_ring A) L end is_integral_closure
61df6da578e6690bf18db6d7fe32f0407d6d762f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/lemmas.lean
88a0046c820692b9e7a80e0557d7c888eb962308
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
2,044
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import tactic.split_ifs /-! # More basic logic properties A few more logic lemmas. These are in their own file, rather than `logic.basic`, because it is convenient to be able to use the `split_ifs` tactic. ## Implementation notes We spell those lemmas out with `dite` and `ite` rather than the `if then else` notation because this would result in less delta-reduced statements. -/ variables {α : Sort*} {p q r : Prop} [decidable p] [decidable q] {a b c : α} lemma dite_dite_distrib_left {a : p → α} {b : ¬ p → q → α} {c : ¬ p → ¬ q → α} : dite p a (λ hp, dite q (b hp) (c hp)) = dite q (λ hq, dite p a $ λ hp, b hp hq) (λ hq, dite p a $ λ hp, c hp hq) := by split_ifs; refl lemma dite_dite_distrib_right {a : p → q → α} {b : p → ¬ q → α} {c : ¬ p → α} : dite p (λ hp, dite q (a hp) (b hp)) c = dite q (λ hq, dite p (λ hp, a hp hq) c) (λ hq, dite p (λ hp, b hp hq) c) := by split_ifs; refl lemma ite_dite_distrib_left {a : α} {b : q → α} {c : ¬ q → α} : ite p a (dite q b c) = dite q (λ hq, ite p a $ b hq) (λ hq, ite p a $ c hq) := dite_dite_distrib_left lemma ite_dite_distrib_right {a : q → α} {b : ¬ q → α} {c : α} : ite p (dite q a b) c = dite q (λ hq, ite p (a hq) c) (λ hq, ite p (b hq) c) := dite_dite_distrib_right lemma dite_ite_distrib_left {a : p → α} {b : ¬ p → α} {c : ¬ p → α} : dite p a (λ hp, ite q (b hp) (c hp)) = ite q (dite p a b) (dite p a c) := dite_dite_distrib_left lemma dite_ite_distrib_right {a : p → α} {b : p → α} {c : ¬ p → α} : dite p (λ hp, ite q (a hp) (b hp)) c = ite q (dite p a c) (dite p b c) := dite_dite_distrib_right lemma ite_ite_distrib_left : ite p a (ite q b c) = ite q (ite p a b) (ite p a c) := dite_dite_distrib_left lemma ite_ite_distrib_right : ite p (ite q a b) c = ite q (ite p a c) (ite p b c) := dite_dite_distrib_right
6dca794c7606fe044f7b214df753ff63f14f6174
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Init/WFTactics.lean
8bb641818f7da1674948bad1c0aa6afdd3a39051
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
2,616
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.SizeOf import Init.WF /-- Unfold definitions commonly used in well founded relation definitions. This is primarily intended for internal use in `decreasing_tactic`. -/ macro "simp_wf" : tactic => `(tactic| simp [invImage, InvImage, Prod.lex, sizeOfWFRel, measure, Nat.lt_wfRel, WellFoundedRelation.rel]) /-- Extensible helper tactic for `decreasing_tactic`. This handles the "base case" reasoning after applying lexicographic order lemmas. It can be extended by adding more macro definitions, e.g. ``` macro_rules | `(tactic| decreasing_trivial) => `(tactic| linarith) ``` -/ syntax "decreasing_trivial" : tactic macro_rules | `(tactic| decreasing_trivial) => `(tactic| simp (config := { arith := true }); done) macro_rules | `(tactic| decreasing_trivial) => `(tactic| assumption) macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.sub_succ_lt_self; assumption) -- a - (i+1) < a - i if i < a macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt'; assumption) -- i-1 < i if j < i macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt; assumption) -- i-1 < i if i ≠ 0 /-- Constructs a proof of decreasing along a well founded relation, by applying lexicographic order lemmas and using `ts` to solve the base case. If it fails, it prints a message to help the user diagnose an ill-founded recursive definition. -/ macro "decreasing_with " ts:tacticSeq : tactic => `(tactic| (simp_wf repeat (first | apply Prod.Lex.right | apply Prod.Lex.left) repeat (first | apply PSigma.Lex.right | apply PSigma.Lex.left) first | done | $ts | fail "failed to prove termination, possible solutions: - Use `have`-expressions to prove the remaining goals - Use `termination_by` to specify a different well-founded relation - Use `decreasing_by` to specify your own tactic for discharging this kind of goal")) /-- `decreasing_tactic` is called by default on well-founded recursions in order to synthesize a proof that recursive calls decrease along the selected well founded relation. It can be locally overridden by using `decreasing_by tac` on the recursive definition, and it can also be globally extended by adding more definitions for `decreasing_tactic` (or `decreasing_trivial`, which this tactic calls). -/ macro "decreasing_tactic" : tactic => `(tactic| decreasing_with first | decreasing_trivial | subst_vars; decreasing_trivial)
68684aee07b87018a342a508749521c89fe9f0bd
6950a6e5cebf75da9b91f42789baf52514655111
/hol/boolean_free_HOL.lean
0cba829c3d4904f24af8ef2f34a11ac3a4540e52
[]
no_license
phlippe/Lean_hammer
a6d0a1af09fbce0c58b801032099b9b91d49ecf0
2116279b9c6b334f5b661e4abf4561368cca2391
refs/heads/master
1,587,486,769,513
1,561,466,931,000
1,561,466,931,000
169,705,506
0
1
null
1,550,228,564,000
1,549,614,939,000
Lean
UTF-8
Lean
false
false
2,453
lean
import .datastructures_hol meta mutual def hol_type_wo_bool, hol_term_wo_bool, hol_formula_wo_bool with hol_type_wo_bool : holtype → holtype | e@(holtype.o) := holtype.ltype "boolean" | e@(holtype.functor ts t) := holtype.functor (list.map (λ (tp : holtype), hol_type_wo_bool tp) ts) (hol_type_wo_bool t) | e@(holtype.dep_binder ts t) := holtype.dep_binder (list.map (λ (tp : (name × holtype)), (tp.1, hol_type_wo_bool tp.2)) ts) (hol_type_wo_bool t) | e@(holtype.partial_app t) := holtype.partial_app (hol_term_wo_bool t) | e := e with hol_term_wo_bool: holterm → holterm | e@(holterm.top) := holterm.const "bool_true" | e@(holterm.bottom) := holterm.const "bool_false" | e@(holterm.app t1 t2) := holterm.app (hol_term_wo_bool t1) (hol_term_wo_bool t2) | e@(holterm.lambda n ty t) := holterm.lambda n (hol_type_wo_bool ty) (hol_term_wo_bool t) | e := e with hol_formula_wo_bool: holform → holform | e@(holform.P t) := holform.P (hol_term_wo_bool t) | e@(holform.T t u) := holform.T (hol_term_wo_bool t) (hol_type_wo_bool u) | e@(holform.eq t u) := holform.eq (hol_term_wo_bool t) (hol_term_wo_bool u) | e@(holform.neg f) := holform.neg (hol_formula_wo_bool f) | e@(holform.imp f1 f2) := holform.imp (hol_formula_wo_bool f1) (hol_formula_wo_bool f2) | e@(holform.iff f1 f2) := holform.iff (hol_formula_wo_bool f1) (hol_formula_wo_bool f2) | e@(holform.conj f1 f2) := holform.conj (hol_formula_wo_bool f1) (hol_formula_wo_bool f2) | e@(holform.disj f1 f2) := holform.disj (hol_formula_wo_bool f1) (hol_formula_wo_bool f2) | e@(holform.all n n1 f) := holform.all n n1 (hol_formula_wo_bool f) | e@(holform.exist n n1 f) := holform.exist n n1 (hol_formula_wo_bool f) | e := e -- meta def axiom_list_wo_bool (l : list axioma) := (list.map (λ (x : axioma), ⟨x.1, hol_formula_wo_bool x.2⟩ ) l) -- meta def typedef_list_wo_bool (l : list type_def) := (list.map (λ (x : type_def), (x.1, x.2, hol_type_wo_bool x.3)) l) meta def axiom_list_wo_bool : list axioma → list axioma | (x :: xs) := [⟨x.1, hol_formula_wo_bool x.2⟩] ++ xs | [] := [] meta def typedef_list_wo_bool : list type_def → list type_def | (x :: xs) := [⟨x.1, x.2, hol_type_wo_bool x.3⟩] ++ xs | [] := [] meta def boolean_type_replacements : list type_def := [⟨"boolean_definition", "boolean", holtype.type⟩, ⟨"boolean_true_definition", "bool_true", holtype.ltype "boolean"⟩, ⟨"boolean_false_definition", "bool_false", holtype.ltype "boolean"⟩]
b70a44571c5d81d78eb931f3883f7bd9b10331b9
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Elab/StructInst.lean
6683395437daefcd6265a7bd51aa42222961f061
[ "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
33,964
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindExpr import Lean.Elab.App import Lean.Elab.Binders import Lean.Elab.Quotation namespace Lean.Elab.Term.StructInst open Std (HashMap) open Meta /- Structure instances are of the form: "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" -/ @[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx => let expectedArg := stx[4] if expectedArg.isNone then Macro.throwUnsupported else let expected := expectedArg[1] let stxNew := stx.setArg 4 mkNullNode `(($stxNew : $expected)) /- If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`. Note that this one is not a `Macro` because we need to access the local context. -/ private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) := withFreshMacroScope do let sourceOpt := stx[1] if sourceOpt.isNone then pure none else let source := sourceOpt[0] match (← isLocalIdent? source) with | some _ => pure none | none => let src ← `(src) let sourceOpt := sourceOpt.setArg 0 src let stxNew := stx.setArg 1 sourceOpt `(let src := $source; $stxNew) inductive Source := | none -- structure instance source has not been provieded | implicit (stx : Syntax) -- `..` | explicit (stx : Syntax) (src : Expr) -- `src with` instance : Inhabited Source := ⟨Source.none⟩ def Source.isNone : Source → Bool | Source.none => true | _ => false def setStructSourceSyntax (structStx : Syntax) : Source → Syntax | Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode | Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx | Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode private def getStructSource (stx : Syntax) : TermElabM Source := withRef stx do let explicitSource := stx[1] let implicitSource := stx[3] if explicitSource.isNone && implicitSource.isNone then return Source.none else if explicitSource.isNone then return Source.implicit implicitSource else if implicitSource.isNone then let fvar? ← isLocalIdent? explicitSource[0] match fvar? with | none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here | some src => return Source.explicit explicitSource src else throwError "invalid structure instance `with` and `..` cannot be used together" /- We say a `{ ... }` notation is a `modifyOp` if it contains only one ``` def structInstArrayRef := parser! "[" >> termParser >>"]" ``` -/ private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do let s? ← stx[2].getArgs.foldlM (init := none) fun s? p => /- p is of the form `(group (structInstField >> optional ", "))` -/ let arg := p[0] /- Remark: the syntax for `structInstField` is ``` def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstField := parser! structInstLVal >> " := " >> termParser ``` -/ let lval := arg[0] let k := lval.getKind if k == `Lean.Parser.Term.structInstArrayRef then match s? with | none => pure (some arg) | some s => if s.getKind == `Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid {...} notation, at most one `[..]` at a given level" else throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level" else match s? with | none => pure (some arg) | some s => if s.getKind == `Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level" else pure s? match s? with | none => pure none | some s => if s[0].getKind == `Lean.Parser.Term.structInstArrayRef then pure s? else pure none private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let cont (val : Syntax) : TermElabM Expr := do let lval := modifyOp[0] let idx := lval[1] let self := source[0] let stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val)) trace[Elab.struct.modifyOp]! "{stx}\n===>\n{stxNew}" withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? trace[Elab.struct.modifyOp]! "{modifyOp}\nSource: {source}" let rest := modifyOp[1] if rest.isNone then cont modifyOp[3] else let s ← `(s) let valFirst := rest[0] let valFirst := if valFirst.getKind == `Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1] let restArgs := rest.getArgs let valRest := mkNullNode restArgs[1:restArgs.size] let valField := modifyOp.setArg 0 valFirst let valField := valField.setArg 1 valRest let valSource := source.modifyArg 0 fun _ => s let val := stx.setArg 1 valSource let val := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]] trace[Elab.struct.modifyOp]! "{stx}\nval: {val}" cont val /- Get structure name and elaborate explicit source (if available) -/ private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name := do tryPostponeIfNoneOrMVar expectedType? let useSource : Unit → TermElabM Name := fun _ => match sourceView, expectedType? with | Source.explicit _ src, _ => do let srcType ← inferType src let srcType ← whnf srcType tryPostponeIfMVar srcType match srcType.getAppFn with | Expr.const constName _ _ => pure constName | _ => throwError! "invalid \{...} notation, source type is not of the form (C ...){indentExpr srcType}" | _, some expectedType => throwError! "invalid \{...} notation, expected type is not of the form (C ...){indentExpr expectedType}" | _, none => throwError! "invalid \{...} notation, expected type must be known" match expectedType? with | none => useSource () | some expectedType => let expectedType ← whnf expectedType match expectedType.getAppFn with | Expr.const constName _ _ => pure constName | _ => useSource () inductive FieldLHS := | fieldName (ref : Syntax) (name : Name) | fieldIndex (ref : Syntax) (idx : Nat) | modifyOp (ref : Syntax) (index : Syntax) instance : Inhabited FieldLHS := ⟨FieldLHS.fieldName arbitrary arbitrary⟩ instance : ToFormat FieldLHS := ⟨fun lhs => match lhs with | FieldLHS.fieldName _ n => fmt n | FieldLHS.fieldIndex _ i => fmt i | FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩ inductive FieldVal (σ : Type) := | term (stx : Syntax) : FieldVal σ | nested (s : σ) : FieldVal σ | default : FieldVal σ -- mark that field must be synthesized using default value structure Field (σ : Type) := (ref : Syntax) (lhs : List FieldLHS) (val : FieldVal σ) (expr? : Option Expr := none) instance {σ} : Inhabited (Field σ) := ⟨⟨arbitrary, [], FieldVal.term arbitrary, arbitrary⟩⟩ def Field.isSimple {σ} : Field σ → Bool | { lhs := [_], .. } => true | _ => false inductive Struct := | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source) instance : Inhabited Struct := ⟨⟨arbitrary, arbitrary, [], arbitrary⟩⟩ abbrev Fields := List (Field Struct) /- true if all fields of the given structure are marked as `default` -/ partial def Struct.allDefault : Struct → Bool | ⟨_, _, fields, _⟩ => fields.all fun ⟨_, _, val, _⟩ => match val with | FieldVal.term _ => false | FieldVal.default => true | FieldVal.nested s => allDefault s def Struct.ref : Struct → Syntax | ⟨ref, _, _, _⟩ => ref def Struct.structName : Struct → Name | ⟨_, structName, _, _⟩ => structName def Struct.fields : Struct → Fields | ⟨_, _, fields, _⟩ => fields def Struct.source : Struct → Source | ⟨_, _, _, s⟩ => s def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format := Format.joinSep field.lhs " . " ++ " := " ++ match field.val with | FieldVal.term v => v.prettyPrint | FieldVal.nested s => formatStruct s | FieldVal.default => "<default>" partial def formatStruct : Struct → Format | ⟨_, structName, fields, source⟩ => let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", " match source with | Source.none => "{" ++ fieldsFmt ++ "}" | Source.implicit _ => "{" ++ fieldsFmt ++ " .. }" | Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}" instance : ToFormat Struct := ⟨formatStruct⟩ instance : ToString Struct := ⟨toString ∘ format⟩ instance : ToFormat (Field Struct) := ⟨formatField formatStruct⟩ instance : ToString (Field Struct) := ⟨toString ∘ format⟩ /- Recall that `structInstField` elements have the form ``` def structInstField := parser! structInstLVal >> " := " >> termParser def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstArrayRef := parser! "[" >> termParser >>"]" -/ -- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName` def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax | FieldLHS.modifyOp stx _ => stx | FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkNullNode #[mkAtomFrom stx ".", mkIdentFrom stx name] | FieldLHS.fieldIndex stx _ => if first then stx else mkNullNode #[mkAtomFrom stx ".", stx] def FieldVal.toSyntax : FieldVal Struct → Syntax | FieldVal.term stx => stx | _ => unreachable! def Field.toSyntax : Field Struct → Syntax | field => let stx := field.ref let stx := stx.setArg 3 field.val.toSyntax match field.lhs with | first::rest => let stx := stx.setArg 0 <| first.toSyntax true let stx := stx.setArg 1 <| mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) stx | _ => unreachable! private def toFieldLHS (stx : Syntax) : Except String FieldLHS := if stx.getKind == `Lean.Parser.Term.structInstArrayRef then return FieldLHS.modifyOp stx stx[1] else -- Note that the representation of the first field is different. let stx := if stx.getKind == nullKind then stx[1] else stx if stx.isIdent then return FieldLHS.fieldName stx stx.getId.eraseMacroScopes else match stx.isFieldIdx? with | some idx => return FieldLHS.fieldIndex stx idx | none => throw "unexpected structure syntax" private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : Except String Struct := do /- Recall that `stx` is of the form ``` parser! "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let fieldsStx := stx[2].getArgs.map (·[0]) let fields ← fieldsStx.toList.mapM fun fieldStx => do let val := fieldStx[3] let first ← toFieldLHS fieldStx[0] let rest ← fieldStx[1].getArgs.toList.mapM toFieldLHS pure { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct } pure ⟨stx, structName, fields, source⟩ def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct := match s with | ⟨ref, structName, fields, source⟩ => return ⟨ref, structName, (← f fields), source⟩ @[inline] def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct := Id.run <| s.modifyFieldsM f def Struct.setFields (s : Struct) (fields : Fields) : Struct := s.modifyFields fun _ => fields private def expandCompositeFields (s : Struct) : Struct := s.modifyFields fun fields => fields.map fun field => match field with | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } => let newEntries := n.components.map <| FieldLHS.fieldName ref { field with lhs := newEntries ++ rest } | _ => field private def expandNumLitFields (s : Struct) : TermElabM Struct := s.modifyFieldsM fun fields => do let env ← getEnv let fieldNames := getStructureFields env s.structName fields.mapM fun field => match field with | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } => if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0" else if idx > fieldNames.size then throwErrorAt! ref "invalid field index, structure has only #{fieldNames.size} fields" else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest } | _ => pure field /- For example, consider the following structures: ``` structure A := (x : Nat) structure B extends A := (y : Nat) structure C extends B := (z : Bool) ``` This method expands parent structure fields using the path to the parent structure. For example, ``` { x := 0, y := 0, z := true : C } ``` is expanded into ``` { toB.toA.x := 0, toB.y := 0, z := true : C } ``` -/ private def expandParentFields (s : Struct) : TermElabM Struct := do let env ← getEnv s.modifyFieldsM fun fields => fields.mapM fun field => match field with | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } => match findField? env s.structName fieldName with | none => throwErrorAt! ref "'{fieldName}' is not a field of structure '{s.structName}'" | some baseStructName => if baseStructName == s.structName then pure field else match getPathToBaseStructure? env baseStructName s.structName with | some path => do let path := path.map fun funName => match funName with | Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s) | _ => unreachable! pure { field with lhs := path ++ field.lhs } | _ => throwErrorAt! ref "failed to access field '{fieldName}' in parent structure" | _ => pure field private abbrev FieldMap := HashMap Name Fields private def mkFieldMap (fields : Fields) : TermElabM FieldMap := fields.foldlM (init := {}) fun fieldMap field => match field.lhs with | FieldLHS.fieldName _ fieldName :: rest => match fieldMap.find? fieldName with | some (prevField::restFields) => if field.isSimple || prevField.isSimple then throwErrorAt! field.ref "field '{fieldName}' has already beed specified" else return fieldMap.insert fieldName (field::prevField::restFields) | _ => return fieldMap.insert fieldName [field] | _ => unreachable! private def isSimpleField? : Fields → Option (Field Struct) | [field] => if field.isSimple then some field else none | _ => none private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do match fieldNames.findIdx? fun n => n == fieldName with | some idx => pure idx | none => throwError! "field '{fieldName}' is not a valid field of '{structName}'" private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax := Syntax.node `Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName] private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source := match src with | Source.explicit stx src => do let idx ← getFieldIdx structName fieldNames fieldName let stx := stx.modifyArg 0 fun stx => mkProjStx stx fieldName return Source.explicit stx (mkProj structName idx src) | s => return s @[specialize] private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName withRef s.ref do s.modifyFieldsM fun fields => do let fieldMap ← mkFieldMap fields fieldMap.toList.mapM fun ⟨fieldName, fields⟩ => do match isSimpleField? fields with | some field => pure field | none => let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! } let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let field := fields.head! match Lean.isSubobjectField? env s.structName fieldName with | some substructName => let substruct := Struct.mk s.ref substructName substructFields substructSource let substruct ← expandStruct substruct pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct } | none => do -- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them. let valStx := s.ref -- construct substructure syntax using s.ref as template let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type let args := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode] let valStx := valStx.setArg 2 (mkNullNode args) let valStx := setStructSourceSyntax valStx substructSource pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx } def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) := fields.find? fun field => match field.lhs with | [FieldLHS.fieldName _ n] => n == fieldName | _ => false @[specialize] private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName let ref := s.ref withRef ref do let fields ← fieldNames.foldlM (init := []) fun fields fieldName => do match findField? s.fields fieldName with | some field => return field::fields | none => let addField (val : FieldVal Struct) : TermElabM Fields := do return { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields match Lean.isSubobjectField? env s.structName fieldName with | some substructName => do let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let substruct := Struct.mk s.ref substructName [] substructSource let substruct ← expandStruct substruct addField (FieldVal.nested substruct) | none => match s.source with | Source.none => addField FieldVal.default | Source.implicit _ => addField (FieldVal.term (mkHole s.ref)) | Source.explicit stx _ => -- stx is of the form `optional (try (termParser >> "with"))` let src := stx[0] let val := mkProjStx src fieldName addField (FieldVal.term val) return s.setFields fields.reverse private partial def expandStruct (s : Struct) : TermElabM Struct := do let s := expandCompositeFields s let s ← expandNumLitFields s let s ← expandParentFields s let s ← groupFields expandStruct s addMissingFields expandStruct s structure CtorHeaderResult := (ctorFn : Expr) (ctorFnType : Expr) (instMVars : Array MVarId := #[]) private def mkCtorHeaderAux : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult | 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars } | n+1, type, ctorFn, instMVars => do let type ← whnfForall type match type with | Expr.forallE _ d b c => match c.binderInfo with | BinderInfo.instImplicit => let a ← mkFreshExprMVar d MetavarKind.synthetic mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!) | _ => let a ← mkFreshExprMVar d mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars | _ => throwError "unexpected constructor type" private partial def getForallBody : Nat → Expr → Option Expr | i+1, Expr.forallE _ _ b _ => getForallBody i b | i+1, _ => none | 0, type => type private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit := match expectedType? with | none => pure () | some expectedType => do match getForallBody numFields type with | none => pure () | some typeBody => unless typeBody.hasLooseBVars do isDefEq expectedType typeBody pure () private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do let lvls ← ctorVal.lparams.mapM fun _ => mkFreshLevelMVar let val := Lean.mkConst ctorVal.name lvls let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams lvls let r ← mkCtorHeaderAux ctorVal.nparams type val #[] propagateExpectedType r.ctorFnType ctorVal.nfields expectedType? synthesizeAppInstMVars r.instMVars pure r def markDefaultMissing (e : Expr) : Expr := mkAnnotation `structInstDefault e def defaultMissing? (e : Expr) : Option Expr := annotation? `structInstDefault e def throwFailedToElabField {α} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α := throwError! "failed to elaborate field '{fieldName}' of '{structName}, {msgData}" def trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do if !s.allDefault then pure none else try synthInstance? expectedType catch _ => pure none private partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr × Struct) := withRef s.ref do let env ← getEnv let ctorVal := getStructureCtor env s.structName let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType? let (e, _, fields) ← s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field => match field.lhs with | [FieldLHS.fieldName ref fieldName] => do let type ← whnfForall type match type with | Expr.forallE _ d b c => let cont (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do let e := mkApp e val let type := b.instantiate1 val let field := { field with expr? := some val } pure (e, type, field::fields) match field.val with | FieldVal.term stx => cont (← elabTermEnsuringType stx d) field | FieldVal.nested s => do -- if all fields of `s` are marked as `default`, then try to synthesize instance match (← trySynthStructInstance? s d) with | some val => cont val { field with val := FieldVal.term (mkHole field.ref) } | none => do let (val, sNew) ← elabStruct s (some d); let val ← ensureHasType d val; cont val { field with val := FieldVal.nested sNew } | FieldVal.default => do let val ← withRef field.ref <| mkFreshExprMVar (some d); cont (markDefaultMissing val) field | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!"unexpected constructor type{indentExpr type}" | _ => throwErrorAt field.ref "unexpected unexpanded structure field" pure (e, s.setFields fields.reverse) namespace DefaultFields structure Context := -- We must search for default values overriden in derived structures (structs : Array Struct := #[]) (allStructNames : Array Name := #[]) /- Consider the following example: ``` structure A := (x : Nat := 1) structure B extends A := (y : Nat := x + 1) (x := y + 1) structure C extends B := (z : Nat := 2*y) (x := z + 3) ``` And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`. We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2. The field `maxDistance` specifies the maximum distance considered in a round of Default field computation. Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0. The fixpoint for setting default values works in the following way. - Keep computing default values using `maxDistance == 0`. - We increase `maxDistance` whenever we failed to compute a new default value in a round. - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value. We use depth-first search. - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above). -/ (maxDistance : Nat := 0) structure State := (progress : Bool := false) partial def collectStructNames (struct : Struct) (names : Array Name) : Array Name := let names := names.push struct.structName struct.fields.foldl (init := names) fun names field => match field.val with | FieldVal.nested struct => collectStructNames struct names | _ => names partial def getHierarchyDepth (struct : Struct) : Nat := struct.fields.foldl (init := 0) fun max field => match field.val with | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1) | _ => max partial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) := struct.fields.findSome? fun field => match field.val with | FieldVal.nested struct => findDefaultMissing? mctx struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field | _ => none def getFieldName (field : Field Struct) : Name := match field.lhs with | [FieldLHS.fieldName _ fieldName] => fieldName | _ => unreachable! abbrev M := ReaderT Context (StateRefT State TermElabM) def isRoundDone : M Bool := do return (← get).progress && (← read).maxDistance > 0 def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr := struct.fields.findSome? fun field => if getFieldName field == fieldName then field.expr? else none partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr) | Expr.lam n d b c => withRef struct.ref do if c.binderInfo.isExplicit then let fieldName := n match getFieldValue? struct fieldName with | none => pure none | some val => let valType ← inferType val if (← isDefEq valType d) then mkDefaultValueAux? struct (b.instantiate1 val) else pure none else let arg ← mkFreshExprMVar d mkDefaultValueAux? struct (b.instantiate1 arg) | e => if e.isAppOfArity `id 2 then pure (some e.appArg!) else pure (some e) def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) := withRef struct.ref do let us ← cinfo.lparams.mapM fun _ => mkFreshLevelMVar mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us) /-- If `e` is a projection function of one of the given structures, then reduce it -/ def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name _ _ => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if structNames.contains structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none /-- Reduce default value. It performs beta reduction and projections of the given structures. -/ partial def reduce (structNames : Array Name) : Expr → MetaM Expr | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (← reduce structNames b) | e@(Expr.forallE _ _ _ _) => forallTelescope e fun xs b => do mkForallFVars xs (← reduce structNames b) | e@(Expr.letE _ _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLetFVars xs (← reduce structNames b) | e@(Expr.proj _ i b _) => do match (← Meta.reduceProj? b i) with | some r => reduce structNames r | none => return e.updateProj! (← reduce structNames b) | e@(Expr.app f _ _) => do match (← reduceProjOf? structNames e) with | some r => reduce structNames r | none => let f := f.getAppFn let f' ← reduce structNames f if f'.isLambda then let revArgs := e.getAppRevArgs reduce structNames (f'.betaRev revArgs) else let args ← e.getAppArgs.mapM (reduce structNames) return (mkAppN f' args) | e@(Expr.mdata _ b _) => do let b ← reduce structNames b if (defaultMissing? e).isSome && !b.isMVar then return b else return e.updateMData! b | e@(Expr.mvar mvarId _) => do match (← getExprMVarAssignment? mvarId) with | some val => if val.isMVar then reduce structNames val else pure val | none => return e | e => return e partial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool := let rec loop (i : Nat) (dist : Nat) := do if dist > maxDistance then pure false else if h : i < structs.size then do let struct := structs.get ⟨i, h⟩ let defaultName := struct.structName ++ fieldName ++ `_default let env ← getEnv match env.find? defaultName with | some cinfo@(ConstantInfo.defnInfo defVal) => do let mctx ← getMCtx let val? ← mkDefaultValue? struct cinfo match val? with | none => do setMCtx mctx; loop (i+1) (dist+1) | some val => do let val ← reduce allStructNames val match val.find? fun e => (defaultMissing? e).isSome with | some _ => setMCtx mctx; loop (i+1) (dist+1) | none => let mvarDecl ← getMVarDecl mvarId let val ← ensureHasType mvarDecl.type val assignExprMVar mvarId val pure true | _ => loop (i+1) dist else pure false loop 0 0 partial def step (struct : Struct) : M Unit := unless (← isRoundDone) do withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do for field in struct.fields do match field.val with | FieldVal.nested struct => step struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => unless (← isExprMVarAssigned mvarId) do let ctx ← read if (← withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then modify fun s => { s with progress := true } | _ => pure () partial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do match findDefaultMissing? (← getMCtx) struct with | none => pure () -- Done | some field => if d > hierarchyDepth then throwErrorAt! field.ref "field '{getFieldName field}' is missing" else withReader (fun ctx => { ctx with maxDistance := d }) do modify fun s => { s with progress := false } step struct if (← get).progress then do propagateLoop hierarchyDepth 0 struct else propagateLoop hierarchyDepth (d+1) struct def propagate (struct : Struct) : TermElabM Unit := let hierarchyDepth := getHierarchyDepth struct let structNames := collectStructNames struct #[] (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {} end DefaultFields private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do let structName ← getStructName stx expectedType? source unless isStructureLike (← getEnv) structName do throwError! "invalid \{...} notation, '{structName}' is not a structure" match mkStructView stx structName source with | Except.error ex => throwError ex | Except.ok struct => let struct ← expandStruct struct trace[Elab.struct]! "{struct}" let (r, struct) ← elabStruct struct expectedType? DefaultFields.propagate struct pure r @[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do match (← expandNonAtomicExplicitSource stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let sourceView ← getStructSource stx match (← isModifyOp? stx), sourceView with | some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType? | some _, _ => throwError "invalid {...} notation, explicit source is required when using '[<index>] := <value>'" | _, _ => elabStructInstAux stx expectedType? sourceView builtin_initialize registerTraceClass `Elab.struct end Lean.Elab.Term.StructInst
aa06606f53439a4d61ec6c31384e079ade717da6
ea6a4a10943d0b1966364cc23dbea151403b12cb
/src/examples.lean
2c4bab85f957c38063d3ea91204b1302529b870f
[]
no_license
cipher1024/transport
4ec290275f540261dd6ae86247eecc99abe0218a
147a1ba17c1e4c0b19b7625a1a70f87458a7f705
refs/heads/master
1,584,163,354,251
1,530,778,876,000
1,530,778,876,000
131,463,521
0
0
null
null
null
null
UTF-8
Lean
false
false
985
lean
import transport open tactic tactic.interactive meta def isolate {α} (tac : tactic α) : tactic unit := do e ← get_env, tac, set_env e -- set_option profiler true -- run_cmd do -- mk_transportable_instance `group -- run_cmd do -- mk_transportable_instance `monoid -- run_cmd do -- mk_transportable_instance `ring -- run_cmd do -- mk_transportable_instance `field -- run_cmd do -- mk_to_fun `group -- run_cmd do -- mk_to_fun `monoid -- set_option pp.notation false set_option trace.app_builder true -- run_cmd do -- mk_to_fun `ring run_cmd do mk_to_fun `field -- run_cmd do -- mk_to_fun `group >>= mk_on_equiv `group -- run_cmd do -- mk_to_fun `monoid >>= mk_on_equiv `monoid -- run_cmd do -- mk_to_fun `ring >>= mk_on_equiv `ring -- run_cmd do -- mk_to_fun `field >>= mk_on_equiv `field -- attribute [derive transportable] group -- attribute [derive transportable] monoid -- attribute [derive transportable] ring -- attribute [derive transportable] field
c81eecf017f76366a6b964b286d74c2628632799
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/simpZetaFalse.lean
e4a92a94bfdbdc83f47c4e81c6f5e288a0b44944
[ "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
918
lean
opaque f : Nat → Nat axiom f_eq (x : Nat) : f (f x) = x theorem ex1 (x : Nat) (h : f (f x) = x) : (let y := x*x; if f (f x) = x then 1 else y + 1) = 1 := by simp (config := { zeta := false }) only [h] trace_state simp #print ex1 -- uses let_congr theorem ex2 (x z : Nat) (h : f (f x) = x) (h' : z = x) : (let y := f (f x); y) = z := by simp (config := { zeta := false }) only [h] trace_state simp [h'] #print ex2 -- uses let_val_congr theorem ex3 (x z : Nat) : (let α := Nat; (fun x : α => 0 + x)) = id := by simp (config := { zeta := false, failIfUnchanged := false }) trace_state -- should not simplify let body since `fun α : Nat => fun x : α => 0 + x` is not type correct simp [id] theorem ex4 (p : Prop) (h : p) : (let n := 10; fun x : { z : Nat // z < n } => x = x) = fun z => p := by simp (config := { zeta := false }) trace_state simp [h] #print ex4 -- uses let_body_congr
a6c0ba70deb8d1f5f6f05fde5b773b0afc74214c
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/primes.lean
30838c747b8164ddf30afdd8a92bfb5c70de0c22
[]
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
18,167
lean
import data.nat.prime import tactic.norm_num import data.nat.gcd open nat definition is_prime : nat → Prop | zero := false | (succ zero) := false | (succ(succ x)) := ¬∃b c:nat,2≤b ∧ 2≤c ∧ b*c=succ(succ x) definition product : list nat → nat | list.nil := 1 | (n::L) := n * product L theorem product_append: ∀L M:list nat,product L*product M=product (L ++ M):=begin assume L, induction L with h L1 HiL, unfold product append list.append, assume M, rw one_mul, assume M1, have H2:product L1 * product (h::M1) = product (L1 ++ (h::M1)):=HiL (h::M1), clear HiL,revert H2, unfold product append list.append, rw[←mul_assoc, mul_comm (product L1) h], assume H,rw H,clear H, induction L1 with h1 L2 HiL1, unfold list.append product, unfold list.append product, rw [HiL1,←mul_assoc,←mul_assoc, mul_comm h h1], end theorem prime_eq :∀ p, is_prime p ↔ prime p:=begin intro, cases p with p, unfold is_prime prime,norm_num, cases p with p, unfold is_prime prime,norm_num,exact dec_trivial, unfold prime is_prime, apply iff.intro, assume H,apply and.intro, exact dec_trivial, assume p1 H3, have H4:=exists_eq_mul_right_of_dvd H3, apply exists.elim H4, assume c Hc, cases c with c, exfalso,revert Hc,exact dec_trivial, cases c with c, revert Hc,norm_num,rw eq_comm,cc, cases classical.em(p1=1),left,assumption, have H5:∃ (b c : ℕ), 2 ≤ b ∧ 2 ≤ c ∧ b * c = succ (succ p):=begin existsi (succ(succ c)),existsi p1, have H6:2 ≤ succ (succ c)↔true:=dec_trivial, rw H6,simp,rw Hc,simp, cases p1 with p1, revert Hc,norm_num,exact succ_ne_zero (succ p), cases p1 with p1, revert a,norm_num,exact dec_trivial, end,exfalso,exact H H5, assume Hp Hexists, apply exists.elim Hexists,assume b Hb, apply exists.elim Hb,assume c Hbc,clear Hb Hexists, apply and.elim Hbc,assume Hb Hc1,clear Hbc, apply and.elim Hc1, assume Hc Hbc,clear Hc1,apply and.elim Hp,clear Hp, assume H1 Hp, have H3:=Hp c, have H4:= dvd_of_mul_left_eq b Hbc, have H5:= H3 H4, have H6:c=1↔false:=begin apply iff.intro, assume Ht,revert Hc,rw Ht,norm_num, end,revert H5,rw H6,simp, assume Hc,rw Hc at Hbc, cases b with b,revert Hb,exact dec_trivial, cases b with b,revert Hb,exact dec_trivial, revert Hbc,simp,rw mul_succ,norm_num,rw[mul_comm,mul_succ],assume Hbc, have H7:succ (succ p) + (succ (succ p) * b + succ (succ p)) = succ (succ p)+0:=begin rw Hbc, end, have H8:(succ (succ p) * b + succ (succ p))=0:=add_left_cancel H7, revert H8,rw[add_comm,succ_add],apply succ_ne_zero, end theorem prime_product: ∀x:ℕ,1≤x→∃L:list ℕ,(∀p:ℕ,p ∈ L→prime p)∧product L=x:=begin have Hstrong:∀ x y:ℕ,x≤y→1≤x→∃L:list ℕ,(∀p:ℕ,p ∈ L→prime p)∧product L=x:=begin assume x y, revert x, induction y with y Hiy, assume x Hxy Hx1, have Hx:=eq_zero_of_le_zero Hxy,revert Hx1,rw Hx,norm_num, assume x Hxy H1x, cases x with x,revert H1x,norm_num, cases x with x, existsi list.nil, unfold list.mem product,simp, cases classical.em(prime (succ(succ x))) with Hx Hx1, existsi ([succ(succ x)]), unfold list.mem product,simp,assumption, rw ←prime_eq at Hx1,unfold is_prime at Hx1, have A:∃ (b c : ℕ), 2 ≤ b ∧ 2 ≤ c ∧ b * c = succ (succ x):=begin revert Hx1,cc, end,clear Hx1, apply exists.elim A, assume b Hb,clear A, apply exists.elim Hb, assume c Hbc1,clear Hb, have Hb:=and.elim_left Hbc1, have Hc:=and.elim_left(and.elim_right Hbc1), have Hbc:=and.elim_right(and.elim_right Hbc1),clear Hbc1, have Hbx:b<succ(succ x),{rw[←Hbc,mul_comm,lt_mul_iff_one_lt_left],exact lt_of_succ_le Hc,cases b,revert Hb,norm_num,exact dec_trivial}, have Hcx:c<succ(succ x),{rw[←Hbc,lt_mul_iff_one_lt_left],exact lt_of_succ_le Hb,cases c,revert Hc,norm_num,exact dec_trivial}, have Hxy1:succ x≤y:=by rwa ←succ_le_succ_iff,clear Hxy, have Hbx1:b≤succ x:=begin rw ←succ_le_succ_iff,apply succ_le_of_lt,assumption end, have Hcx1:c≤succ x:=begin rw ←succ_le_succ_iff,apply succ_le_of_lt,assumption end, have Hby:=le_trans Hbx1 Hxy1, have Hcy:=le_trans Hcx1 Hxy1, have H12:1≤2:=dec_trivial, have H1b:=le_trans H12 Hb, have H1c:=le_trans H12 Hc, clear H12 Hcx1 Hbx1 Hxy1 Hcx Hbx Hb Hc H1x, apply exists.elim (Hiy b Hby H1b),assume Lb HLb, apply exists.elim (Hiy c Hcy H1c),assume Lc HLc,clear Hiy H1b H1c Hby Hcy, have HLb1:=and.elim_left HLb,have HLb2:=and.elim_right HLb,clear HLb, have HLc1:=and.elim_left HLc,have HLc2:=and.elim_right HLc,clear HLc, existsi(Lb ++ Lc), apply and.intro,rw[←Hbc,←HLb2,←HLc2,eq_comm], exact product_append Lb Lc, norm_num, assume p H, cases H with A A, exact HLb1 p A, exact HLc1 p A, end, assume x, exact Hstrong x x (le_refl x), end def euclid_r: int→int→nat→int | a b 0 := b | a b 1 := a%b | a b (n+2) := euclid_r a b n % euclid_r a b (succ n) def euclid_q: int→int→nat→int | a b 0 := 0 | a b 1 := -(a/b) | a b (n+2) := euclid_r a b n / euclid_r a b (succ n) def euclid_x: int→int→nat→int | a b 0 := 0 | a b 1 := 1 | a b (n+2) := euclid_x a b n - euclid_q a b (succ (succ n)) * euclid_x a b (succ n) def euclid_y: int→int→nat→int | a b 0 := 1 | a b 1 := euclid_q a b 1 | a b (n+2) := euclid_y a b n - euclid_q a b (succ (succ n)) * euclid_y a b (succ n) open int theorem pos_mod:∀ a b:int,a%b≥ 0:=sorry theorem int_mod_lt: ∀ b c:int, c≠ 0→ b%c<abs(c):=int.mod_lt theorem decreasing_r: ∀ (b c:int) (n:ℕ),abs(euclid_r b c (n+1))<abs(euclid_r b c n) ∨ ∃m,m≤n+1∧euclid_r b c m = 0 :=begin assume b c n, induction n with n1 Hin, unfold euclid_r, cases classical.em(c=0) with A A, right,existsi 0,unfold euclid_r, rw A,simp,exact dec_trivial,left, rw abs_of_nonneg (pos_mod b c), exact int_mod_lt b c A, unfold euclid_r,rw ←add_one, cases classical.em (∃ (m : ℕ), m ≤ n1 + 1 ∧ euclid_r b c m = 0) with A A, right,apply exists.elim A,assume m Hm,existsi m, apply and.intro, exact le_trans (and.elim_left Hm) (le_add_right (n1+1) 1), exact and.elim_right Hm, cases classical.em(euclid_r b c (n1 + 1)=0) with A A, right, existsi n1+1,apply and.intro,norm_num, assumption,left, rw abs_of_nonneg (pos_mod(euclid_r b c n1)(euclid_r b c (n1 + 1))), apply int_mod_lt,exact A, end --use size_of not abs theorem gcd_exists:∀ b c :int, ∃ n:nat, euclid_r b c (succ n) = 0:=begin assume b c , have H:∀ n:nat,(∀ m:nat,m≤n→¬euclid_r b c m = 0)→abs (euclid_r b c n)≤abs c-n:=begin assume n Hn, induction n with n1 Hin, unfold euclid_r,norm_num, have Hn1:∀ (m : ℕ), m ≤ n1 → ¬euclid_r b c m = 0:=begin assume m Hm, have H:=le_trans Hm (le_succ n1), exact Hn m H, end, have Hin1:=Hin Hn1,clear Hin, have H1:=decreasing_r b c n1, have H3:∀ (m : ℕ),¬( m ≤succ n1 ∧ euclid_r b c m = 0):=begin assume m,rw not_and,exact Hn m, end, have H2:¬∃ (m : ℕ), m ≤ succ n1 ∧ euclid_r b c m = 0:=not_exists_of_forall_not H3, have H4:(∃ (m : ℕ), m ≤ succ n1 ∧ euclid_r b c m = 0)↔false:=begin apply iff.intro,exact H2,trivial, end,rw H4 at H1,simp at H1,clear H4 H2 H3, have H2:= lt_of_lt_of_le H1 Hin1, have H3:= add_one_le_of_lt H2, have H4:abs c - ↑n1=(abs c -↑n1-1)+1:=begin rw sub_add_cancel, end, rw H4 at H3, have H5:=le_of_add_le_add_right H3,revert H5,norm_num, end, cases classical.em (∃m:nat,↑m≤abs c ∧ euclid_r b c m = 0) with A A, have H1 end open nat theorem quotients :∀(c b:int) n:nat, euclid_r c b n -euclid_q c b (succ(succ n)) * euclid_r c b (succ n) = euclid_r c b (succ (succ n)):=begin assume c b n, unfold euclid_q euclid_r, rw int.mod_def,norm_num, end theorem almost_bezout: ∀ (c b:int) n:nat, euclid_x c b n * c + euclid_y c b n * b = euclid_r c b n:=begin -- semi strong induction, need previous two cases have Hi:∀(c b:int) n:nat,euclid_x c b n * c + euclid_y c b n * b = euclid_r c b n ∧ euclid_x c b (succ n) * c + euclid_y c b (succ n) * b = euclid_r c b (succ n):=begin assume c b n, induction n with n1 Hin2, apply and.intro, unfold euclid_x euclid_y euclid_r,simp, unfold euclid_x euclid_y euclid_r euclid_q,rw int.mod_def,simp, have Hin:=and.elim_left Hin2, have Hin1:=and.elim_right Hin2,clear Hin2, apply and.intro,assumption, unfold euclid_x euclid_y, rw ←quotients c b n1, have H1:(euclid_x c b n1 - euclid_q c b (succ (succ n1)) * euclid_x c b (succ n1)) * c=euclid_x c b n1 *c - euclid_q c b (succ (succ n1)) * euclid_x c b (succ n1)*c:=begin norm_num,rw mul_add,norm_num,end, have H2:(euclid_y c b n1 - euclid_q c b (succ (succ n1)) * euclid_y c b (succ n1)) * b=euclid_y c b n1 *b - euclid_q c b (succ (succ n1)) * euclid_y c b (succ n1)*b:=begin norm_num,rw mul_add,norm_num,end, rw [H1,H2],clear H1 H2, have H1:=calc euclid_x c b n1 * c - euclid_q c b (succ (succ n1)) * euclid_x c b (succ n1) * c + (euclid_y c b n1 * b - euclid_q c b (succ (succ n1)) * euclid_y c b (succ n1) * b)=euclid_x c b n1 * c - euclid_q c b (succ (succ n1)) * euclid_x c b (succ n1) * c + euclid_y c b n1 * b - euclid_q c b (succ (succ n1)) * euclid_y c b (succ n1) * b:by norm_num ...=euclid_x c b n1 * c + euclid_y c b n1 * b - euclid_q c b (succ (succ n1)) * euclid_y c b (succ n1) * b-euclid_q c b (succ (succ n1)) * euclid_x c b (succ n1)*c:by norm_num ...=euclid_r c b n1 -euclid_q c b (succ (succ n1)) * euclid_y c b (succ n1) * b-euclid_q c b (succ (succ n1)) * euclid_x c b (succ n1)*c:by rw ←Hin ...=euclid_r c b n1 + (-euclid_q c b (succ (succ n1)) * (euclid_y c b (succ n1) * b) + -euclid_q c b (succ (succ n1)) * (euclid_x c b (succ n1)*c)):by norm_num, rw H1, have H2:=mul_add (-euclid_q c b (succ (succ n1))) (euclid_y c b (succ n1) * b) (euclid_x c b (succ n1)*c),rw ←H2, rw ←Hin1,norm_num, end, assume c b n, exact and.elim_left (Hi c b n), end theorem int_dvd_mod_iff: ∀ (b c d:int), b ∣ d → (b ∣ (c % d) ↔ b ∣ c) :=begin assume b c d Hbd, apply iff.intro, rw int.mod_def, have H1:c=c-(d * (c / d))+(d * (c / d)):=by norm_num, intros,rw H1, exact dvd_add a (dvd_mul_of_dvd_left Hbd (c/d)), assume H1, rw int.mod_def, exact dvd_sub H1 (dvd_mul_of_dvd_left Hbd (c/d)), end theorem cd_dvd_r:∀ (b c x:int), x ∣ b → x∣c→∀ n:nat, x∣euclid_r b c n:=begin assume b c x Hb Hc n, have Hi:x ∣ euclid_r b c n∧x ∣ euclid_r b c (succ n):=begin induction n with n1 Hin, unfold euclid_r,apply and.intro, assumption, exact iff.elim_right (int_dvd_mod_iff x b c Hc) Hb, unfold euclid_r, exact and.intro (and.elim_right Hin) (iff.elim_right (int_dvd_mod_iff x (euclid_r b c n1) (euclid_r b c (succ n1)) (and.elim_right Hin)) (and.elim_left Hin)), end, exact and.elim_left Hi, end def gcd1: int→int→int→Prop | a b n:= n∣a ∧ n ∣ b ∧ (∀ e : int,e∣a→ e∣b → e∣n) theorem gcd_euclid: ∀ (b c:int) (n:nat), euclid_r b c (n+1)=0→gcd1 b c (euclid_r b c n):=begin have quotients_mod: ∀ (b c:int) (n:nat), euclid_r b c n= euclid_q b c (succ (succ n)) * euclid_r b c(succ n) +euclid_r b c (succ (succ n)):=begin assume b c n, rw ←quotients,norm_num, end, have Hi:∀ (b c:int) (n:nat), euclid_r b c (succ(succ n))=0→(∀ k:nat,k≤n→euclid_r b c (succ n) ∣ euclid_r b c (n-k)∧euclid_r b c (succ n) ∣ euclid_r b c (succ(n-k))):=begin assume b c n H, unfold euclid_r at H, have H2:=int.dvd_of_mod_eq_zero H, assume k Hkn, induction k with k1 Hik, simp,assumption, have Hik3:=Hik ( le_trans (le_succ k1) Hkn),clear Hik, have Hik1:= and.elim_left Hik3, have Hik2:=and.elim_right Hik3,clear Hik3, have Hsucc:(nat.succ (n - succ k1))=n-k1:=sorry, apply and.intro, rw quotients_mod b c (n- succ k1), rw Hsucc, exact dvd_add (dvd_mul_of_dvd_right Hik1 (euclid_q b c (succ (n - k1)))) Hik2, rw Hsucc,assumption, end, assume b c n Hn, have H1:euclid_r b c n ∣ c:=begin cases n with n1, unfold euclid_r,exact dvd_refl c,rw add_one at Hn, have Hi1:= Hi b c n1 Hn n1 (le_refl n1), have H1:n1-n1=0:=nat.sub_self n1, rw H1 at Hi1, unfold euclid_r at Hi1, exact and.elim_left Hi1, end, have H2:euclid_r b c n ∣ (b%c):=begin cases n with n1, unfold euclid_r,unfold euclid_r at Hn,rw Hn, exact dvd_zero c, cases n1 with n2, unfold euclid_r,exact dvd_refl (b%c), have Hi1:= Hi b c (succ n2) Hn n2, have H1:nat.succ n2-n2=1:=begin rw ←zero_add 1,have H2:=nat.sub_self n2,rw[←H2,add_one],exact succ_sub (le_refl n2), end, rw H1 at Hi1, have H3: euclid_r b c 1 =b%c:=by unfold euclid_r, rw ←H3,exact and.elim_left (Hi1 (le_succ n2)), end, unfold gcd1, apply and.intro, exact iff.elim_left (int_dvd_mod_iff (euclid_r b c n) b c H1) H2, apply and.intro,assumption, assume x Hb Hc, exact cd_dvd_r b c x Hb Hc n, end theorem bezout: ∀ b c d:int, gcd1 b c d→ ∃ x y:ℤ, x *b + y*c = d:=begin assume b c n Hn, apply exists.elim (gcd_exists b c), existsi euclid_x b c n, existsi euclid_y b c n, existsi euclid_r b c n, rw ←add_one at Hn, apply and.intro, exact almost_bezout b c n, exact gcd_euclid b c n Hn, end def int_prime : int→Prop | p := abs p ≠ 1 ∧ ∀ x:int, x∣p → abs x=1 ∨ abs x = p open int #eval int.sizeof (0:int) theorem gcdprime:∀ p x:int, int_prime p → ∀ d, gcd1 x p d → d=1 ∨ d=p:=sorry theorem euclids_lemma: ∀b c p:int, int_prime p→p ∣ (b*c) → p ∣ b ∨ p ∣ c:=sorry def product_int :list int → int | list.nil := 1 | (p::L) := p* product_int L theorem int_prime_product: ∀ x:int,∃ L:list int,(∀ p:int,p ∈ L → int_prime p)∧product_int L = x:=sorry def count: int → (list int) → nat | n [] :=0 | n (a::l):= if abs a=abs n then (succ (count n l)) else (count n l) theorem product_dvd: ∀ (p:int) (L:list int),p ∈ L→ p ∣ product_int L:=sorry theorem unique_prime_factorization: ∀ (x :int) (A : list int),((∀ p:int,p ∈ A → int_prime p)∧product_int A = x)→(∀ B:list int,((∀ p:int,p ∈ B → int_prime p)∧product_int B = x)→ ∀ p:int,count p A = count p B):=begin assume x A HA,revert x, induction A with pA A1 HiA, norm_num,unfold product_int count,assume B HB, admit, assume x1 HA1, have H2:∀ p,p ∈ pA :: A1↔p=pA∨p∈A1:=begin norm_num, end, have H1:(∀ (p : ℤ), p ∈ A1 → int_prime p):=begin assume p H1, have H:=and.elim_left HA1 p,rw (H2 p) at H, exact H (or.intro_right (p=pA) H1), end, have HiA3:=HiA (product_int A1) (and.intro H1 (by trivial)),clear HiA, assume B HB, cases B with pB B1, unfold product_int at HB, have Hx1:=and.elim_right HB,clear HB, have HA2:=and.elim_right HA1,exfalso,revert HA2, rw ←Hx1,unfold product_int,admit, have H2B:∀ p,p ∈ pB :: B1↔p=pB∨p∈B1:=begin norm_num, end, have H1B:(∀ (p : ℤ), p ∈ B1 → int_prime p):=begin assume p H1, have H:=and.elim_left HB p,rw (H2B p) at H, exact H (or.intro_right (p=pB) H1), end, cases classical.em (pA∣pB) with A A, have H1:abs(pA)=abs(pB):=sorry, unfold count,admit, end open nat def nat_count: nat → (list nat) → nat | n [] :=0 | n (a::l):= if a=n then (succ (nat_count n l)) else (nat_count n l) theorem unique_prime_factorization_nat: ∀ A B:list nat,product A=product B→(∀p:nat, p∈A→prime p)→(∀ p:nat,p∈ B→ prime p)→∀ p:nat,nat_count p A=nat_count p B:=begin assume A, induction A with pA A1 Hi, admit, assume B, cases B with pB B1, admit, cases classical.em(pA ∣ pB) with A B, have H1:pB = pA:=sorry, unfold product, have H2:product A1=product B1:=sorry, assume H3 H4 H5, have H6:(∀ (p : ℕ), p ∈ A1 → prime p):=sorry, have H7:(∀ (p : ℕ), p ∈ B1 → prime p):=sorry, have Hi2:=Hi B1 H2 H6 H7,rw H1, unfold nat_count,admit, unfold product, have H6:(∀ (p : ℕ), p ∈ A1 → prime p):=sorry, have H7:(∀ (p : ℕ), p ∈ B1 → prime p):=sorry, have H8:pA ∣ product B1:=sorry, have H9:pA ∈ B1:=sorry, have H10:∃ B2, pA :: B2 = pB :: B1:=sorry,intros, apply exists.elim H10,clear H10, assume B2 HB2, have H2:product A1=product B2:=sorry, have H3:∀p,p∈ B2→prime p:=sorry, have Hi2:= Hi B2 H2 H6 H3, rw ←HB2,unfold nat_count, cases classical.em (pA=p), rw a_3,norm_num,rw Hi2 p, have H2:pA=p↔false:=sorry,admit, end
8408043f3b81b655fac2c3a3dd4ef15d9edc992f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Match/MatchEqsExt.lean
68be6001ed566d587de8c2bbd8ed2450afda3fd6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,206
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean.Meta.Match structure MatchEqns where eqnNames : Array Name splitterName : Name splitterAltNumParams : Array Nat deriving Inhabited, Repr def MatchEqns.size (e : MatchEqns) : Nat := e.eqnNames.size structure MatchEqnsExtState where map : PHashMap Name MatchEqns := {} deriving Inhabited /- We generate the equations and splitter on demand, and do not save them on .olean files. -/ builtin_initialize matchEqnsExt : EnvExtension MatchEqnsExtState ← registerEnvExtension (pure {}) def registerMatchEqns (matchDeclName : Name) (matchEqns : MatchEqns) : CoreM Unit := modifyEnv fun env => matchEqnsExt.modifyState env fun s => { s with map := s.map.insert matchDeclName matchEqns } /- Forward definition. We want to use `getEquationsFor` in the simplifier, `getEquationsFor` depends on `mkEquationsfor` which uses the simplifier. -/ @[extern "lean_get_match_equations_for"] opaque getEquationsFor (matchDeclName : Name) : MetaM MatchEqns end Lean.Meta.Match
2534f4ec65f2213ab1a1e8eec742711449bf814f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/dynamics/minimal.lean
0f2dbe871cb8d27300c72fc18a698c8f8d0b2d8d
[ "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,047
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import group_theory.group_action.basic import topology.algebra.const_mul_action /-! # Minimal action of a group > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define an action of a monoid `M` on a topological space `α` to be *minimal* if the `M`-orbit of every point `x : α` is dense. We also provide an additive version of this definition and prove some basic facts about minimal actions. ## TODO * Define a minimal set of an action. ## Tags group action, minimal -/ open_locale pointwise /-- An action of an additive monoid `M` on a topological space is called *minimal* if the `M`-orbit of every point `x : α` is dense. -/ class add_action.is_minimal (M α : Type*) [add_monoid M] [topological_space α] [add_action M α] : Prop := (dense_orbit : ∀ x : α, dense (add_action.orbit M x)) /-- An action of a monoid `M` on a topological space is called *minimal* if the `M`-orbit of every point `x : α` is dense. -/ @[to_additive] class mul_action.is_minimal (M α : Type*) [monoid M] [topological_space α] [mul_action M α] : Prop := (dense_orbit : ∀ x : α, dense (mul_action.orbit M x)) open mul_action set variables (M G : Type*) {α : Type*} [monoid M] [group G] [topological_space α] [mul_action M α] [mul_action G α] @[to_additive] lemma mul_action.dense_orbit [is_minimal M α] (x : α) : dense (orbit M x) := mul_action.is_minimal.dense_orbit x @[to_additive] lemma dense_range_smul [is_minimal M α] (x : α) : dense_range (λ c : M, c • x) := mul_action.dense_orbit M x @[priority 100, to_additive] instance mul_action.is_minimal_of_pretransitive [is_pretransitive M α] : is_minimal M α := ⟨λ x, (surjective_smul M x).dense_range⟩ @[to_additive] lemma is_open.exists_smul_mem [is_minimal M α] (x : α) {U : set α} (hUo : is_open U) (hne : U.nonempty) : ∃ c : M, c • x ∈ U := (dense_range_smul M x).exists_mem_open hUo hne @[to_additive] lemma is_open.Union_preimage_smul [is_minimal M α] {U : set α} (hUo : is_open U) (hne : U.nonempty) : (⋃ c : M, (•) c ⁻¹' U) = univ := Union_eq_univ_iff.2 $ λ x, hUo.exists_smul_mem M x hne @[to_additive] lemma is_open.Union_smul [is_minimal G α] {U : set α} (hUo : is_open U) (hne : U.nonempty) : (⋃ g : G, g • U) = univ := Union_eq_univ_iff.2 $ λ x, let ⟨g, hg⟩ := hUo.exists_smul_mem G x hne in ⟨g⁻¹, _, hg, inv_smul_smul _ _⟩ @[to_additive] lemma is_compact.exists_finite_cover_smul [is_minimal G α] [has_continuous_const_smul G α] {K U : set α} (hK : is_compact K) (hUo : is_open U) (hne : U.nonempty) : ∃ I : finset G, K ⊆ ⋃ g ∈ I, g • U := hK.elim_finite_subcover (λ g : G, g • U) (λ g, hUo.smul _) $ calc K ⊆ univ : subset_univ K ... = ⋃ g : G, g • U : (hUo.Union_smul G hne).symm @[to_additive] lemma dense_of_nonempty_smul_invariant [is_minimal M α] {s : set α} (hne : s.nonempty) (hsmul : ∀ c : M, c • s ⊆ s) : dense s := let ⟨x, hx⟩ := hne in (mul_action.dense_orbit M x).mono (range_subset_iff.2 $ λ c, hsmul c $ ⟨x, hx, rfl⟩) @[to_additive] lemma eq_empty_or_univ_of_smul_invariant_closed [is_minimal M α] {s : set α} (hs : is_closed s) (hsmul : ∀ c : M, c • s ⊆ s) : s = ∅ ∨ s = univ := s.eq_empty_or_nonempty.imp_right $ λ hne, hs.closure_eq ▸ (dense_of_nonempty_smul_invariant M hne hsmul).closure_eq @[to_additive] lemma is_minimal_iff_closed_smul_invariant [has_continuous_const_smul M α] : is_minimal M α ↔ ∀ s : set α, is_closed s → (∀ c : M, c • s ⊆ s) → s = ∅ ∨ s = univ := begin split, { introsI h s, exact eq_empty_or_univ_of_smul_invariant_closed M }, refine λ H, ⟨λ x, dense_iff_closure_eq.2 $ (H _ _ _).resolve_left _⟩, exacts [is_closed_closure, λ c, smul_closure_orbit_subset _ _, (orbit_nonempty _).closure.ne_empty] end
9b5b26cae5a40c870b9633f280998f0bcf7e7d43
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/logic/decidable.lean
3c19f0bcadaa790902a93eb6b8eaa8287a86bd90
[ "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
4,036
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.connectives data.empty inductive decidable [class] (p : Prop) : Type := inl : p → decidable p, inr : ¬p → decidable p namespace decidable definition true_decidable [instance] : decidable true := inl trivial definition false_decidable [instance] : decidable false := inr not_false_trivial variables {p q : Prop} definition rec_on_true [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : p) (H4 : H1 H3) : rec_on H H1 H2 := rec_on H (λh, H4) (λh, false.rec _ (h H3)) definition rec_on_false [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : ¬p) (H4 : H2 H3) : rec_on H H1 H2 := rec_on H (λh, false.rec _ (H3 h)) (λh, H4) theorem irrelevant [instance] : subsingleton (decidable p) := subsingleton.intro (fun d1 d2, decidable.rec (assume Hp1 : p, decidable.rec (assume Hp2 : p, congr_arg inl (eq.refl Hp1)) -- using proof irrelevance for Prop (assume Hnp2 : ¬p, absurd Hp1 Hnp2) d2) (assume Hnp1 : ¬p, decidable.rec (assume Hp2 : p, absurd Hp2 Hnp1) (assume Hnp2 : ¬p, congr_arg inr (eq.refl Hnp1)) -- using proof irrelevance for Prop d2) d1) definition by_cases {q : Type} [C : decidable p] (Hpq : p → q) (Hnpq : ¬p → q) : q := rec_on C (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) theorem em (p : Prop) [H : decidable p] : p ∨ ¬p := by_cases (λ Hp, or.inl Hp) (λ Hnp, or.inr Hnp) theorem by_contradiction [Hp : decidable p] (H : ¬p → false) : p := by_cases (assume H1 : p, H1) (assume H1 : ¬p, false_elim (H H1)) definition and_decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (p ∧ q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (and.intro Hp Hq)) (assume Hnq : ¬q, inr (and.not_right p Hnq))) (assume Hnp : ¬p, inr (and.not_left q Hnp)) definition or_decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (p ∨ q) := rec_on Hp (assume Hp : p, inl (or.inl Hp)) (assume Hnp : ¬p, rec_on Hq (assume Hq : q, inl (or.inr Hq)) (assume Hnq : ¬q, inr (or.not_intro Hnp Hnq))) definition not_decidable [instance] (Hp : decidable p) : decidable (¬p) := rec_on Hp (assume Hp, inr (not_not_intro Hp)) (assume Hnp, inl Hnp) definition implies_decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (p → q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (assume H, Hq)) (assume Hnq : ¬q, inr (assume H : p → q, absurd (H Hp) Hnq))) (assume Hnp : ¬p, inl (assume Hp, absurd Hp Hnp)) definition iff_decidable [instance] (Hp : decidable p) (Hq : decidable q) : decidable (p ↔ q) := _ definition decidable_iff_equiv (Hp : decidable p) (H : p ↔ q) : decidable q := rec_on Hp (assume Hp : p, inl (iff.elim_left H Hp)) (assume Hnp : ¬p, inr (iff.elim_left (iff.flip_sign H) Hnp)) definition decidable_eq_equiv (Hp : decidable p) (H : p = q) : decidable q := decidable_iff_equiv Hp (eq_to_iff H) protected theorem rec_subsingleton [instance] [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : Π(h : p), subsingleton (H1 h)) (H4 : Π(h : ¬p), subsingleton (H2 h)) : subsingleton (rec_on H H1 H2) := rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases" end decidable definition decidable_pred {A : Type} (R : A → Prop) := Π (a : A), decidable (R a) definition decidable_rel {A : Type} (R : A → A → Prop) := Π (a b : A), decidable (R a b) definition decidable_eq (A : Type) := decidable_rel (@eq A) --empty cannot depend on decidable, so we prove this here protected definition empty.has_decidable_eq [instance] : decidable_eq empty := take (a b : empty), decidable.inl (!empty.elim a)
cee79d553feca7c9f896f2ee5680d9775e736a5f
4c630d016e43ace8c5f476a5070a471130c8a411
/set_theory/ordinal.lean
efa4751eaddc703dfe78538ea8f09f7df338af03
[ "Apache-2.0" ]
permissive
ngamt/mathlib
9a510c391694dc43eec969914e2a0e20b272d172
58909bd424209739a2214961eefaa012fb8a18d2
refs/heads/master
1,585,942,993,674
1,540,739,585,000
1,540,916,815,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
125,226
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Ordinal arithmetic. Ordinals are defined as equivalences of well-ordered sets by order isomorphism. -/ import order.order_iso set_theory.cardinal data.sum noncomputable theory open function cardinal local attribute [instance] classical.prop_decidable universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ≼o s := (init : ∀ a b, s b (to_order_embedding a) → ∃ a', to_order_embedding a' = b) local infix ` ≼i `:50 := initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ≼o s) := ⟨initial_seg.to_order_embedding⟩ @[simp] theorem coe_fn_mk (f : r ≼o s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_order_embedding (f : r ≼i s) : (f.to_order_embedding : α → β) = f := rfl theorem coe_coe_fn (f : r ≼i s) : ((f : r ≼o s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ≼o s).ord'.2 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ≼o s).ord'.1 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃o s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, order_iso.apply_inverse_apply f _⟩⟩ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨order_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ @[trans] protected def trans : r ≼i s → s ≼i t → r ≼i t | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ := ⟨f₁.trans f₂, λ a c h, begin simp at h ⊢, rcases o₂ _ _ h with ⟨b, rfl⟩, have h := f₂.ord'.2 h, rcases o₁ _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem of_iso_apply (f : r ≃o s) (x : α) : of_iso f x = f x := rfl @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply : ∀ (f : r ≼i s) (g : s ≼i t) (a : α), (f.trans g) a = g (f a) | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := order_embedding.trans_apply _ _ _ theorem unique_of_extensional [is_extensional β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact order_embedding.eq_of_to_fun_eq this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ≼o s).ord'.1 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ≼o s).ord'.1 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@order_embedding.well_founded _ _ r s a (is_well_order.wf s))) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f | x := begin have := ((is_well_order.wf r).apply x), induction this with x _ IH, refine @is_extensional.ext _ r _ _ _ (λ y, _), simp only [g.init_iff, f.init_iff], split; intro h, { rcases h with ⟨a, rfl, b, rfl, h⟩, rwa IH _ h }, { exact ⟨f y, IH _ h, y, rfl, h⟩ } end def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃o s := by haveI := f.to_order_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.ord⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := order_iso.eq_of_to_fun_eq rfl theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on ((is_well_order.wf s).apply b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨order_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl.symm⟩, λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ≼o s := (top : β) (down : ∀ b, s b top ↔ ∃ a, to_order_embedding a = b) local infix ` ≺i `:50 := principal_seg namespace principal_seg instance : has_coe (r ≺i s) (r ≼o s) := ⟨principal_seg.to_order_embedding⟩ @[simp] theorem coe_fn_mk (f : r ≼o s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_order_embedding (f : r ≺i s) : (f.to_order_embedding : α → β) = f := rfl theorem coe_coe_fn (f : r ≺i s) : ((f : r ≼o s) : α → β) = f := rfl theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b := f.down _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_order_embedding, λ a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := initial_seg.init_iff f theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end def lt_le [is_trans β s] (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@order_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, order_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := order_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl @[trans] protected def trans [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans β s] [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl def equiv_lt [is_trans β s] [is_trans γ t] (f : r ≃o s) (g : s ≺i t) : r ≺i t := ⟨@order_embedding.trans _ _ _ r s t f g, g.top, λ c, by simp only [g.down', coe_fn_coe_base, order_embedding.trans_apply]; exact ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, order_iso.apply_inverse_apply, order_iso.coe_coe_fn]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ @[simp] theorem equiv_lt_apply [is_trans β s] [is_trans γ t] (f : r ≃o s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := order_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top [is_trans β s] [is_trans γ t] (f : r ≃o s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (λ x, _), simp only [f.down, g.down, ef, coe_fn_to_order_embedding] }, cases f, cases g, have := order_embedding.eq_of_to_fun_eq ef; congr' end⟩ theorem top_eq [is_well_order β s] [is_well_order γ t] (e : r ≃o s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) [is_well_order α r] (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.order_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) [is_well_order α r] (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) [is_well_order α r] (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨order_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down'.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl end principal_seg def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : r ≺i s ⊕ r ≃o s := if h : surjective f then sum.inr (order_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ @[simp] theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) {g} (h : f.lt_or_eq = sum.inl g) (a : α) : g a = f a := begin unfold initial_seg.lt_or_eq at h, by_cases sj : surjective f, { rw dif_pos sj at h, cases h }, { rw dif_neg sj at h, cases h, refl } end @[simp] theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) {g} (h : f.lt_or_eq = sum.inr g) (a : α) : g a = f a := begin unfold initial_seg.lt_or_eq at h, by_cases sj : surjective f, {rw dif_pos sj at h, cases h, refl}, {rw dif_neg sj at h, cases h} end def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left h] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right h] } end namespace order_embedding def collapse_F [is_well_order β s] (f : r ≼o s) : Π a, {b // ¬ s (f a) b} := (order_embedding.well_founded f $ is_well_order.wf s).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.ord'.1 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.ord'.1 h, exact ⟨(is_well_order.wf s).min S (set.ne_empty_of_mem this), (is_well_order.wf s).not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ≼o s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ≼o s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding. -/ def collapse [is_well_order β s] (f : r ≼o s) : r ≼i s := by haveI := order_embedding.is_well_order f; exact ⟨order_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, acc.rec_on ((is_well_order.wf s).apply b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S ≠ ∅ := set.ne_empty_of_mem (asymm h), existsi (is_well_order.wf r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact (is_well_order.wf r).not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order β s] (f : r ≼o s) (a) : collapse f a = (collapse_F f a).1 := rfl end order_embedding section well_ordering_thm parameter {σ : Type*} private def partial_wo := Σ p : set σ, {r // is_well_order p r} private def partial_wo.le (x y : partial_wo) := ∃ f : x.2.1 ≼i y.2.1, ∀ x, (f x).1 = x.1 local infix ` ≤ `:50 := partial_wo.le private def partial_wo.is_refl : is_refl _ (≤) := ⟨λ a, ⟨initial_seg.refl _, λ x, rfl⟩⟩ local attribute [instance] partial_wo.is_refl private def partial_wo.trans {a b c} : a ≤ b → b ≤ c → a ≤ c | ⟨f, hf⟩ ⟨g, hg⟩ := ⟨f.trans g, λ a, by rw [initial_seg.trans_apply, hg, hf]⟩ private def sub_of_le {s t} : s ≤ t → s.1 ⊆ t.1 | ⟨f, hf⟩ x h := by have := (f ⟨x, h⟩).2; rwa [hf ⟨x, h⟩] at this private def agree_of_le {s t} : s ≤ t → ∀ {a b} sa sb ta tb, s.2.1 ⟨a, sa⟩ ⟨b, sb⟩ ↔ t.2.1 ⟨a, ta⟩ ⟨b, tb⟩ | ⟨f, hf⟩ a b sa sb ta tb := by rw [f.to_order_embedding.ord', show f.to_order_embedding ⟨a, sa⟩ = ⟨a, ta⟩, from subtype.eq (hf ⟨a, sa⟩), show f.to_order_embedding ⟨b, sb⟩ = ⟨b, tb⟩, from subtype.eq (hf ⟨b, sb⟩)] section parameters {c : set partial_wo} (hc : zorn.chain (≤) c) private def U := ⋃₀ ((λ x:partial_wo, x.1) '' c) private def R (x y : U) := ∃ a : partial_wo, a ∈ c ∧ ∃ (hx : x.1 ∈ a.1) (hy : y.1 ∈ a.1), a.2.1 ⟨_, hx⟩ ⟨_, hy⟩ private lemma mem_U {a} : a ∈ U ↔ ∃ s : partial_wo, s ∈ c ∧ a ∈ s.1 := by simp only [U, set.sUnion_image, set.mem_Union, exists_prop] private lemma mem_U2 {a b} (au : a ∈ U) (bu : b ∈ U) : ∃ s : partial_wo, s ∈ c ∧ a ∈ s.1 ∧ b ∈ s.1 := let ⟨s, sc, as⟩ := mem_U.1 au, ⟨t, tc, bt⟩ := mem_U.1 bu, ⟨k, kc, ks, kt⟩ := hc.directed sc tc in ⟨k, kc, sub_of_le ks as, sub_of_le kt bt⟩ private lemma R_ex {s : partial_wo} (sc : s ∈ c) {a b : σ} (hb : b ∈ s.1) {au bu} : R ⟨a, au⟩ ⟨b, bu⟩ → ∃ ha, s.2.1 ⟨a, ha⟩ ⟨b, hb⟩ | ⟨t, tc, at', bt, h⟩ := match hc.total_of_refl sc tc with | or.inr hr := ⟨sub_of_le hr at', (agree_of_le hr _ _ _ _).1 h⟩ | or.inl hr@⟨f, hf⟩ := begin rw [← show (f ⟨b, hb⟩) = ⟨(subtype.mk b bu).val, bt⟩, from subtype.eq (hf _)] at h, rcases f.init_iff.1 h with ⟨⟨a', ha⟩, e, h'⟩, have : a' = a, { have := congr_arg subtype.val e, rwa hf at this }, subst a', exact ⟨_, h'⟩ end end private lemma R_iff {s : partial_wo} (sc : s ∈ c) {a b : σ} (ha hb) {au bu} : R ⟨a, au⟩ ⟨b, bu⟩ ↔ s.2.1 ⟨a, ha⟩ ⟨b, hb⟩ := ⟨λ h, let ⟨_, h⟩ := R_ex sc hb h in h, λ h, ⟨s, sc, ha, hb, h⟩⟩ private theorem wo : is_well_order U R := { trichotomous := λ ⟨a, au⟩ ⟨b, bu⟩, let ⟨s, sc, ha, hb⟩ := mem_U2 au bu in (@trichotomous _ s.2.1 s.2.2.1.1 ⟨a, ha⟩ ⟨b, hb⟩).imp (R_iff sc _ _).2 (λ o, o.imp (subtype.eq ∘ subtype.mk.inj) (R_iff sc _ _).2), irrefl := λ ⟨a, au⟩ h, let ⟨s, sc, ha⟩ := mem_U.1 au in -- by haveI := s.2.2; exact irrefl _ ((R_iff hc sc _ ha).1 h), @irrefl _ s.2.1 s.2.2.1.2.1 _ ((R_iff sc _ ha).1 h), trans := λ ⟨a, au⟩ ⟨b, bu⟩ ⟨d, du⟩ ab bd, let ⟨s, sc, as, bs⟩ := mem_U2 au bu, ⟨t, tc, dt⟩ := mem_U.1 du, ⟨k, kc, ks, kt⟩ := hc.directed sc tc in begin simp only [R_iff hc kc, sub_of_le ks as, sub_of_le ks bs, sub_of_le kt dt] at ab bd ⊢, -- haveI := k.2.2, exact trans ab bd exact @trans _ k.2.1 k.2.2.1.2.2 _ _ _ ab bd end, wf := ⟨λ ⟨a, au⟩, let ⟨s, sc, ha⟩ := mem_U.1 au in suffices ∀ (a : s.1) (au : a.1 ∈ U), acc R ⟨a.1, au⟩, from this ⟨a, ha⟩ au, λ a, acc.rec_on ((@is_well_order.wf _ _ s.2.2).apply a) $ λ ⟨a, ha⟩ H IH au, ⟨_, λ ⟨b, hb⟩ h, let ⟨hb, h⟩ := R_ex sc ha h in IH ⟨b, hb⟩ h _⟩⟩ } theorem chain_ub : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨⟨U, R, wo⟩, λ s sc, ⟨⟨⟨⟨ λ a, ⟨a.1, mem_U.2 ⟨s, sc, a.2⟩⟩, λ a b h, subtype.eq $ subtype.mk.inj h⟩, λ a b, by cases a with a ha; cases b with b hb; exact (R_iff hc sc _ _).symm⟩, λ ⟨a, ha⟩ ⟨b, hb⟩ h, let ⟨bs, h'⟩ := R_ex sc ha h in ⟨⟨_, bs⟩, rfl⟩⟩, λ a, rfl⟩⟩ end theorem well_ordering_thm : ∃ r, is_well_order σ r := let ⟨m, MM⟩ := zorn.zorn (λ c, chain_ub) (λ a b c, partial_wo.trans) in suffices hf : ∀ a, a ∈ m.1, from let f : σ ≃ m.1 := ⟨λ a, ⟨a, hf a⟩, λ a, a.1, λ a, rfl, λ ⟨a, ha⟩, rfl⟩ in ⟨order.preimage f m.2.1, @order_embedding.is_well_order _ _ _ _ (order_iso.preimage f m.2.1 : f ⁻¹'o m.2.1 ≼o m.2.1) m.2.2⟩, λ a, classical.by_contradiction $ λ ha, let f : (insert a m.1 : set σ) ≃ (m.1 ⊕ unit) := ⟨λ x, if h : x.1 ∈ m.1 then sum.inl ⟨_, h⟩ else sum.inr ⟨⟩, λ x, sum.cases_on x (λ x, ⟨x.1, or.inr x.2⟩) (λ _, ⟨a, or.inl rfl⟩), λ x, match x with | ⟨_, or.inl rfl⟩ := by dsimp only; rw dif_neg ha | ⟨x, or.inr h⟩ := by dsimp only; rw dif_pos h end, λ x, by rcases x with ⟨x, h⟩ | ⟨⟨⟩⟩; dsimp only; [rw [dif_pos h], rw [dif_neg ha]]⟩ in let r' := sum.lex m.2.1 (@empty_relation unit) in have r'wo : is_well_order _ r' := @sum.lex.is_well_order _ _ _ _ m.2.2 _, let m' : partial_wo := ⟨insert a m.1, order.preimage f r', @order_embedding.is_well_order _ _ _ _ ↑(order_iso.preimage f r') r'wo⟩ in let g : m.2.1 ≼i r' := ⟨⟨⟨sum.inl, λ a b, sum.inl.inj⟩, λ a b, sum.lex_inl_inl.symm⟩, λ a b h, begin rcases b with b | ⟨⟨⟩⟩, { exact ⟨_, rfl⟩ }, { cases sum.lex_inr_inl h } end⟩ in ha (sub_of_le (MM m' ⟨g.trans (initial_seg.of_iso (order_iso.preimage f r').symm), λ x, rfl⟩) (or.inl rfl)) end well_ordering_thm structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃o s), iseqv := ⟨λ⟨α, r, _⟩, ⟨order_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, quotient by order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : α → α → Prop) [wo : is_well_order α r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃o s) := quotient.eq @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl instance : partial_order ordinal := { le := (≤), lt := (<), le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨order_iso.of_surjective (order_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.cod_restrict _ ((subrel.order_embedding _ _).trans f) (λ ⟨x, h⟩, by rw [order_embedding.trans_apply]; exact f.to_order_embedding.ord'.1 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_order_embedding.ord'.2 h⟩, subtype.eq $ order_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := ⟨λ h, ((@trichotomous _ r _ a b) .resolve_left (λ hn, ne_of_lt ((typein_lt_typein r).2 hn) h)) .resolve_right (λ hn, ne_of_gt ((typein_lt_typein r).2 hn) h), congr_arg _⟩ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (order_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein theorem enum_lt {α β} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order α r] [is_well_order β s] [is_well_order γ t] (h₁ : type s < type r) (h₂ : type t < type r) : r (enum r (type s) h₁) (enum r (type t) h₂) ↔ type s < type t := by rw [← typein_lt_typein r, typein_enum, typein_enum] theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (λ ⟨α, r, _⟩, mk α) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = mk α := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨equiv.empty_equiv_pempty.symm, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, ⟨⟨⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim, λ a, a.elim⟩, λ a, a.elim⟩⟩ @[simp] theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := by simp only [le_antisymm_iff, zero_le, and_true] theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := by simp only [lt_iff_le_and_ne, zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨equiv.punit_equiv_punit, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl instance : has_add ordinal.{u} := ⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨order_iso.sum_lex_congr f g⟩⟩ @[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩, λ _ _, sum.lex_inl_inl.symm⟩, sum.inr punit.star, λ b, sum.rec_on b (λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _ _ _⟩) (λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_pos (o : ordinal) : 0 < succ o := lt_of_le_of_lt (zero_le _) (lt_succ_self _) theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@order_embedding.of_monotone (α ⊕ punit) β _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.ord'.1 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [succ, card_add, card_one] @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(equiv.pempty_sum α).symm, λ a b, sum.lex_inr_inr.symm⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(equiv.sum_pempty α).symm, λ a b, sum.lex_inl_inl.symm⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨equiv.sum_assoc _ _ _, λ a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [equiv.sum_assoc_apply_in1, equiv.sum_assoc_apply_in2, equiv.sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ 0 = 1 := zero_add _ theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_congr f, λ a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, λ a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa only [add_zero] using add_le_add_left (zero_le b) a theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c := ⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨ have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a, by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply] using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂) ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a, have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2, ⟨⟨⟨g, λ x y h, by injection f.inj (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, λ a b, by simpa only [sum.lex_inr_inr, fr, order_embedding.coe_fn_to_embedding, initial_seg.coe_fn_to_order_embedding, function.embedding.coe_fn_mk] using @order_embedding.ord _ _ _ _ f.to_order_embedding (sum.inr a) (sum.inr b)⟩, λ a b H, begin rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩, { rw fl at h, cases h }, { rw fr at h, exact ⟨a', sum.inr.inj h⟩ } end⟩⟩, λ h, add_le_add_left h _⟩ theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp only [le_antisymm_iff, add_le_add_iff_left] /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. -/ def lift (o : ordinal.{u}) : ordinal.{max u v} := quotient.lift_on o (λ ⟨α, r, wo⟩, @type _ _ (@order_embedding.is_well_order _ _ (@equiv.ulift.{u v} α ⁻¹'o r) r (order_iso.preimage equiv.ulift.{u v} r) wo)) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(order_iso.preimage equiv.ulift r).trans $ f.trans (order_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] : ∃ wo', lift (type r) = @type _ (@equiv.ulift.{u v} α ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(order_iso.preimage equiv.ulift r).trans (order_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨order_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := induction_on a $ λ α r _, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans $ (order_iso.preimage equiv.ulift _).trans (order_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) ≤ lift.{v (max u w)} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃o s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).symm.trans $ f.trans (order_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).trans $ f.trans (order_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r ≺i s) := by haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{u (max v w)} α ⁻¹'o r) r (order_iso.preimage equiv.ulift.{u (max v w)} r) _; haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{v (max u w)} β ⁻¹'o s) s (order_iso.preimage equiv.ulift.{v (max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans ⟨equiv.pempty_equiv_pempty, λ a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans ⟨equiv.punit_equiv_punit, λ a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans (order_iso.sum_lex_congr (order_iso.preimage equiv.ulift _) (order_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by unfold succ; simp only [lift_add, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (mk β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := order_iso.preimage f s, haveI := g.to_order_embedding.is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼o s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c := induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hr₂ hs)).2 ⟨⟨embedding.sum_congr f (embedding.refl _), λ a b, begin split; intro H, { cases H; constructor; [rwa ← fo, assumption] }, { cases a with a a; cases b with b b; cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa only [zero_add] using add_le_add_right (zero_le b) a theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ h₂ end instance : decidable_linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c := lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _) @[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b := by rw [lt_succ, succ_le] @[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 succ_lt_succ theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b := by simp only [le_antisymm_iff, succ_le_succ] theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b := by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero], rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]] theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by simp only [le_antisymm_iff, add_le_add_iff_right] @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin refine le_antisymm (le_of_not_lt $ λ hn, ne_zero_iff_nonempty.2 _ h) (zero_le _), rw [← succ_le, succ_zero] at hn, cases hn with f, exact ⟨f punit.star⟩ end, λ e, by simp only [e, card_zero]⟩ @[simp] theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α := (not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty @[simp] theorem type_eq_zero_iff_empty [is_well_order α r] : type r = 0 ↔ ¬ nonempty α := (not_iff_comm.1 type_ne_zero_iff_nonempty).symm instance : zero_ne_one_class ordinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ type_ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem zero_lt_one : (0 : ordinal) < 1 := lt_iff_le_and_ne.2 ⟨zero_le _, zero_ne_one⟩ /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal.{u}) : ordinal.{u} := if h : ∃ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩; simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≤ o := if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _) else by rw [pred, dif_neg h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e, λ h, dif_neg h⟩ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a := iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le]) (iff_not_comm.1 pred_eq_iff_not_succ).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩ theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o := ⟨lt_trans (lt_succ_self _), λ l, lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ] else by simp only [pred, dif_neg h, succ_lt_of_not_succ h] theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $ h.symm ▸ lt_succ_self _ in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : ∃ a, o = succ a then by cases h with a e; simp only [e, pred_succ, lift_succ] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o theorem not_zero_is_limit : ¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : ¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _)) theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e ▸ h) theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o := ⟨lt_trans (lt_succ_self _), h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a := ⟨λ h x l, le_trans (le_of_lt l) h, λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn, not_lt_of_le (H _ hn) (lt_succ_self _)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x := by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h), λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in by rw [← e, ← lift_succ, lift_lt]; rw [← e, lift_lt] at h; exact H a' h⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa only [succ_zero] using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : ∃ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ instance : is_well_order ordinal (<) := ⟨wf⟩ @[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*} (o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o)) (H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o := wf.fix (λ o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : ∃ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ := by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl @[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) : @limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) := begin have h : ∃ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, well_founded.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = h₂, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert h₂ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) : @limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) := by rw [limit_rec_on, well_founded.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl /-- A normal ordinal function is a strictly increasing function which is order-continuous. -/ def is_normal (f : ordinal → ordinal) : Prop := (∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ ∃ b < o, a < f b := not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := lt_iff_lt_of_strict_mono f $ λ a b, limit_rec_on b (not.elim (not_lt_of_le $ zero_le _)) (λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim (λ h, lt_trans (IH h) (H.1 _)) (λ e, e ▸ H.1 _)) (λ b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 (le_refl _) _ (l.2 _ h))) theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp only [le_antisymm_iff, H.le_iff] theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a := limit_rec_on a (zero_le _) (λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _)) (λ a l IH, (limit_le l).2 $ λ b h, le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h) theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f a ≤ o := ⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h, λ h, begin revert H₂, apply limit_rec_on S, { intro H₂, cases p0 with x px, have := le_zero.1 ((H₂ _).1 (zero_le _) _ px), rw this at px, exact h _ px }, { intros S _ H₂, rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) }, { intros S L _ H₂, apply (H.2 _ L _).2, intros a h', rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) } end⟩ theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o := (H.le_set (λ x, ∃ y, p y ∧ x = g y) (let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _ (λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1, λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans ⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩ theorem is_normal.refl : is_normal id := ⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (λ x, f (g x)) := ⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ lt_of_le_of_lt (zero_le _) $ H.lt_iff.2 l.pos, λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩ theorem add_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c := ⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { cases this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [← typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le] at this, refine lt_of_le_of_lt (type_le'.2 ⟨order_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by cases h; assumption⟩ } }, { rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂; rintro ⟨⟩; constructor; assumption } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _), λ b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) := (add_is_normal a).is_limit def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨order_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-- The minimal element of a nonempty family of ordinals -/ def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in set.ne_empty_of_mem (set.mem_range_self i)) theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ι I} {f : ι → ordinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm ▸ h theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{u v}, λ a b, lift_inj.1⟩, λ a b, lift_lt.symm⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, intros α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(order_iso.of_surjective (order_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.ord'.1 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, intros α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{u (max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/ def sub (a b : ordinal.{u}) : ordinal.{u} := omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩ instance : has_sub ordinal := ⟨sub⟩ theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) := omin_mem {o | a ≤ b+o} _ theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c := ⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _), λ h, omin_le h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_refl _) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h ▸ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≤ a := sub_le.2 $ le_add_left _ _ theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a := le_antisymm begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp only [e, add_zero, h] }, { rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self }, { exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) } end (le_add_sub _ _) @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0 theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b := ⟨λ h, by simpa only [h, add_zero] using le_add_sub a b, λ h, by rwa [← le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero, λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + omega.{u} = omega := begin refine le_antisymm _ (le_add_left _ _), rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add], have : is_well_order unit empty_relation := by apply_instance, refine ⟨order_embedding.collapse (order_embedding.of_monotone _ _)⟩, { apply sum.rec, exact λ _, 0, exact nat.succ }, { intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H; [cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] } end @[simp] theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o := by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega] instance : monoid ordinal.{u} := { mul := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨order_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨equiv.prod_assoc _ _ _, λ a b, begin rcases a with ⟨⟨a₁, a₂⟩, a₃⟩, rcases b with ⟨⟨b₁, b₂⟩, b₃⟩, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨equiv.punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp only [prod.lex_def, empty_relation, false_or]; dsimp only; simp only [eq_self_iff_true, true_and]; refl⟩⟩, one_mul := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨equiv.prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ } @[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans (order_iso.prod_lex_congr (order_iso.preimage equiv.ulift _) (order_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk β) (mk α) @[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_iff_empty.2 (λ ⟨⟨e, _⟩⟩, e.elim) @[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_iff_empty.2 (λ ⟨⟨_, e⟩⟩, e.elim) theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨equiv.sum_prod_distrib _ _ _, begin rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def, sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr, equiv.sum_prod_distrib_apply_left, equiv.sum_prod_distrib_apply_right]; simp only [sum.inl.inj_iff, true_or, false_and, false_or] end⟩⟩ @[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a := by simp only [mul_add, mul_one] @[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _ theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨order_embedding.of_monotone (λ a, (f a.1, a.2)) (λ a b h, _)⟩, clear_, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ _ (f.to_order_embedding.ord'.1 h') }, { exact prod.lex.right _ _ h' } end theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨order_embedding.of_monotone (λ a, (a.1, f a.2)) (λ a b h, _)⟩, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ _ h' }, { exact prod.lex.right _ _ (f.to_order_embedding.ord'.1 h') } end theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d := le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁) private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s] {c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) : false := begin suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [← typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw [mul_succ] at this, have := lt_of_lt_of_le ((add_lt_add_iff_left _).2 (typein_lt_type _ a)) this, refine lt_of_le_of_lt _ this, refine (type_le'.2 _), constructor, refine order_embedding.of_monotone (λ a, _) (λ a b, _), { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, a₁⟩, h₁⟩, rcases b with ⟨⟨b₂, a₂⟩, h₂⟩, intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂, { substs b₁ b₂, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h }, { subst b₁, simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢, cases h₂; [exact asymm h h₂_h, exact e₂ rfl] }, { simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] }, { simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } } end theorem mul_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c := ⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _, by exactI mul_le_of_limit_aux) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h, λ b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁ theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by simpa only [pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b := le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h theorem mul_left_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b → is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact (lt_irrefl _).elim b0 }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ protected def div (a b : ordinal.{u}) : ordinal.{u} := if h : b = 0 then 0 else omin {o | a < b * succ o} ⟨a, succ_le.1 $ by simpa only [succ_zero, one_mul] using mul_le_mul_right (succ a) (succ_le.2 (pos_iff_ne_zero.2 h))⟩ instance : has_div ordinal := ⟨ordinal.div⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl def div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = omin {o | a < b * succ o} _ := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by rw div_def a h; exact omin_mem {o | a < b * succ o} _ theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by simpa only [mul_succ] using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c := ⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h), λ h, by rw div_def a b0; exact omin_le h⟩ theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by rw [← not_le, div_le c0, not_lt] theorem le_div {a b c : ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := begin apply limit_rec_on a, { simp only [mul_zero, zero_le] }, { intros, rw [succ_le, lt_div c0] }, { simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c := lt_iff_lt_of_le_iff_le $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c := if b0 : b = 0 then by simp only [b0, div_zero, zero_le] else (div_le b0).2 $ lt_of_le_of_lt h $ mul_lt_mul_of_pos_left (lt_succ_self _) (pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b := lt_imp_lt_of_le_imp_le div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := le_zero.1 $ div_le_of_le_mul $ zero_le _ theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a := if b0 : b = 0 then by simp only [b0, zero_mul, zero_le] else (le_div b0).1 (le_refl _) theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := by rw [← le_zero, div_le $ pos_iff_ne_zero.1 $ lt_of_le_of_lt (zero_le _) h]; simpa only [succ_zero, mul_one] using h @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a := by simpa only [add_zero, zero_div] using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa only [one_mul] using mul_div_cancel a one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 := by simpa only [mul_one] using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else eq_of_forall_ge_iff $ λ d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] /-- Divisibility is defined by right multiplication: `a ∣ b` if there exists `c` such that `b = a * c`. -/ instance : has_dvd ordinal := ⟨λ a b, ∃ c, b = a * c⟩ theorem dvd_def {a b : ordinal} : a ∣ b ↔ ∃ c, b = a * c := iff.rfl theorem dvd_mul (a b : ordinal) : a ∣ a * b := ⟨_, rfl⟩ theorem dvd_trans : ∀ {a b c : ordinal}, a ∣ b → b ∣ c → a ∣ c | a _ _ ⟨b, rfl⟩ ⟨c, rfl⟩ := ⟨b * c, mul_assoc _ _ _⟩ theorem dvd_mul_of_dvd {a b : ordinal} (c) (h : a ∣ b) : a ∣ b * c := dvd_trans h (dvd_mul _ _) theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, λ ⟨d, e⟩, by rw [e, ← mul_add]; apply dvd_mul⟩ theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c := (dvd_add_iff h₁).2 theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩ theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 := ⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩ theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩ theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b | a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a (one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0)) theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂) /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp only [a0, zero_mod] else by simp only [mod_def, div_self a0, mul_one, sub_self] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self] end ordinal namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. -/ def ord (c : cardinal) : ordinal := begin let ι := λ α, {r // is_well_order α r}, have : ∀ α, nonempty (ι α) := λ α, ⟨classical.indefinite_description _ well_ordering_thm⟩, let F := λ α, ordinal.min (this _) (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, le_antisymm (this h) (this (setoid.symm h)), intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _), haveI := @order_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(order_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨order_iso.preimage f i.1⟩, exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end def ord_eq_min (α : Type u) : ord (mk α) = @ordinal.min _ _ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (mk α) = @type α r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq _ ⟨classical.indefinite_description _ well_ordering_thm⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (mk α) ≤ ordinal.type r := @ordinal.min_le _ ⟨classical.indefinite_description _ well_ordering_thm⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := quotient.induction_on c $ λ α, induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp only [mk_def, card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := order_embedding.preimage f s, haveI := order_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := ord_le.2 (le_refl _) @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : ℕ) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end def ord.order_embedding : @order_embedding cardinal ordinal (<) (<) := order_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2 @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ def univ := lift.{(u+1) v} (mk ordinal) theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{u (u+1)} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{u (max (u+1) v)} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl /-- The supremum of a family of ordinals -/ def sup {ι} (f : ι → ordinal) : ordinal := omin {c | ∀ i, f i ≤ c} ⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $ cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩ theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f := omin_mem {c | ∀ i, f i ≤ c} _ theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩ theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i := by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a) theorem is_normal.sup {f} (H : is_normal f) {ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ λ a, by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)]; intros; simp only [sup_le, true_implies_iff] theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord := eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le] /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. (This is not a special case of `sup` over the subtype, because `{a // a < o} : Type (u+1)` and `sup` only works over families in `Type u`.) -/ def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} := match o, o.out, o.out_eq with | _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _)) end theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a := match o, o.out, o.out_eq, f : ∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}), bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with | _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI ⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩ end theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) : bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ λ o, by rw [bsup_le, sup_le]; exact ⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩ theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f := bsup_le.1 (le_refl _) _ _ theorem is_normal.bsup {f} (H : is_normal f) {o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) := induction_on o $ λ α r _ g h, by resetI; rw [bsup_type, H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type] /-- The ordinal exponential, defined by transfinite recursion. -/ def power (a b : ordinal) : ordinal := if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b) instance : has_pow ordinal ordinal := ⟨power⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a := by simp only [pow, power, if_pos rfl] @[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 := by rwa [zero_power', sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero], simp only [pow, power, if_neg h, limit_rec_on_zero]] @[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero] else by simp only [pow, power, limit_rec_on_succ, if_neg h] theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b = bsup.{u u} b (λ c _, a ^ c) := by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c := by rw [power_limit a0 h, bsup_le] theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) : a < b ^ c ↔ ∃ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and] @[simp] theorem power_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul] @[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, { simp only [power_zero] }, { intros _ ih, simp only [power_succ, ih, mul_one] }, refine λ b l IH, eq_of_forall_ge_iff (λ c, _), rw [power_le_of_limit one_ne_zero l], exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos, λ H b' h, by rwa IH _ h⟩, end theorem power_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [power_succ], exact mul_pos IH a0 }, { exact λ b l _, (lt_power_of_limit (pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem power_ne_zero {a : ordinal} (b) (a0 : a ≠ 0) : a ^ b ≠ 0 := pos_iff_ne_zero.1 $ power_pos b $ pos_iff_ne_zero.2 a0 theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from lt_trans zero_lt_one h, ⟨λ b, by simpa only [mul_one, power_succ] using (mul_lt_mul_iff_left (power_pos b a0)).2 h, λ b l c, power_le_of_limit (ne_of_gt a0) l⟩ theorem power_lt_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (power_is_normal a1).lt_iff theorem power_le_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c := (power_is_normal a1).le_iff theorem power_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (power_is_normal a1).inj theorem power_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b → is_limit (a ^ b) := (power_is_normal a1).is_limit theorem power_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw power_succ, exact mul_is_limit (power_pos _ l.pos) l }, { exact power_is_limit l.one_lt l' } end theorem power_le_power_right {a b c : ordinal} (h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (power_le_power_iff_right h₁).2 h₂ }, { subst a, simp only [one_power] } end theorem power_le_power_left {a b : ordinal} (c) (ab : a ≤ b) : a ^ c ≤ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp only [power_zero] }, { simp only [zero_power c0, zero_le] } }, { apply limit_rec_on c, { simp only [power_zero] }, { intros c IH, simpa only [power_succ] using mul_le_mul IH ab }, { exact λ c l IH, (power_le_of_limit a0 l).2 (λ b' h, le_trans (IH _ h) (power_le_power_right (lt_of_lt_of_le (pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } } end theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b := (power_is_normal a1).le_self _ theorem power_lt_power_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by rw [power_succ, power_succ]; exact lt_of_le_of_lt (mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab) (mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (zero_le _) ab))) theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]}, have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le (pos_iff_ne_zero.2 c0) (le_add_left _ _)), simp only [zero_power c0, zero_power this, mul_zero] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power, mul_one] }, apply limit_rec_on c, { simp only [add_zero, power_zero, mul_one] }, { intros c IH, rw [add_succ, power_succ, IH, power_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (((mul_is_normal $ power_pos b (pos_iff_ne_zero.2 a0)).trans (power_is_normal a1)).limit_le l).symm } end theorem power_dvd_power (a) {b c : ordinal} (h : b ≤ c) : a ^ b ∣ a ^ c := by rw [← add_sub_cancel_of_le h, power_add]; apply dvd_mul theorem power_dvd_power_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c := ⟨λ h, le_of_not_lt $ λ hn, not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $ le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h, power_dvd_power _⟩ theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]}, simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power] }, apply limit_rec_on c, { simp only [mul_zero, power_zero] }, { intros c IH, rw [mul_succ, power_add, IH, power_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (mul_is_normal (pos_iff_ne_zero.2 b0))).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (power_le_of_limit (power_ne_zero _ a0) l).symm } end /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b`. -/ def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred $ omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩ else 0 @[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 := by simp only [log, dif_neg b1] theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x = pred (omin {o | x < b^o} (log._proof_1 b x b1)) := by simp only [log, dif_pos b1] @[simp] theorem log_zero (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then by rw [log_def b1, ← le_zero, pred_le]; apply omin_le; change 0<b^succ 0; rw [succ_zero, power_one]; exact lt_trans zero_lt_one b1 else by simp only [log_not_one_lt b1] theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) = omin {o | x < b^o} (log._proof_1 b x b1) := begin let t := omin {o | x < b^o} (log._proof_1 b x b1), have : x < b ^ t := omin_mem {o | x < b^o} _, rcases zero_or_succ_or_limit t with h|h|h, { refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim, simpa only [h, power_zero] }, { rw [show log b x = pred t, from log_def b1 x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩, exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) } end theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin cases lt_or_eq_of_le (zero_le x) with x0 x0, { rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ }, { subst x, apply power_pos _ (lt_trans zero_lt_one b1) } end theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) : b ^ log b x ≤ x := begin by_cases b0 : b = 0, { rw [b0, zero_power'], refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _), have := @omin_le {o | x < b^o} _ _ h, rwa ← succ_log_def b1 x0 at this }, { rw [← b1, one_power], exact one_le_iff_pos.2 x0 } end theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : c ≤ log b x ↔ b ^ c ≤ x := ⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0), λ h, le_of_not_lt $ λ hn, not_le_of_lt (lt_power_succ_log b1 x) $ le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩ theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : log b x < c ↔ x < b ^ c := lt_iff_lt_of_le_iff_le (le_log b1 x0) theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) : log b x ≤ log b y := if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else have x0 : 0 < x, from pos_iff_ne_zero.2 x0, if b1 : 1 < b then (le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy else by simp only [log_not_one_lt b1, zero_le] theorem log_le_self (b x : ordinal) : log b x ≤ x := if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else if b1 : 1 < b then le_trans (le_power_self _ b1) (power_log_le b (pos_iff_ne_zero.2 x0)) else by simp only [log_not_one_lt b1, zero_le] @[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n := by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero], rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]] @[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n := by induction n with n IH; [simp only [nat.pow_zero, nat.cast_zero, power_zero, nat.cast_one], rw [nat.pow_succ, nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]] @[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n := by rw [← cardinal.ord_nat, ← cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n := by simp only [lt_iff_le_not_le, nat_cast_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n := by simp only [le_antisymm_iff, nat_cast_le] @[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 @[simp] theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 := not_congr nat_cast_eq_zero @[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n := @nat_cast_lt 0 n @[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n := (_root_.le_total m n).elim (λ h, by rw [nat.sub_eq_zero_iff_le.2 h, sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl) (λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add, nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)]) @[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n := if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else have n0':_, from nat_cast_ne_zero.2 n0, le_antisymm (by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm]; apply nat.div_mul_le_self) (by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul, nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)]; apply nat.lt_succ_self) @[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n := by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add, add_comm, nat.mod_add_div] @[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o := ⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h, λ h, card_nat n ▸ card_le_card h⟩ @[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o := by rw [← succ_le, ← cardinal.succ_le, cardinal.nat_succ, nat_le_card]; refl @[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n := lt_iff_lt_of_le_iff_le nat_le_card @[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n := le_iff_le_iff_lt_iff_lt.2 nat_lt_card @[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n := by simp only [le_antisymm_iff, card_le_nat, nat_le_card] @[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n := by rw [← card_eq_nat, card_type, mk_fin] @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n with n ih; [simp only [nat.cast_zero, lift_zero], simp only [nat.cast_succ, lift_add, ih, lift_one]] theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n := by simp only [type_fin, lift_nat_cast] theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α := by rw [← card_eq_nat, card_type, fintype_card] end ordinal namespace cardinal open ordinal @[simp] theorem ord_omega : ord.{u} omega = ordinal.omega := le_antisymm (ord_le.2 $ le_refl _) $ le_of_forall_lt $ λ o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ← lift_card, ← lift_omega.{0 u}, lift_lt, ← typein_enum (<) h'], exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c := by rw [add_comm, ← card_ord c, ← card_one, ← card_add, one_add_of_omega_le]; rwa [← ord_omega, ord_le_ord] end cardinal namespace ordinal theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n := by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat] theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < omega := nat_lt_omega 0 theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1 theorem omega_is_limit : is_limit omega := ⟨omega_ne_zero, λ o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ H, le_of_forall_lt $ λ a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ← succ_le]; exact H (n+1)⟩ theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := lt_of_le_of_ne (zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o := omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := begin rcases lt_omega.1 h with ⟨n, rfl⟩, clear h, induction n with n IH, { rw [nat.cast_zero, zero_add] }, { rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] } end theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega end theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩, { refine (limit_le l).2 (λ x hx, le_of_lt _), rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact le_trans (add_le_add_right (mul_div_le _ _) _) (le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (pos_iff_ne_zero.2 $ mt _ a0), intro e, simp only [e, mul_zero] } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega end theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, apply limit_rec_on b, { intro h, rw [power_zero, ← succ_zero, lt_succ, le_zero] at h, rw [h, zero_add] }, { intros b _ h, rw [power_succ] at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [power_succ, ← mul_add, add_omega xo] }, { intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, refine (((add_is_normal a).trans (power_is_normal one_lt_omega)) .limit_le l).2 (λ y yb, _), let z := max x y, have := IH z (max_lt xb yb) (lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)), exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _) (le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) } end theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) : a + b < omega ^ c := by rwa [← add_omega_power h₁, add_lt_add_iff_left] theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c := by rw [← add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁] theorem add_absorp_iff {o : ordinal} (o0 : o > 0) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a := ⟨λ H, ⟨log omega o, begin refine ((lt_or_eq_of_le (power_log_le _ o0)) .resolve_left $ λ h, _).symm, have := H _ h, have := lt_power_succ_log one_lt_omega o, rw [power_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]}, simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH] end⟩, λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩ theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ λ c' h, begin apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)), rw IH _ h, apply le_trans (add_le_add_left _ _), { rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right _ (le_add_right _ _)) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp only [succ_zero, mul_one] }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba) theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := le_antisymm ((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb)) (by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0)) theorem mul_lt_omega_power {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw power_succ at ha, rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _, rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)], exact mul_lt_omega hn hb }, { rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _, rw [← power_succ, power_lt_power_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h}, refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)), rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _, rw [← power_add, add_omega_power xb] end theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (λ b hb, le_of_lt (power_lt_omega h hb))) (le_power_self _ a1) theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : o % b ^ log b o < o := lt_of_lt_of_le (mod_lt _ $ power_ne_zero _ b0) (power_log_le _ $ pos_iff_ne_zero.2 o0) @[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0) {C : ordinal → Sort*} (H0 : C 0) (H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o) : ∀ o, C o | o := if o0 : o = 0 then by rw o0; exact H0 else have _, from CNF_aux b0 o0, H o o0 this (CNF_rec (o % b ^ log b o)) using_well_founded {dec_tac := `[assumption]} @[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 := by rw [CNF_rec, dif_pos rfl]; refl @[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) : @CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) := by rw [CNF_rec, dif_neg o0] /-- The Cantor normal form of an ordinal is the list of coefficients in the base-`b` expansion of `o`. CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/ def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) := if b0 : b = 0 then [] else CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o @[simp] theorem zero_CNF (o) : CNF 0 o = [] := dif_pos rfl @[simp] theorem CNF_zero (b) : CNF b 0 = [] := if b0 : b = 0 then dif_pos b0 else (dif_neg b0).trans $ CNF_rec_zero _ theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) := by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0] theorem one_CNF {o : ordinal} (o0 : o ≠ 0) : CNF 1 o = [(0, o)] := by rw [CNF_ne_zero one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one, CNF_zero, div_one] theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) : (CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o := CNF_rec b0 (by rw CNF_zero; refl) (λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o theorem CNF_pairwise_aux (b := omega) (o) : (∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧ (CNF b o).pairwise (λ p q, q.1 < p.1) := begin by_cases b0 : b = 0, { simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine CNF_rec b0 _ _ o, { simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim }, intros o o0 H IH, cases IH with IH₁ IH₂, simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true], refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩, { exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) }, { refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _), { rw pos_iff_ne_zero, intro e, rw e at m, simpa only [CNF_zero] using m }, { exact mod_lt _ (power_ne_zero _ b0) } } }, { by_cases o0 : o = 0, { simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim }, rw [← b1, one_CNF o0], simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] } end theorem CNF_pairwise (b := omega) (o) : (CNF b o).pairwise (λ p q, prod.fst q < p.1) := (CNF_pairwise_aux _ _).2 theorem CNF_fst_le_log (b := omega) (o) : ∀ p ∈ CNF b o, prod.fst p ≤ log b o := (CNF_pairwise_aux _ _).1 theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o := le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _) theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) : ∀ p ∈ CNF b o, prod.snd p < b := begin have b0 := ne_of_gt (lt_trans zero_lt_one b1), refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o, intros o o0 H IH, simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, list.forall_mem_cons', iff_true_intro IH, and_true], rw [div_lt (power_ne_zero _ b0), ← power_succ], exact lt_power_succ_log b1 _, end theorem CNF_sorted (b := omega) (o) : ((CNF b o).map prod.fst).sorted (>) := by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o /-- The next fixed point function, the least fixed point of the normal function `f` above `a`. -/ def nfp (f : ordinal → ordinal) (a : ordinal) := sup (λ n : ℕ, f^[n] a) theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := le_sup _ n theorem le_nfp_self (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := lt_sup.trans $ iff.trans (by exact ⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩, λ ⟨n, h⟩, ⟨n+1, by rw nat.iterate_succ'; exact H.lt_iff.2 h⟩⟩) lt_sup.symm theorem is_normal.nfp_le {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_nfp theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := sup_le.2 $ λ i, begin induction i with i IH generalizing a, {exact ab}, exact IH (le_trans (H.le_iff.2 ab) h), end theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a := begin refine le_antisymm _ (H.le_self _), cases le_or_lt (f a) a with aa aa, { rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) }, rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l, { refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1), simp only [e, zero_le] }, { have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]), rw [e, lt_succ] at this, have ab : a ≤ b, { rw [← lt_succ, ← e], exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) }, refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this)) (le_trans this (le_of_lt _)), simp only [e, lt_succ_self] }, { exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) } end theorem is_normal.le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.le_self _), λ h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp f 0) (λ a IH, nfp f (succ IH)) (λ a l, bsup.{u u} a) @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u u} o (λ a _, deriv f a) := limit_rec_on_limit _ _ _ _ theorem deriv_is_normal (f) : is_normal (deriv f) := ⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self, λ o l a, by rw [deriv_limit _ l, bsup_le]⟩ theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o := begin apply limit_rec_on o, { rw [deriv_zero, H.nfp_fp] }, { intros o ih, rw [deriv_succ, H.nfp_fp] }, intros o l IH, rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1], refine eq_of_forall_ge_iff (λ c, _), simp only [bsup_le, IH] {contextual:=tt} end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, a = deriv f o := ⟨λ ha, begin suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o, from this a ((deriv_is_normal _).le_self _), intro o, apply limit_rec_on o, { intros h₁, refine ⟨0, le_antisymm h₁ _⟩, rw deriv_zero, exact H.nfp_le_fp (zero_le _) ha }, { intros o IH h₁, cases le_or_lt a (deriv f o), {exact IH h}, refine ⟨succ o, le_antisymm h₁ _⟩, rw deriv_succ, exact H.nfp_le_fp (succ_le.2 h) ha }, { intros o l IH h₁, cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩}, rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩ end ordinal namespace cardinal open ordinal theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa only [card_zero, le_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊢, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @order_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_order_embedding.ord'.symm @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ def aleph_idx.order_iso : @order_iso cardinal.{u} ordinal.{u} (<) (<) := @order_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.inj, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.order_iso_coe : (aleph_idx.order_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.order_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal def aleph'.order_iso := cardinal.aleph_idx.order_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁, etc. -/ def aleph' : ordinal → cardinal := aleph'.order_iso @[simp] theorem aleph'.order_iso_coe : (aleph'.order_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.order_iso.ord'.symm @[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := cardinal.aleph_idx.order_iso.to_equiv.inverse_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.order_iso.to_equiv.apply_inverse_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← le_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, λ h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp only [aleph, add_zero, aleph'_omega] theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using mul_le_mul_left c (le_trans (le_of_lt one_lt_omega) h)), refine acc.rec_on (cardinal.wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, rcases ord_eq α with ⟨r, wo, e⟩, resetI, let := decidable_linear_order_of_STO' r, have : is_well_order α (<) := wo, let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), have : is_well_order _ s := (order_embedding.preimage _ _).is_well_order, suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr equiv.punit_equiv_punit), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) ▸ mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using mul_le_mul_left a (le_trans (le_of_lt one_lt_omega) hb)) (by simpa only [one_mul] using mul_le_mul_right b (le_trans (le_of_lt one_lt_omega) ha)) theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := lt_of_le_of_lt (mul_le_mul (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (mul_lt_omega h h) hc) (λ h, by rw mul_eq_self h; exact max_lt h1 h2) theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using mul_le_mul_right c (le_trans (le_of_lt $ nat_lt_omega 2) h)) (le_add_left c c) theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (le_add_right _ _) (le_add_left _ _) theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (add_lt_omega h h) hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) theorem pow_le {κ μ : cardinal.{u}} (H1 : omega ≤ κ) (H2 : μ < omega) : κ^μ ≤ κ := let ⟨n, H3⟩ := lt_omega.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero]; from one_lt_omega) H1) (λ n ih, trans_rel_left _ (by rw [nat.cast_succ, power_add, power_one]; from mul_le_mul_right _ ih) (mul_eq_self H1))) H1) theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (list α) = mk α := eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc mk (list α) = sum (λ n : ℕ, mk α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, mk α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n ... = sum (λ n : ulift.{u} ℕ, mk α) : quotient.sound ⟨@equiv.sigma_congr_left _ _ (λ _, quotient.out (mk α)) equiv.ulift.symm⟩ ... = omega * mk α : sum_const _ _ ... = max (omega) (mk α) : mul_eq_max (le_refl _) H1 ... = mk α : max_eq_right H1 end cardinal
d3614f50b1a44c978aeadecd60dabc3589c00b7e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/tactic/norm_num.lean
b1fc7ea943a495eecfe314fcbb5fa46b528310ba
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
63,644
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro -/ import data.rat.cast import data.rat.meta_defs /-! # `norm_num` Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`. -/ universes u v w namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a proof by reflexivity. -/ meta def or_refl_conv (tac : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := tac e <|> refl_conv e /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]) /-- Faster version of `mk_app ``bit1 [e]`. -/ meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) end instance_cache end tactic open tactic /-! Each lemma in this file is written the way it is to exactly match (with no defeq reduction allowed) the conclusion of some lemma generated by the proof procedure that uses it. That proof procedure should describe the shape of the generated lemma in its docstring. -/ namespace norm_num variable {α : Type u} lemma subst_into_add {α} [has_add α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rw [prl, prr, prt] lemma subst_into_mul {α} [has_mul α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by rw [prl, prr, prt] lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ meta inductive match_numeral_result | zero | one | bit0 (e : expr) | bit1 (e : expr) | other /-- Unfold the top level constructor of the numeral expression. -/ meta def match_numeral : expr → match_numeral_result | `(bit0 %%e) := match_numeral_result.bit0 e | `(bit1 %%e) := match_numeral_result.bit1 e | `(@has_zero.zero _ _) := match_numeral_result.zero | `(@has_one.one _ _) := match_numeral_result.one | _ := match_numeral_result.other theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _ theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr) | c e r := match match_numeral e with | zero := c.mk_app ``zero_succ [] | one := c.mk_app ``one_succ [] | bit0 e := c.mk_app ``bit0_succ [e] | bit1 e := do let r := r.app_arg, (c, p) ← prove_succ c e r, c.mk_app ``bit1_succ [e, r, p] | _ := failed end end /-- Given `a` natural numeral, returns `(b, ⊢ a + 1 = b)`. -/ meta def prove_succ' (c : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, (c, b) ← c.of_nat (na + 1), (c, p) ← prove_succ c a b, return (c, b, p) theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_assoc] theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result meta mutual def prove_add_nat, prove_adc_nat with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := c.mk_app ``zero_add [b] | _, zero := c.mk_app ``add_zero [a] | _, one := prove_succ c a r | one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p] | _, _ := failed end with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p] | _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p] | one, one := c.mk_app ``adc_one_one [] | bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p] | one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p] | bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p] | one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p] | _, _ := failed end /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ add_decl_doc prove_add_nat /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ add_decl_doc prove_adc_nat /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, nb ← b.to_nat, (c, r) ← c.of_nat (na + nb), (c, p) ← prove_add_nat c a b r, return (c, r, p) end theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul] theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) : a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add] theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h) theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic a b := match match_numeral a, match_numeral b with | zero, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, zero := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p) | _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p) | bit0 a, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p], (ic, c') ← ic.mk_bit0 c, (ic, c') ← ic.mk_bit0 c', return (ic, c', p) | bit0 a, _ := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | _, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | bit1 a, bit1 b := do (ic, c, pc) ← prove_mul_nat ic a b, (ic, d, pd) ← prove_add_nat' ic a b, (ic, c') ← ic.mk_bit0 c, (ic, e, pe) ← prove_add_nat' ic c' d, (ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe], (ic, e') ← ic.mk_bit1 e, return (ic, e', p) | _, _ := failed end end section open match_numeral_result /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr) | e := match match_numeral e with | one := c.mk_app ``zero_lt_one' [] | bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p] | bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p] | _ := failed end end /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr) | `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂, c.mk_app ``div_pos [e₁, e₂, p₁, p₂] | e := prove_pos_nat c e /-- `match_neg (- e) = some e`, otherwise `none` -/ meta def match_neg : expr → option expr | `(- %%e) := some e | _ := none /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ meta def match_sign : expr → expr ⊕ bool | `(- %%e) := sum.inl e | `(has_zero.zero) := sum.inr ff | _ := sum.inr tt theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1 /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_neg a with | some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p] | none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p] end theorem clear_denom_div {α} [division_ring α] (a b b' c d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c := by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀] /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom' (prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr)) (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) := if na.denom = 1 then prove_mul_nat c a d else do [_, _, a, b] ← return a.get_app_args, (c, b') ← c.of_nat (nd / na.denom), (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, _, p₁) ← prove_mul_nat c b b', (c, r, p₂) ← prove_mul_nat c a b', (c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂], return (c, r, p) theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h) theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := one_lt_bit1.2 h theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2 theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _) theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h) theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2 theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 _ h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 _ h) theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2 theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 _ _ h) theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 _ _ h) theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2 theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2 theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _ theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _ theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := (bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := (bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr) | e@`(has_zero.zero) := ic.mk_app ``le_refl [e] | e := if ic.α = `(ℕ) then return (ic, `(nat.zero_le).mk_app [e]) else do (ic, p) ← prove_pos ic e, ic.mk_app ``nonneg_pos [e, p] section open match_numeral_result /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_numeral a with | one := ic.mk_app ``le_refl [a] | bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p] | bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p] | _ := failed end meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache) with prove_le_nat : expr → expr → tactic (instance_cache × expr) | a b := if a = b then ic.mk_app ``le_refl [a] else match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p] | _, _ := failed end with prove_sle_nat : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p] | _, _ := failed end /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ add_decl_doc prove_le_nat /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ add_decl_doc prove_sle_nat /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_pos ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p] | _, _ := failed end end theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_lt_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_lt_nat ic a' b', ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p] lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do -- we have to switch the order of `a` and `b` because `a < b ↔ -b < -a` (ic, p) ← prove_lt_nonneg_rat ic b a (-nb) (-na), ic.mk_app ``neg_lt_neg [b, a, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_pos ic a, ic.mk_app ``neg_neg_of_pos [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_pos ic a, (ic, pb) ← prove_pos ic b, ic.mk_app ``lt_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_pos ic b | sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb end theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (by rwa [ha, hb]) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_le_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_le_nat ic a' b', ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p] lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_le_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_nonneg ic a, ic.mk_app ``neg_nonpos_of_nonneg [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_nonneg ic a, (ic, pb) ← prove_nonneg ic b, ic.mk_app ``le_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_nonneg ic b | sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb end /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na < nb then do (ic, p) ← prove_lt_rat ic a b na nb, ic.mk_app ``ne_of_lt [a, b, p] else do (ic, p) ← prove_lt_rat ic b a nb na, ic.mk_app ``ne_of_gt [a, b, p] theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 _ theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 _ theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 _ theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 _ theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 _ theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 _ /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (nc, e) ← nc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``nat_cast_zero [], return (ic, nc, e, p) | match_numeral_result.one := do (nc, e) ← nc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``nat_cast_one [], return (ic, nc, e, p) | match_numeral_result.bit0 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a0) ← nc.mk_bit0 a, (ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p], return (ic, nc, a0, p) | match_numeral_result.bit1 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a1) ← nc.mk_bit1 a, (ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p], return (ic, nc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (zc, e) ← zc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``int_cast_zero [], return (ic, zc, e, p) | match_numeral_result.one := do (zc, e) ← zc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``int_cast_one [], return (ic, zc, e, p) | match_numeral_result.bit0 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a0) ← zc.mk_bit0 a, (ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p], return (ic, zc, a0, p) | match_numeral_result.bit1 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a1) ← zc.mk_bit1 a, (ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p], return (ic, zc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (qc, e) ← qc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``rat.cast_zero [], return (ic, qc, e, p) | match_numeral_result.one := do (qc, e) ← qc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``rat.cast_one [], return (ic, qc, e, p) | match_numeral_result.bit0 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a0) ← qc.mk_bit0 a, (ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p], return (ic, qc, a0, p) | match_numeral_result.bit1 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a1) ← qc.mk_bit1 a, (ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p], return (ic, qc, a1, p) | _ := failed end theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div _ _ /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := if na'.denom = 1 then prove_rat_uncast_nat ic qc cz_inst a' else do [_, _, a', b'] ← return a'.get_app_args, (ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a', (ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b', (qc, e) ← qc.mk_app ``has_div.div [a, b], (ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb], return (ic, qc, e, p) theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ int.cast_neg _ theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ rat.cast_neg _ /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, zc, a, p) ← prove_int_uncast_nat ic zc a', (zc, e) ← zc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``int_cast_neg [a, a', p], return (ic, zc, e, p) | none := prove_int_uncast_nat ic zc a' end /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'), (qc, e) ← qc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p], return (ic, qc, e, p) | none := prove_rat_uncast_nonneg ic qc cz_inst a' na' end theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt nat.cast_inj.1 h theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt int.cast_inj.1 h theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt rat.cast_inj.1 h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr) | ic a b na nb := prove_ne_rat ic a b na nb <|> do cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance, if na.denom = 1 ∧ nb.denom = 1 then if na ≥ 0 ∧ nb ≥ 0 then do guard (ic.α ≠ `(ℕ)), nc ← mk_instance_cache `(ℕ), (ic, nc, a', pa) ← prove_nat_uncast ic nc a, (ic, nc, b', pb) ← prove_nat_uncast ic nc b, (nc, p) ← prove_ne_rat nc a' b' na nb, ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℤ)), zc ← mk_instance_cache `(ℤ), (ic, zc, a', pa) ← prove_int_uncast ic zc a, (ic, zc, b', pb) ← prove_int_uncast ic zc b, (zc, p) ← prove_ne_rat zc a' b' na nb, ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℚ)), qc ← mk_instance_cache `(ℚ), (ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na, (ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb, (qc, p) ← prove_ne_rat qc a' b' na nb, ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr) | a na := do (ic, z) ← ic.mk_app ``has_zero.zero [], prove_ne ic a z na 0 /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ → tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := mul_right_cancel' h₀ $ by rwa [add_mul, ha, hb, hc] /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_add_nat ic a b c else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_ne_zero ic d (rat.of_int nd), (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, p) ← prove_add_nat ic a' b' c', ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p] theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c := h ▸ by simp theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c := h ▸ by simp theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c := h ▸ by simp theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c := h ▸ by simp theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c := h ▸ by simp /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) := match match_neg ea, match_neg eb, match_neg ec with | some ea, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c), ic.mk_app ``add_neg_neg [ea, eb, ec, p] | some ea, none, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a), ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p] | some ea, none, none := do (ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b, ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p] | none, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b), ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p] | none, some eb, none := do (ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a, ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p] | _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c end /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_rat, nb ← b.to_rat, let nc := na + nb, (ic, c) ← ic.of_rat nc, (ic, p) ← prove_add_rat ic a b c na nb nc, return (ic, c, p) theorem clear_denom_simple_nat {α} [division_ring α] (a : α) : (1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩ theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩ /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) := if na.denom = 1 then do (c, d) ← c.mk_app ``has_one.one [], (c, p) ← c.mk_app ``clear_denom_simple_nat [a], return (c, d, a, p) else do [α, _, a, b] ← return a.get_app_args, (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀], return (c, b, a, p) theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := mul_right_cancel' ha.1 $ mul_right_cancel' hb.1 $ by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a] /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_mul_nat ic a b else do let nc := na * nb, (ic, c) ← ic.of_rat nc, (ic, d₁, a', pa) ← prove_clear_denom_simple ic a na, (ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb, (ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, _, p) ← prove_mul_nat ic a' b', (ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p], return (ic, c, p) theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb), (ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p], return (ic, c, p) | sum.inr ff, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, sum.inr ff := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | sum.inl a, sum.inr tt := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb, (ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb), (ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb end theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b := h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div] theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a := by rw [one_div, inv_inv'] theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div _ theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a := by simp only [inv_eq_one_div, one_div_div] /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr) | ic e n := match match_sign e with | sum.inl e := do (ic, e', p) ← prove_inv ic e (-n), (ic, r) ← ic.mk_app ``has_neg.neg [e'], (ic, p) ← ic.mk_app ``inv_neg [e, e', p], return (ic, r, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``inv_zero [], return (ic, e, p) | sum.inr tt := if n.num = 1 then if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_one [], return (ic, e, p) else do let e := e.app_arg, (ic, p) ← ic.mk_app ``inv_one_div [e], return (ic, e, p) else if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_div_one [e], e ← infer_type p, return (ic, e.app_arg, p) else do [_, _, a, b] ← return e.get_app_args, (ic, e') ← ic.mk_app ``has_div.div [b, a], (ic, p) ← ic.mk_app ``inv_div [a, b], return (ic, e', p) end theorem div_eq {α} [division_ring α] (a b b' c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa [ ← hb, ← div_eq_mul_inv] at h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := do (ic, b', pb) ← prove_inv ic b nb, (ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹, (ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p], return (ic, c, p) /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := match match_sign a with | sum.inl a := do (ic, p) ← ic.mk_app ``neg_neg [a], return (ic, a, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``neg_zero [], return (ic, a, p) | sum.inr tt := do (ic, a') ← ic.mk_app ``has_neg.neg [a], p ← mk_eq_refl a', return (ic, a', p) end theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := by rwa [← hb, ← sub_eq_add_neg] at h theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c := by rwa sub_neg_eq_add /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (ic, c, p) ← prove_add_rat' ic a b, (ic, p) ← ic.mk_app ``sub_neg [a, b, c, p], return (ic, c, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``sub_zero [a], return (ic, a, p) | sum.inr tt := do (ic, b', pb) ← prove_neg ic b, (ic, c, p) ← prove_add_rat' ic a b', (ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p], return (ic, c, p) end theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c := h ▸ nat.add_sub_cancel_left _ _ theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 := nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _ /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do na ← a.to_nat, nb ← b.to_nat, if nb ≤ na then do (ic, c) ← ic.of_nat (na - nb), (ic, p) ← prove_add_nat ic b c a, return (c, `(sub_nat_pos).mk_app [a, b, c, p]) else do (ic, c) ← ic.of_nat (nb - na), (ic, p) ← prove_add_nat ic a c b, return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p]) /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ meta def eval_field : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, let n₃ := n₁ + n₂, (c, e₃) ← c.of_rat n₃, (_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃, return (e₃, p) | `(%%e₁ * %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂ | `(- %%e) := do c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_neg c e | `(@has_sub.sub %%α %%inst %%a %%b) := do c ← mk_instance_cache α, if α = `(nat) then prove_sub_nat c a b else prod.snd <$> prove_sub c a b | `(has_inv.inv %%e) := do n ← e.to_rat, c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_inv c e n | `(%%e₁ / %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_div c e₁ e₂ n₁ n₂ | _ := failed lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := h₂ ▸ by simp [pow_bit0, h] lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := by rw [← h₃, ← h₂]; simp [pow_bit1, h] section open match_numeral_result /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr) | ic b := match match_numeral b with | zero := do (ic, p) ← ic.mk_app ``pow_zero [a], (ic, o) ← ic.mk_app ``has_one.one [], return (ic, o, p) | one := do (ic, p) ← ic.mk_app ``pow_one [a], return (ic, a, p) | bit0 b := do (ic, c', p) ← prove_pow ic b, nc' ← expr.to_rat c', (ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc', (ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂], return (ic, c, p) | bit1 b := do (ic, c₁, p) ← prove_pow ic b, nc₁ ← expr.to_rat c₁, (ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁, (ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na, (ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃], return (ic, c, p) | _ := failed end end /-- Evaluates expressions of the form `a ^ b`, `monoid.pow a b` or `nat.pow a b`. -/ meta def eval_pow : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, match m with | `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed end | `(monoid.pow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed /-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/ meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk `(true) <$> mk_app ``eq_true_intro [p] /-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/ meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk `(false) <$> mk_app ``eq_false_intro [p] theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false := eq_false_intro $ not_not_intro rfl /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ meta def eval_ineq : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p else if n₁ = n₂ then do (_, p) ← c.mk_app ``lt_irrefl [e₁], false_intro p else do (c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'], false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (_, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else prove_le_rat c e₁ e₂ n₁ n₂, true_intro p else do (c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq | `(%%e₁ ≠ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁] else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p | _ := failed theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr) | `(nat.succ %%a) := do (ic, n, b, p₁) ← prove_nat_succ a, let n' := n + 1, (ic, c) ← ic.of_nat n', (ic, p₂) ← prove_add_nat ic b `(1) c, return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂]) | e := do n ← e.to_nat, p ← mk_eq_refl e, return (ic, n, e, p) lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg _ _ lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c := (int.mod_neg _ _).trans h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr) | a b mod := match match_neg b with | some b := do (ic, c', p) ← prove_div_mod a b mod, if mod then return (ic, c', `(int_mod_neg).mk_app [a, b, c', p]) else do (ic, c, p₂) ← prove_neg ic c', return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂]) | none := do nb ← b.to_nat, na ← a.to_int, let nq := na / nb, let nr := na % nb, let nm := nq * nr, (ic, q) ← ic.of_int nq, (ic, r) ← ic.of_int nr, (ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb), (ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na), (ic, p') ← prove_lt_nat ic r b, if ic.α = `(nat) then if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p']) else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p']) else if ic.α = `(int) then do (ic, p₀) ← prove_nonneg ic r, if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p']) else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p']) else failed end theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂ theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂ theorem int_to_nat_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : a.to_nat = b := by rw ← h; simp theorem int_to_nat_neg (a : ℤ) (h : 0 < a) : (-a).to_nat = 0 := by simp [int.to_nat_zero_of_neg, h] theorem nat_abs_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : a.nat_abs = b := by rw ← h; simp theorem nat_abs_neg (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : (-a).nat_abs = b := by rw ← h; simp theorem neg_succ_of_nat (a b : ℕ) (c : ℤ) (h₁ : a + 1 = b) (h₂ : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = c) : -[1+ a] = -c := by rw [← h₂, ← h₁, int.nat_cast_eq_coe_nat]; refl /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ meta def eval_nat_int_ext : expr → tactic (expr × expr) | e@`(nat.succ _) := do ic ← mk_instance_cache `(ℕ), (_, _, ep) ← prove_nat_succ ic e, return ep | `(%%a / %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b ff | `(%%a % %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b tt | `(%%a ∣ %%b) := do α ← infer_type a, ic ← mk_instance_cache α, th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else if α = `(int) then return `(dvd_eq_int) else failed, (ic, c, p₁) ← prove_div_mod ic b a tt, (ic, z) ← ic.mk_app ``has_zero.zero [], (e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq, return (e', th.mk_app [a, b, c, e', p₁, p₂]) | `(int.to_nat %%a) := do n ← a.to_int, ic ← mk_instance_cache `(ℤ), if n ≥ 0 then do nc ← mk_instance_cache `(ℕ), (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(int_to_nat_pos).mk_app [a, b, p]) else do a ← match_neg a, (_, p) ← prove_pos ic a, pure (`(0), `(int_to_nat_neg).mk_app [a, p]) | `(int.nat_abs %%a) := do n ← a.to_int, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), if n ≥ 0 then do (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(nat_abs_pos).mk_app [a, b, p]) else do a ← match_neg a, (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(nat_abs_neg).mk_app [a, b, p]) | `(int.neg_succ_of_nat %%a) := do na ← a.to_nat, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), let nb := na + 1, (nc, b) ← nc.of_nat nb, (nc, p₁) ← prove_add_nat nc a `(1) b, (ic, c) ← ic.of_nat nb, (_, _, _, p₂) ← prove_nat_uncast ic nc c, pure (`(-%%c : ℤ), `(neg_succ_of_nat).mk_app [a, b, c, p₁, p₂]) | _ := failed theorem int_to_nat_cast (a : ℕ) (b : ℤ) (h : (by haveI := @nat.cast_coe ℤ; exact a : ℤ) = b) : ↑a = b := eq.trans (by simp) h /-- Evaluates the `↑n` cast operation from `ℕ`, `ℤ`, `ℚ` to an arbitrary type `α`. -/ meta def eval_cast : expr → tactic (expr × expr) | `(@coe ℕ %%α %%inst %%a) := do if inst.is_app_of ``coe_to_lift then if inst.app_arg.is_app_of ``nat.cast_coe then do n ← a.to_nat, ic ← mk_instance_cache α, nc ← mk_instance_cache `(ℕ), (ic, b) ← ic.of_nat n, (_, _, _, p) ← prove_nat_uncast ic nc b, pure (b, p) else if inst.app_arg.is_app_of ``int.cast_coe then do n ← a.to_int, ic ← mk_instance_cache α, zc ← mk_instance_cache `(ℤ), (ic, b) ← ic.of_int n, (_, _, _, p) ← prove_int_uncast ic zc b, pure (b, p) else if inst.app_arg.is_app_of ``int.cast_coe then do n ← a.to_rat, cz_inst ← mk_mapp ``char_zero [α, none, none] >>= mk_instance, ic ← mk_instance_cache α, qc ← mk_instance_cache `(ℚ), (ic, b) ← ic.of_rat n, (_, _, _, p) ← prove_rat_uncast ic qc cz_inst b n, pure (b, p) else failed else if inst = `(@coe_base nat int int.has_coe) then do n ← a.to_nat, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (ic, b) ← ic.of_nat n, (_, _, _, p) ← prove_nat_uncast ic nc b, pure (b, `(int_to_nat_cast).mk_app [a, b, p]) else failed | _ := failed /-- This version of `derive` does not fail when the input is already a numeral -/ meta def derive.step (e : expr) : tactic (expr × expr) := eval_field e <|> eval_pow e <|> eval_ineq e <|> eval_cast e <|> eval_nat_int_ext e /-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put `@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`, `12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the original expression is equal to the rewritten expression. Failure is used to indicate that this tactic does not apply to the term. For performance reasons, it is best to detect non-applicability as soon as possible so that the next tactic can have a go, so generally it will start with a pattern match and then checking that the arguments to the term are numerals or of the appropriate form, followed by proof construction, which should not fail. Propositions are treated like any other term. The normal form for propositions is `true` or `false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be used to help here. -/ @[user_attribute] protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit := { name := `norm_num, descr := "Add norm_num derivers", cache_cfg := { mk_cache := λ ns, do { t ← ns.mfoldl (λ (t : expr → tactic (expr × expr)) n, do t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []), pure (λ e, t' e <|> t e)) (λ _, failed), pure (λ e, derive.step e <|> t e) }, dependencies := [] } } add_tactic_doc { name := "norm_num", category := doc_category.attr, decl_names := [`norm_num.attr], tags := ["arithmetic", "decision_procedure"] } /-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with additional reduction procedures. -/ meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache /-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/ meta def derive' (step : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← step e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) /-- Simplify an expression bottom-up using the default `norm_num` set to simplify the subexpressions. -/ meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e end norm_num /-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num1 (step : expr → tactic (expr × expr)) (loc : interactive.loc) : tactic unit := do ns ← loc.get_locals, success ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction, monad.unlessb success $ done <|> fail "norm_num failed to simplify" /-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num (step : expr → tactic (expr × expr)) (hs : list simp_arg_type) (l : interactive.loc) : tactic unit := repeat1 $ orelse' (tactic.norm_num1 step l) $ interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none])) ff (simp_arg_type.except ``one_div :: hs) [] l >> skip namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do f ← get_step, tactic.norm_num1 f loc /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := do f ← get_step, tactic.norm_num f hs l add_hint_tactic "norm_num" /-- Normalizes a numerical expression and tries to close the goal with the result. -/ meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. ```lean import data.real.basic example : (2 : ℝ) + 2 = 4 := by norm_num example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num example : (73 : ℝ) < 789/2 := by norm_num example : 123456789 + 987654321 = 1111111110 := by norm_num example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num example : nat.prime (2^13 - 1) := by norm_num example : ¬ nat.prime (2^11 - 1) := by norm_num example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption ``` The variant `norm_num1` does not call `simp`. Both `norm_num` and `norm_num1` can be called inside the `conv` tactic. The tactic `apply_normed` normalises a numerical expression and tries to close the goal with the result. Compare: ```lean def a : ℕ := 2^100 #print a -- 2 ^ 100 def normed_a : ℕ := by apply_normed 2^100 #print normed_a -- 1267650600228229401496703205376 ``` -/ add_tactic_doc { name := "norm_num", category := doc_category.tactic, decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num, `tactic.interactive.apply_normed], tags := ["arithmetic", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 : conv unit := replace_lhs derive /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) [] { discharger := tactic.interactive.norm_num1 (loc.ns [none]) } end conv.interactive
dbb5602ef5247bce5741d87e702f743fb5445826
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/jacobson_ideal_auto.lean
dd62361e6fb3d8010607e336237cf8a8f21f35b4
[]
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
7,959
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Devon Tuma -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.ideal.operations import Mathlib.ring_theory.polynomial.basic import Mathlib.PostPort universes u v namespace Mathlib /-! # Jacobson radical The Jacobson radical of a ring `R` is defined to be the intersection of all maximal ideals of `R`. This is similar to how the nilradical is equal to the intersection of all prime ideals of `R`. We can extend the idea of the nilradical to ideals of `R`, by letting the radical of an ideal `I` be the intersection of prime ideals containing `I`. Under this extension, the original nilradical is the radical of the zero ideal `⊥`. Here we define the Jacobson radical of an ideal `I` in a similar way, as the intersection of maximal ideals containing `I`. ## Main definitions Let `R` be a commutative ring, and `I` be an ideal of `R` * `jacobson I` is the jacobson radical, i.e. the infimum of all maximal ideals containing I. * `is_local I` is the proposition that the jacobson radical of `I` is itself a maximal ideal ## Main statements * `mem_jacobson_iff` gives a characterization of members of the jacobson of I * `is_local_of_is_maximal_radical`: if the radical of I is maximal then so is the jacobson radical ## Tags Jacobson, Jacobson radical, Local Ideal -/ namespace ideal /-- The Jacobson radical of `I` is the infimum of all maximal ideals containing `I`. -/ def jacobson {R : Type u} [comm_ring R] (I : ideal R) : ideal R := Inf (set_of fun (J : ideal R) => I ≤ J ∧ is_maximal J) theorem le_jacobson {R : Type u} [comm_ring R] {I : ideal R} : I ≤ jacobson I := fun (x : R) (hx : x ∈ I) => iff.mpr mem_Inf fun (J : ideal R) (hJ : J ∈ set_of fun (J : ideal R) => I ≤ J ∧ is_maximal J) => and.left hJ x hx @[simp] theorem jacobson_idem {R : Type u} [comm_ring R] {I : ideal R} : jacobson (jacobson I) = jacobson I := sorry theorem radical_le_jacobson {R : Type u} [comm_ring R] {I : ideal R} : radical I ≤ jacobson I := le_Inf fun (J : ideal R) (hJ : J ∈ set_of fun (J : ideal R) => I ≤ J ∧ is_maximal J) => Eq.symm (radical_eq_Inf I) ▸ Inf_le { left := and.left hJ, right := is_maximal.is_prime (and.right hJ) } theorem eq_radical_of_eq_jacobson {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I → radical I = I := fun (h : jacobson I = I) => le_antisymm (le_trans radical_le_jacobson (le_of_eq h)) le_radical @[simp] theorem jacobson_top {R : Type u} [comm_ring R] : jacobson ⊤ = ⊤ := iff.mpr eq_top_iff le_jacobson @[simp] theorem jacobson_eq_top_iff {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = ⊤ ↔ I = ⊤ := sorry theorem jacobson_eq_bot {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = ⊥ → I = ⊥ := fun (h : jacobson I = ⊥) => iff.mpr eq_bot_iff (h ▸ le_jacobson) theorem jacobson_eq_self_of_is_maximal {R : Type u} [comm_ring R] {I : ideal R} [H : is_maximal I] : jacobson I = I := le_antisymm (Inf_le { left := le_of_eq rfl, right := H }) le_jacobson protected instance jacobson.is_maximal {R : Type u} [comm_ring R] {I : ideal R} [H : is_maximal I] : is_maximal (jacobson I) := { left := fun (htop : jacobson I = ⊤) => and.left H (iff.mp jacobson_eq_top_iff htop), right := fun (J : ideal R) (hJ : jacobson I < J) => and.right H J (lt_of_le_of_lt le_jacobson hJ) } theorem mem_jacobson_iff {R : Type u} [comm_ring R] {I : ideal R} {x : R} : x ∈ jacobson I ↔ ∀ (y : R), ∃ (z : R), x * y * z + z - 1 ∈ I := sorry /-- An ideal equals its Jacobson radical iff it is the intersection of a set of maximal ideals. Allowing the set to include ⊤ is equivalent, and is included only to simplify some proofs. -/ theorem eq_jacobson_iff_Inf_maximal {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ ∃ (M : set (ideal R)), (∀ (J : ideal R), J ∈ M → is_maximal J ∨ J = ⊤) ∧ I = Inf M := sorry theorem eq_jacobson_iff_Inf_maximal' {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ ∃ (M : set (ideal R)), (∀ (J : ideal R), J ∈ M → ∀ (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := sorry /-- An ideal `I` equals its Jacobson radical if and only if every element outside `I` also lies outside of a maximal ideal containing `I`. -/ theorem eq_jacobson_iff_not_mem {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ ∀ (x : R), ¬x ∈ I → ∃ (M : ideal R), (I ≤ M ∧ is_maximal M) ∧ ¬x ∈ M := sorry theorem map_jacobson_of_surjective {R : Type u} [comm_ring R] {I : ideal R} {S : Type v} [comm_ring S] {f : R →+* S} (hf : function.surjective ⇑f) : ring_hom.ker f ≤ I → map f (jacobson I) = jacobson (map f I) := sorry theorem map_jacobson_of_bijective {R : Type u} [comm_ring R] {I : ideal R} {S : Type v} [comm_ring S] {f : R →+* S} (hf : function.bijective ⇑f) : map f (jacobson I) = jacobson (map f I) := map_jacobson_of_surjective (and.right hf) (le_trans (le_of_eq (iff.mp (ring_hom.injective_iff_ker_eq_bot f) (and.left hf))) bot_le) theorem comap_jacobson {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] {f : R →+* S} {K : ideal S} : comap f (jacobson K) = Inf (comap f '' set_of fun (J : ideal S) => K ≤ J ∧ is_maximal J) := trans (comap_Inf' f (set_of fun (J : ideal S) => K ≤ J ∧ is_maximal J)) (Eq.symm Inf_eq_infi) theorem comap_jacobson_of_surjective {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] {f : R →+* S} (hf : function.surjective ⇑f) {K : ideal S} : comap f (jacobson K) = jacobson (comap f K) := sorry theorem mem_jacobson_bot {R : Type u} [comm_ring R] {x : R} : x ∈ jacobson ⊥ ↔ ∀ (y : R), is_unit (x * y + 1) := sorry /-- An ideal `I` of `R` is equal to its Jacobson radical if and only if the Jacobson radical of the quotient ring `R/I` is the zero ideal -/ theorem jacobson_eq_iff_jacobson_quotient_eq_bot {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ jacobson ⊥ = ⊥ := sorry /-- The standard radical and Jacobson radical of an ideal `I` of `R` are equal if and only if the nilradical and Jacobson radical of the quotient ring `R/I` coincide -/ theorem radical_eq_jacobson_iff_radical_quotient_eq_jacobson_bot {R : Type u} [comm_ring R] {I : ideal R} : radical I = jacobson I ↔ radical ⊥ = jacobson ⊥ := sorry theorem jacobson_mono {R : Type u} [comm_ring R] {I : ideal R} {J : ideal R} : I ≤ J → jacobson I ≤ jacobson J := sorry theorem jacobson_radical_eq_jacobson {R : Type u} [comm_ring R] {I : ideal R} : jacobson (radical I) = jacobson I := sorry theorem jacobson_bot_polynomial_le_Inf_map_maximal {R : Type u} [comm_ring R] : jacobson ⊥ ≤ Inf (map polynomial.C '' set_of fun (J : ideal R) => is_maximal J) := sorry theorem jacobson_bot_polynomial_of_jacobson_bot {R : Type u} [comm_ring R] (h : jacobson ⊥ = ⊥) : jacobson ⊥ = ⊥ := sorry /-- An ideal `I` is local iff its Jacobson radical is maximal. -/ def is_local {R : Type u} [comm_ring R] (I : ideal R) := is_maximal (jacobson I) theorem is_local_of_is_maximal_radical {R : Type u} [comm_ring R] {I : ideal R} (hi : is_maximal (radical I)) : is_local I := sorry theorem is_local.le_jacobson {R : Type u} [comm_ring R] {I : ideal R} {J : ideal R} (hi : is_local I) (hij : I ≤ J) (hj : J ≠ ⊤) : J ≤ jacobson I := sorry theorem is_local.mem_jacobson_or_exists_inv {R : Type u} [comm_ring R] {I : ideal R} (hi : is_local I) (x : R) : x ∈ jacobson I ∨ ∃ (y : R), y * x - 1 ∈ I := sorry theorem is_primary_of_is_maximal_radical {R : Type u} [comm_ring R] {I : ideal R} (hi : is_maximal (radical I)) : is_primary I := sorry end Mathlib
2962419e0f9c868ab6163fb5fd68f7adf0be5b8e
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/ExamPractice/officeHoursExam2.lean
b27b8fa48af9af6bd48799b0ab434aeb17f163ec
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
481
lean
def my_reverse {α : Type} : list α → list α | list.nil := list.nil | (list.cons h t) := list.append (my_reverse t) (list.cons h list.nil) #eval my_reverse [1,2,3] -- Look over translating from logic to english -- looking at pEval /- def pEval : pExp → (var → bool) → bool | (litExp b) i := b | (varExp v) i := i v | (unOpExp op e) i := (interpUnOp op) (pEval e i) | (binOpExp op e1 e2) i := (interpBinOp op) (pEval e1 i) (pEval e2 i) -/
9c63afad8a93e71170d18e977d92b252d9fab199
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/metric_space/baire.lean
7a400cf2d405d2fdb3b152db6080577311494e70
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,819
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.specific_limits import order.filter.countable_Inter import topology.G_delta /-! # Baire theorem In a complete metric space, a countable intersection of dense open subsets is dense. The good concept underlying the theorem is that of a Gδ set, i.e., a countable intersection of open sets. Then Baire theorem can also be formulated as the fact that a countable intersection of dense Gδ sets is a dense Gδ set. We prove Baire theorem, giving several different formulations that can be handy. We also prove the important consequence that, if the space is covered by a countable union of closed sets, then the union of their interiors is dense. The names of the theorems do not contain the string "Baire", but are instead built from the form of the statement. "Baire" is however in the docstring of all the theorems, to facilitate grep searches. We also define the filter `residual α` generated by dense `Gδ` sets and prove that this filter has the countable intersection property. -/ noncomputable theory open_locale classical topological_space filter open filter encodable set variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} section Baire_theorem open emetric ennreal variables [emetric_space α] [complete_space α] /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here when the source space is ℕ (and subsumed below by `dense_Inter_of_open` working with any encodable source space). -/ theorem dense_Inter_of_open_nat {f : ℕ → set α} (ho : ∀n, is_open (f n)) (hd : ∀n, dense (f n)) : dense (⋂n, f n) := begin let B : ℕ → ennreal := λn, 1/2^n, have Bpos : ∀n, 0 < B n, { intro n, simp only [B, one_div, one_mul, ennreal.inv_pos], exact pow_ne_top two_ne_top }, /- Translate the density assumption into two functions `center` and `radius` associating to any n, x, δ, δpos a center and a positive radius such that `closed_ball center radius` is included both in `f n` and in `closed_ball x δ`. We can also require `radius ≤ (1/2)^(n+1)`, to ensure we get a Cauchy sequence later. -/ have : ∀n x δ, δ > 0 → ∃y r, r > 0 ∧ r ≤ B (n+1) ∧ closed_ball y r ⊆ (closed_ball x δ) ∩ f n, { assume n x δ δpos, have : x ∈ closure (f n) := hd n x, rcases emetric.mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, xy⟩, rw edist_comm at xy, obtain ⟨r, rpos, hr⟩ : ∃ r > 0, closed_ball y r ⊆ f n := nhds_basis_closed_eball.mem_iff.1 (is_open_iff_mem_nhds.1 (ho n) y ys), refine ⟨y, min (min (δ/2) r) (B (n+1)), _, _, λz hz, ⟨_, _⟩⟩, show 0 < min (min (δ / 2) r) (B (n+1)), from lt_min (lt_min (ennreal.half_pos δpos) rpos) (Bpos (n+1)), show min (min (δ / 2) r) (B (n+1)) ≤ B (n+1), from min_le_right _ _, show z ∈ closed_ball x δ, from calc edist z x ≤ edist z y + edist y x : edist_triangle _ _ _ ... ≤ (min (min (δ / 2) r) (B (n+1))) + (δ/2) : add_le_add hz (le_of_lt xy) ... ≤ δ/2 + δ/2 : add_le_add (le_trans (min_le_left _ _) (min_le_left _ _)) (le_refl _) ... = δ : ennreal.add_halves δ, show z ∈ f n, from hr (calc edist z y ≤ min (min (δ / 2) r) (B (n+1)) : hz ... ≤ r : le_trans (min_le_left _ _) (min_le_right _ _)) }, choose! center radius H using this, refine λ x, (mem_closure_iff_nhds_basis nhds_basis_closed_eball).2 (λ ε εpos, _), /- `ε` is positive. We have to find a point in the ball of radius `ε` around `x` belonging to all `f n`. For this, we construct inductively a sequence `F n = (c n, r n)` such that the closed ball `closed_ball (c n) (r n)` is included in the previous ball and in `f n`, and such that `r n` is small enough to ensure that `c n` is a Cauchy sequence. Then `c n` converges to a limit which belongs to all the `f n`. -/ let F : ℕ → (α × ennreal) := λn, nat.rec_on n (prod.mk x (min ε (B 0))) (λn p, prod.mk (center n p.1 p.2) (radius n p.1 p.2)), let c : ℕ → α := λn, (F n).1, let r : ℕ → ennreal := λn, (F n).2, have rpos : ∀n, r n > 0, { assume n, induction n with n hn, exact lt_min εpos (Bpos 0), exact (H n (c n) (r n) hn).1 }, have rB : ∀n, r n ≤ B n, { assume n, induction n with n hn, exact min_le_right _ _, exact (H n (c n) (r n) (rpos n)).2.1 }, have incl : ∀n, closed_ball (c (n+1)) (r (n+1)) ⊆ (closed_ball (c n) (r n)) ∩ (f n) := λn, (H n (c n) (r n) (rpos n)).2.2, have cdist : ∀n, edist (c n) (c (n+1)) ≤ B n, { assume n, rw edist_comm, have A : c (n+1) ∈ closed_ball (c (n+1)) (r (n+1)) := mem_closed_ball_self, have I := calc closed_ball (c (n+1)) (r (n+1)) ⊆ closed_ball (c n) (r n) : subset.trans (incl n) (inter_subset_left _ _) ... ⊆ closed_ball (c n) (B n) : closed_ball_subset_closed_ball (rB n), exact I A }, have : cauchy_seq c := cauchy_seq_of_edist_le_geometric_two _ one_ne_top cdist, -- as the sequence `c n` is Cauchy in a complete space, it converges to a limit `y`. rcases cauchy_seq_tendsto_of_complete this with ⟨y, ylim⟩, -- this point `y` will be the desired point. We will check that it belongs to all -- `f n` and to `ball x ε`. use y, simp only [exists_prop, set.mem_Inter], have I : ∀n, ∀m ≥ n, closed_ball (c m) (r m) ⊆ closed_ball (c n) (r n), { assume n, refine nat.le_induction _ (λm hnm h, _), { exact subset.refl _ }, { exact subset.trans (incl m) (subset.trans (inter_subset_left _ _) h) }}, have yball : ∀n, y ∈ closed_ball (c n) (r n), { assume n, refine is_closed_ball.mem_of_tendsto ylim _, refine (filter.eventually_ge_at_top n).mono (λ m hm, _), exact I n m hm mem_closed_ball_self }, split, show ∀n, y ∈ f n, { assume n, have : closed_ball (c (n+1)) (r (n+1)) ⊆ f n := subset.trans (incl n) (inter_subset_right _ _), exact this (yball (n+1)) }, show edist y x ≤ ε, from le_trans (yball 0) (min_le_left _ _), end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_open {S : set (set α)} (ho : ∀s∈S, is_open s) (hS : countable S) (hd : ∀s∈S, dense s) : dense (⋂₀S) := begin cases S.eq_empty_or_nonempty with h h, { simp [h] }, { rcases hS.exists_surjective h with ⟨f, hf⟩, have F : ∀n, f n ∈ S := λn, by rw hf; exact mem_range_self _, rw [hf, sInter_range], exact dense_Inter_of_open_nat (λn, ho _ (F n)) (λn, hd _ (F n)) } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_open {S : set β} {f : β → set α} (ho : ∀s∈S, is_open (f s)) (hS : countable S) (hd : ∀s∈S, dense (f s)) : dense (⋂s∈S, f s) := begin rw ← sInter_image, apply dense_sInter_of_open, { rwa ball_image_iff }, { exact hS.image _ }, { rwa ball_image_iff } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_open [encodable β] {f : β → set α} (ho : ∀s, is_open (f s)) (hd : ∀s, dense (f s)) : dense (⋂s, f s) := begin rw ← sInter_range, apply dense_sInter_of_open, { rwa forall_range_iff }, { exact countable_range _ }, { rwa forall_range_iff } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_Gδ {S : set (set α)} (ho : ∀s∈S, is_Gδ s) (hS : countable S) (hd : ∀s∈S, dense s) : dense (⋂₀S) := begin -- the result follows from the result for a countable intersection of dense open sets, -- by rewriting each set as a countable intersection of open sets, which are of course dense. choose T hT using ho, have : ⋂₀ S = ⋂₀ (⋃s∈S, T s ‹_›) := (sInter_bUnion (λs hs, (hT s hs).2.2)).symm, rw this, refine dense_sInter_of_open _ (hS.bUnion (λs hs, (hT s hs).2.1)) _; simp only [set.mem_Union, exists_prop]; rintro t ⟨s, hs, tTs⟩, show is_open t, { exact (hT s hs).1 t tTs }, show dense t, { intro x, have := hd s hs x, rw (hT s hs).2.2 at this, exact closure_mono (sInter_subset_of_mem tTs) this } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_Gδ [encodable β] {f : β → set α} (ho : ∀s, is_Gδ (f s)) (hd : ∀s, dense (f s)) : dense (⋂s, f s) := begin rw ← sInter_range, exact dense_sInter_of_Gδ (forall_range_iff.2 ‹_›) (countable_range _) (forall_range_iff.2 ‹_›) end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_Gδ {S : set β} {f : Π x ∈ S, set α} (ho : ∀s∈S, is_Gδ (f s ‹_›)) (hS : countable S) (hd : ∀s∈S, dense (f s ‹_›)) : dense (⋂s∈S, f s ‹_›) := begin rw bInter_eq_Inter, haveI := hS.to_encodable, exact dense_Inter_of_Gδ (λ s, ho s s.2) (λ s, hd s s.2) end /-- Baire theorem: the intersection of two dense Gδ sets is dense. -/ theorem dense.inter_of_Gδ {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) (hsc : dense s) (htc : dense t) : dense (s ∩ t) := begin rw [inter_eq_Inter], apply dense_Inter_of_Gδ; simp [bool.forall_bool, *] end /-- A property holds on a residual (comeagre) set if and only if it holds on some dense `Gδ` set. -/ lemma eventually_residual {p : α → Prop} : (∀ᶠ x in residual α, p x) ↔ ∃ (t : set α), is_Gδ t ∧ dense t ∧ ∀ x ∈ t, p x := calc (∀ᶠ x in residual α, p x) ↔ ∀ᶠ x in ⨅ (t : set α) (ht : is_Gδ t ∧ dense t), 𝓟 t, p x : by simp only [residual, infi_and] ... ↔ ∃ (t : set α) (ht : is_Gδ t ∧ dense t), ∀ᶠ x in 𝓟 t, p x : mem_binfi (λ t₁ h₁ t₂ h₂, ⟨t₁ ∩ t₂, ⟨h₁.1.inter h₂.1, dense.inter_of_Gδ h₁.1 h₂.1 h₁.2 h₂.2⟩, by simp⟩) ⟨univ, is_Gδ_univ, dense_univ⟩ ... ↔ _ : by simp [and_assoc] /-- A set is residual (comeagre) if and only if it includes a dense `Gδ` set. -/ lemma mem_residual {s : set α} : s ∈ residual α ↔ ∃ t ⊆ s, is_Gδ t ∧ dense t := (@eventually_residual α _ _ (λ x, x ∈ s)).trans $ exists_congr $ λ t, by rw [exists_prop, and_comm (t ⊆ s), subset_def, and_assoc] instance : countable_Inter_filter (residual α) := ⟨begin intros S hSc hS, simp only [mem_residual] at *, choose T hTs hT using hS, refine ⟨⋂ s ∈ S, T s ‹_›, _, _, _⟩, { rw [sInter_eq_bInter], exact Inter_subset_Inter (λ s, Inter_subset_Inter $ hTs s) }, { exact is_Gδ_bInter hSc (λ s hs, (hT s hs).1) }, { exact dense_bInter_of_Gδ (λ s hs, (hT s hs).1) hSc (λ s hs, (hT s hs).2) } end⟩ /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bUnion_interior_of_closed {S : set β} {f : β → set α} (hc : ∀s∈S, is_closed (f s)) (hS : countable S) (hU : (⋃s∈S, f s) = univ) : dense (⋃s∈S, interior (f s)) := begin let g := λs, (frontier (f s))ᶜ, have : dense (⋂s∈S, g s), { refine dense_bInter_of_open (λs hs, _) hS (λs hs, _), show is_open (g s), from is_open_compl_iff.2 is_closed_frontier, show dense (g s), { intro x, simp [interior_frontier (hc s hs)] }}, refine this.mono _, show (⋂s∈S, g s) ⊆ (⋃s∈S, interior (f s)), assume x hx, have : x ∈ ⋃s∈S, f s, { have := mem_univ x, rwa ← hU at this }, rcases mem_bUnion_iff.1 this with ⟨s, hs, xs⟩, have : x ∈ g s := mem_bInter_iff.1 hx s hs, have : x ∈ interior (f s), { have : x ∈ f s \ (frontier (f s)) := mem_inter xs this, simpa [frontier, xs, (hc s hs).closure_eq] using this }, exact mem_bUnion_iff.2 ⟨s, ⟨hs, this⟩⟩ end /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with `⋃₀`. -/ theorem dense_sUnion_interior_of_closed {S : set (set α)} (hc : ∀s∈S, is_closed s) (hS : countable S) (hU : (⋃₀ S) = univ) : dense (⋃s∈S, interior s) := by rw sUnion_eq_bUnion at hU; exact dense_bUnion_interior_of_closed hc hS hU /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Union_interior_of_closed [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : dense (⋃s, interior (f s)) := begin rw ← bUnion_univ, apply dense_bUnion_interior_of_closed, { simp [hc] }, { apply countable_encodable }, { rwa ← bUnion_univ at hU } end /-- One of the most useful consequences of Baire theorem: if a countable union of closed sets covers the space, then one of the sets has nonempty interior. -/ theorem nonempty_interior_of_Union_of_closed [nonempty α] [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : ∃s, (interior $ f s).nonempty := begin by_contradiction h, simp only [not_exists, not_nonempty_iff_eq_empty] at h, have := calc ∅ = closure (⋃s, interior (f s)) : by simp [h] ... = univ : (dense_Union_interior_of_closed hc hU).closure_eq, exact univ_nonempty.ne_empty this.symm end end Baire_theorem
51b30e6c8569aa4a86ecce967af6414f3487dc49
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/category/Top/open_nhds_auto.lean
5ace4ab3a969f58a9cd01c63a2e46e0239a25b35
[]
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
4,737
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.category.Top.opens import Mathlib.category_theory.filtered import Mathlib.PostPort universes u namespace Mathlib namespace topological_space def open_nhds {X : Top} (x : ↥X) := Subtype fun (U : opens ↥X) => x ∈ U namespace open_nhds protected instance partial_order {X : Top} (x : ↥X) : partial_order (open_nhds x) := partial_order.mk (fun (U V : open_nhds x) => subtype.val U ≤ subtype.val V) (preorder.lt._default fun (U V : open_nhds x) => subtype.val U ≤ subtype.val V) sorry sorry sorry protected instance lattice {X : Top} (x : ↥X) : lattice (open_nhds x) := lattice.mk (fun (U V : open_nhds x) => { val := subtype.val U ⊔ subtype.val V, property := sorry }) partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry (fun (U V : open_nhds x) => { val := subtype.val U ⊓ subtype.val V, property := sorry }) sorry sorry sorry protected instance order_top {X : Top} (x : ↥X) : order_top (open_nhds x) := order_top.mk { val := ⊤, property := trivial } partial_order.le partial_order.lt sorry sorry sorry sorry protected instance open_nhds_category {X : Top} (x : ↥X) : category_theory.category (open_nhds x) := eq.mpr sorry (category_theory.full_subcategory fun (U : opens ↥X) => x ∈ U) protected instance opens_nhds_hom_has_coe_to_fun {X : Top} {x : ↥X} {U : open_nhds x} {V : open_nhds x} : has_coe_to_fun (U ⟶ V) := has_coe_to_fun.mk (fun (f : U ⟶ V) => ↥(subtype.val U) → ↥(subtype.val V)) fun (f : U ⟶ V) (x_1 : ↥(subtype.val U)) => { val := ↑x_1, property := sorry } /-- The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets. -/ def inf_le_left {X : Top} {x : ↥X} (U : open_nhds x) (V : open_nhds x) : U ⊓ V ⟶ U := category_theory.hom_of_le sorry /-- The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets. -/ def inf_le_right {X : Top} {x : ↥X} (U : open_nhds x) (V : open_nhds x) : U ⊓ V ⟶ V := category_theory.hom_of_le sorry def inclusion {X : Top} (x : ↥X) : open_nhds x ⥤ opens ↥X := category_theory.full_subcategory_inclusion fun (U : opens ↥X) => x ∈ U @[simp] theorem inclusion_obj {X : Top} (x : ↥X) (U : opens ↥X) (p : x ∈ U) : category_theory.functor.obj (inclusion x) { val := U, property := p } = U := rfl protected instance open_nhds_is_filtered {X : Top} (x : ↥X) : category_theory.is_filtered (open_nhds xᵒᵖ) := category_theory.is_filtered.mk def map {X : Top} {Y : Top} (f : X ⟶ Y) (x : ↥X) : open_nhds (coe_fn f x) ⥤ open_nhds x := category_theory.functor.mk (fun (U : open_nhds (coe_fn f x)) => { val := category_theory.functor.obj (opens.map f) (subtype.val U), property := sorry }) fun (U V : open_nhds (coe_fn f x)) (i : U ⟶ V) => category_theory.functor.map (opens.map f) i @[simp] theorem map_obj {X : Top} {Y : Top} (f : X ⟶ Y) (x : ↥X) (U : opens ↥Y) (q : coe_fn f x ∈ U) : category_theory.functor.obj (map f x) { val := U, property := q } = { val := category_theory.functor.obj (opens.map f) U, property := q } := rfl @[simp] theorem map_id_obj {X : Top} (x : ↥X) (U : open_nhds (coe_fn 𝟙 x)) : category_theory.functor.obj (map 𝟙 x) U = U := sorry @[simp] theorem map_id_obj' {X : Top} (x : ↥X) (U : set ↥X) (p : is_open U) (q : coe_fn 𝟙 x ∈ { val := U, property := p }) : category_theory.functor.obj (map 𝟙 x) { val := { val := U, property := p }, property := q } = { val := { val := U, property := p }, property := q } := rfl @[simp] theorem map_id_obj_unop {X : Top} (x : ↥X) (U : open_nhds xᵒᵖ) : category_theory.functor.obj (map 𝟙 x) (opposite.unop U) = opposite.unop U := sorry @[simp] theorem op_map_id_obj {X : Top} (x : ↥X) (U : open_nhds xᵒᵖ) : category_theory.functor.obj (category_theory.functor.op (map 𝟙 x)) U = U := sorry def inclusion_map_iso {X : Top} {Y : Top} (f : X ⟶ Y) (x : ↥X) : inclusion (coe_fn f x) ⋙ opens.map f ≅ map f x ⋙ inclusion x := category_theory.nat_iso.of_components (fun (U : open_nhds (coe_fn f x)) => category_theory.iso.mk 𝟙 𝟙) sorry @[simp] theorem inclusion_map_iso_hom {X : Top} {Y : Top} (f : X ⟶ Y) (x : ↥X) : category_theory.iso.hom (inclusion_map_iso f x) = 𝟙 := rfl @[simp] theorem inclusion_map_iso_inv {X : Top} {Y : Top} (f : X ⟶ Y) (x : ↥X) : category_theory.iso.inv (inclusion_map_iso f x) = 𝟙 := rfl end Mathlib
56dcec045698bf8ef234eacc2163f4f0bb8a0445
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/determinant.lean
a236e674c7bf3f597426ad75e6f35f1986fa2a91
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,892
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.matrix.pequiv import Mathlib.data.fintype.card import Mathlib.group_theory.perm.sign import Mathlib.algebra.algebra.basic import Mathlib.tactic.ring import Mathlib.linear_algebra.alternating import Mathlib.PostPort universes u v w z u_1 namespace Mathlib namespace matrix /-- The determinant of a matrix given by the Leibniz formula. -/ def det {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) : R := finset.sum finset.univ fun (σ : equiv.perm n) => ↑↑(coe_fn equiv.perm.sign σ) * finset.prod finset.univ fun (i : n) => M (coe_fn σ i) i @[simp] theorem det_diagonal {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {d : n → R} : det (diagonal d) = finset.prod finset.univ fun (i : n) => d i := sorry @[simp] theorem det_zero {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (h : Nonempty n) : det 0 = 0 := sorry @[simp] theorem det_one {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : det 1 = 1 := sorry theorem det_eq_one_of_card_eq_zero {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := sorry theorem det_mul_aux {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {M : matrix n n R} {N : matrix n n R} {p : n → n} (H : ¬function.bijective p) : (finset.sum finset.univ fun (σ : equiv.perm n) => ↑↑(coe_fn equiv.perm.sign σ) * finset.prod finset.univ fun (x : n) => M (coe_fn σ x) (p x) * N (p x) x) = 0 := sorry @[simp] theorem det_mul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) (N : matrix n n R) : det (matrix.mul M N) = det M * det N := sorry protected instance det.is_monoid_hom {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : is_monoid_hom det := is_monoid_hom.mk det_one /-- Transposing a matrix preserves the determinant. -/ @[simp] theorem det_transpose {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) : det (transpose M) = det M := sorry /-- The determinant of a permutation matrix equals its sign. -/ @[simp] theorem det_permutation {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (σ : equiv.perm n) : det (pequiv.to_matrix (equiv.to_pequiv σ)) = ↑(coe_fn equiv.perm.sign σ) := sorry /-- Permuting the columns changes the sign of the determinant. -/ theorem det_permute {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (σ : equiv.perm n) (M : matrix n n R) : (det fun (i : n) => M (coe_fn σ i)) = ↑(coe_fn equiv.perm.sign σ) * det M := sorry @[simp] theorem det_smul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A := sorry theorem ring_hom.map_det {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {S : Type w} [comm_ring S] {M : matrix n n R} {f : R →+* S} : coe_fn f (det M) = det (coe_fn (ring_hom.map_matrix f) M) := sorry theorem alg_hom.map_det {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {S : Type w} [comm_ring S] [algebra R S] {T : Type z} [comm_ring T] [algebra R T] {M : matrix n n S} {f : alg_hom R S T} : coe_fn f (det M) = det (coe_fn (ring_hom.map_matrix ↑f) M) := sorry /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ theorem det_eq_zero_of_row_eq_zero {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {A : matrix n n R} (i : n) (h : ∀ (j : n), A i j = 0) : det A = 0 := sorry theorem det_eq_zero_of_column_eq_zero {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {A : matrix n n R} (j : n) (h : ∀ (i : n), A i j = 0) : det A = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (det A = 0)) (Eq.symm (det_transpose A)))) (det_eq_zero_of_row_eq_zero j h) /-- If a matrix has a repeated row, the determinant will be zero. -/ theorem det_zero_of_row_eq {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {M : matrix n n R} {i : n} {j : n} (i_ne_j : i ≠ j) (hij : M i = M j) : det M = 0 := sorry theorem det_update_column_add {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) (j : n) (u : n → R) (v : n → R) : det (update_column M j (u + v)) = det (update_column M j u) + det (update_column M j v) := sorry theorem det_update_row_add {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) (j : n) (u : n → R) (v : n → R) : det (update_row M j (u + v)) = det (update_row M j u) + det (update_row M j v) := sorry theorem det_update_column_smul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column M j (s • u)) = s * det (update_column M j u) := sorry theorem det_update_row_smul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row M j (s • u)) = s * det (update_row M j u) := sorry /-- `det` is an alternating multilinear map over the rows of the matrix. See also `is_basis.det`. -/ def det_row_multilinear {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : alternating_map R (n → R) R n := alternating_map.mk det sorry sorry sorry @[simp] theorem det_block_diagonal {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] {o : Type u_1} [fintype o] [DecidableEq o] (M : o → matrix n n R) : det (block_diagonal M) = finset.prod finset.univ fun (k : o) => det (M k) := sorry
e2279b0deb6365482c07ce121aecdca0f586589f
0bd6c950c82dcba3e46dc8d8acb5ecc60b917520
/inclusion_exclusion.lean
4867418ccd61eeca7a03625fcd39644f5e0a239a
[]
no_license
truonghoangle/formalabstracts
976dbbdede5c71346a3c534a8f319456248d4610
b889ec60143315053a51b1829a5dc4d82ba503b3
refs/heads/master
1,584,899,948,798
1,537,184,894,000
1,537,184,894,000
140,428,980
0
0
null
null
null
null
UTF-8
Lean
false
false
2,526
lean
import data.real.basic data.finset data.set.lattice data.nat.choose analysis.measure_theory.measurable_space analysis.measure_theory.measure_space open real namespace inclusion_exclusion_finset variables α β : Type instance :lattice.semilattice_inf_top (finset β) := sorry theorem inclusion_exclusion_usual [decidable_eq β] {s : finset α} {t : α → finset β}: (((s.bind t).card):ℝ) = ((finset.range (s.card + 1)).filter (λ k, k>0)).sum (λ k, (-1:ℝ)^( k+1) * ((finset.powerset s).filter (λ s₁:finset α, s₁.card=k)).sum (λ s₁:finset α, (s₁.inf t).card)) := sorry instance :decidable_pred (λ (s₁ : finset α), ¬s₁ = ∅):= sorry theorem inclusion_exclusion [decidable_eq β] {s : finset α} {t : α → finset β}: (((s.bind t).card):ℝ) = ((finset.powerset s).filter (λ s₁, (s₁ ≠ ∅))).sum (λ s₁:finset α, (-1:ℝ)^(s₁.card+1) * (s₁.inf t).card) := sorry theorem special_inclusion_exclusion [decidable_eq β] {s : finset α} {t : α → finset β} (f:ℕ → ℕ) (h:∀ k A, A∈ (finset.powerset s).filter (λ s₁:finset α, s₁.card =k) → (A.inf t).card=f k): (((s.bind t).card):ℝ) = ((finset.range (s.card + 1)).filter (λ k, k>0)).sum (λ k, (-1:ℝ)^( k+1) * (choose (s.card) k) * (f k)) := sorry theorem Mobius_inclusion_exclusion {g f:finset α → ℝ} (h: ∀ A, g A= (finset.powerset A).sum (λ s, f s)): ∀ A, f A= (finset.powerset A).sum (λ s, (-1:ℝ)^(A.card -s.card) * g s) := sorry theorem inclusion_exclusion_sysmetric {g f:finset α → ℝ} (h: ∀ A, g A= (finset.powerset A).sum (λ s, (-1)^(s.card)* f s)): ∀ A, f A= (finset.powerset A).sum (λ s, (-1:ℝ)^(s.card) * g s) := sorry end inclusion_exclusion_finset namespace measure_inclusion_exclusion variables α β : Type variables [measurable_space β ] {μ: measure_theory.measure β } variables{s : finset α} {t : α → set β} variables (h: ∀ i, i∈ s→ is_measurable (t i)) variables (hfin: ∀ i, i∈ s→ μ (t i)< ⊤) theorem measure_inclusion_exclusion: μ (⋃b∈s, t b)+ ((finset.range (s.card + 1)).filter (λ n, n>0 ∧ n % 2=0)).sum (λ k, ((finset.powerset s).filter (λ s₁:finset α, s₁.card=k)).sum (λ s₁:finset α,μ (⋂b∈s₁, t b))) =((finset.range (s.card + 1)).filter (λ n, n>0 ∧ n % 2=1)).sum (λ k, ((finset.powerset s).filter (λ s₁:finset α, s₁.card=k)).sum (λ s₁:finset α,μ (⋂b∈s₁, t b))) := sorry end measure_inclusion_exclusion
3d5f10f7b8e7db79a3276898caa9840274228603
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/unique_factorization_domain.lean
29f8b4dd4830b51dffac8e725c7bc2197fb1b5b2
[ "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
60,784
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson -/ import algebra.big_operators.associated import algebra.gcd_monoid.basic import data.finsupp.multiset import ring_theory.noetherian import ring_theory.multiplicity /-! # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop := (well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _)) export wf_dvd_monoid (well_founded_dvd_not_unit) @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring.wf_dvd_monoid [comm_ring α] [is_domain α] [is_noetherian_ring α] : wf_dvd_monoid α := ⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _), ext, exact ideal.span_singleton_lt_span_singleton.symm }⟩ namespace wf_dvd_monoid variables [comm_monoid_with_zero α] open associates nat theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α := ⟨begin haveI := h, refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ variables [wf_dvd_monoid α] instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) := ⟨begin refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) := subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit local attribute [elab_as_eliminator] well_founded.fix lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_rfl⟩) (well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, hi.2.trans (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a := wf_dvd_monoid.induction_on_irreducible a (λ h, (h rfl).elim) (λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i ::ₘ s, ⟨by clear _let_match; { intros b H, cases (multiset.mem_cons.mp H), { convert hii }, { exact hs.1 b h } }, by { rw multiset.prod_cons, exact hs.2.mul_left _ }⟩⟩) end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates [cancel_comm_monoid_with_zero α] (h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α := wf_dvd_monoid.of_wf_dvd_monoid_associates ⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩ theorem wf_dvd_monoid.iff_well_founded_associates [cancel_comm_monoid_with_zero α] : wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) := ⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- unique factorization monoids. These are defined as `cancel_comm_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_exists_unique_irreducible_factors` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factors` -/ class unique_factorization_monoid (α : Type*) [cancel_comm_monoid_with_zero α] extends wf_dvd_monoid α : Prop := (irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a) /-- Can't be an instance because it would cause a loop `ufm → wf_dvd_monoid → ufm → ...`. -/ @[reducible] lemma ufm_of_gcd_of_wf_dvd_monoid [cancel_comm_monoid_with_zero α] [wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α := { irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime .. ‹wf_dvd_monoid α› } instance associates.ufm [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α] : unique_factorization_monoid (associates α) := { irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff, apply unique_factorization_monoid.irreducible_iff_prime, } .. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) } end prio namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α] theorem exists_prime_factors (a : α) : a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a := by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime, apply wf_dvd_monoid.exists_factors a } @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := begin simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃, exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃, end lemma factors_unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit (is_unit_iff_dvd_one.2 ((multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_monoid lemma prime_factors_unique [cancel_comm_monoid_with_zero α] : ∀ {f g : multiset α}, (∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem $ λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit $ is_unit_iff_dvd_one.2 $ (multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this)) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (hf p (by simp)) (λ q hq, hg _ hq) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)), end) /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ lemma prime_factors_irreducible [cancel_comm_monoid_with_zero α] {a : α} {f : multiset α} (ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) : ∃ p, a ~ᵤ p ∧ f = {p} := begin haveI := classical.dec_eq α, refine multiset.induction_on f (λ h, (ha.not_unit (associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1, rintros p s _ ⟨u, hu⟩ hs, use p, have hs0 : s = 0, { by_contra hs0, obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0, apply (hs q (by simp [hq])).2.1, refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _, { rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu, mul_comm, mul_comm p _, mul_assoc], simp, }, apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _), apply (hs p (multiset.mem_cons_self _ _)).2.1 }, simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *, exact ⟨associated.symm ⟨u, hu⟩, rfl⟩, end section exists_prime_factors variables [cancel_comm_monoid_with_zero α] variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) include pf lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α := ⟨begin classical, refine rel_hom_class.well_founded (rel_hom.mk _ _ : (dvd_not_unit : α → α → Prop) →r ((<) : with_top ℕ → with_top ℕ → Prop)) (with_top.well_founded_lt nat.lt_wf), { intro a, by_cases h : a = 0, { exact ⊤ }, exact (classical.some (pf a h)).card }, rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩, rw dif_neg ane0, by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] }, rw [dif_neg h, with_top.coe_lt_coe], have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] }, calc multiset.card (classical.some (pf a ane0)) < _ + multiset.card (classical.some (pf c cne0)) : lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _))) ... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) : (multiset.card_add _ _).symm ... = multiset.card (classical.some (pf b h)) : multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _), { convert (classical.some_spec (pf c cne0)).2.symm, rw [con, multiset.prod_zero] }, { intros x hadd, rw multiset.mem_add at hadd, cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd }, { rw multiset.prod_add, transitivity a * c, { apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 }, { rw ← b_eq, apply (classical.some_spec (pf _ _)).2.symm, } } end⟩ lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p := begin by_cases hp0 : p = 0, { simp [hp0] }, refine ⟨λ h, _, prime.irreducible⟩, obtain ⟨f, hf⟩ := pf p hp0, obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf, rw hq.prime_iff, exact hf.1 q (multiset.mem_singleton_self _) end theorem unique_factorization_monoid.of_exists_prime_factors : unique_factorization_monoid α := { irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf, .. wf_dvd_monoid.of_exists_prime_factors pf } end exists_prime_factors theorem unique_factorization_monoid.iff_exists_prime_factors [cancel_comm_monoid_with_zero α] : unique_factorization_monoid α ↔ (∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) := ⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h, unique_factorization_monoid.of_exists_prime_factors⟩ theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) (p : α) : irreducible p ↔ prime p := ⟨by letI := classical.dec_eq α; exact λ hpi, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0, have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0, begin cases eif x hx0 with fx hfx, cases eif a ha0 with fa hfa, cases eif b hb0 with fb hfb, have h : multiset.rel associated (p ::ₘ fx) (fa + fb), { apply uif, { exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), }, { exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), }, calc multiset.prod (p ::ₘ fx) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact hfx.2.mul_left _ ... ~ᵤ (fa).prod * (fb).prod : hfa.2.symm.mul_mul hfb.2.symm ... = _ : by rw multiset.prod_add, }, exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ hq.dvd_iff_dvd_left.2 $ hfa.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ hq.dvd_iff_dvd_left.2 $ hfb.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqb)) end⟩, prime.irreducible⟩ theorem unique_factorization_monoid.of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) : unique_factorization_monoid α := unique_factorization_monoid.of_exists_prime_factors (by { convert eif, simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif }) namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero α] [decidable_eq α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else classical.some (unique_factorization_monoid.exists_prime_factors a h) theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a := begin rw [factors, dif_neg ane0], exact (classical.some_spec (exists_prime_factors a ane0)).2 end theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x := begin rw [factors], split_ifs with ane0, { simp only [multiset.not_mem_zero, forall_false_left, forall_const] }, intros x hx, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx, end theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x := λ x h, (prime_of_factor x h).irreducible lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ factors b) (factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _)) irreducible_of_factor (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ factors b) : by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) end unique_factorization_monoid namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero α] [decidable_eq α] [normalization_monoid α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def normalized_factors (a : α) : multiset α := multiset.map normalize $ factors a theorem normalized_factors_prod {a : α} (ane0 : a ≠ 0) : associated (normalized_factors a).prod a := begin rw [normalized_factors, factors, dif_neg ane0], refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2, rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk, multiset.map_map], congr' 2, ext, rw [function.comp_apply, associates.mk_normalize], end theorem prime_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → prime x := begin rw [normalized_factors, factors], split_ifs with ane0, { simp }, intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩, rw (normalize_associated _).prime_iff, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy, end theorem irreducible_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → irreducible x := λ x h, (prime_of_normalized_factor x h).irreducible theorem normalize_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → normalize x = x := begin rw [normalized_factors, factors], split_ifs with h, { simp }, intros x hx, obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx, apply normalize_idem end lemma normalized_factors_irreducible {a : α} (ha : irreducible a) : normalized_factors a = {normalize a} := begin obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha ⟨prime_of_normalized_factor, normalized_factors_prod ha.ne_zero⟩, have p_mem : p ∈ normalized_factors a, { rw hp, exact multiset.mem_singleton_self _ }, convert hp, rwa [← normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated] end lemma exists_mem_normalized_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ normalized_factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ normalized_factors b) (normalized_factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_normalized_factor _)) irreducible_of_normalized_factor (associated.symm $ calc multiset.prod (normalized_factors a) ~ᵤ a : normalized_factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ normalized_factors b) : by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) @[simp] lemma normalized_factors_zero : normalized_factors (0 : α) = 0 := by simp [normalized_factors, factors] @[simp] lemma normalized_factors_one : normalized_factors (1 : α) = 0 := begin nontriviality α using [normalized_factors, factors], rw ← multiset.rel_zero_right, apply factors_unique irreducible_of_normalized_factor, { intros x hx, exfalso, apply multiset.not_mem_zero x hx }, { simp [normalized_factors_prod (@one_ne_zero α _ _)] }, apply_instance end @[simp] lemma normalized_factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : normalized_factors (x * y) = normalized_factors x + normalized_factors y := begin have h : (normalize : α → α) = associates.out ∘ associates.mk, { ext, rw [function.comp_apply, associates.out_mk], }, rw [← multiset.map_id' (normalized_factors (x * y)), ← multiset.map_id' (normalized_factors x), ← multiset.map_id' (normalized_factors y), ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm, ← multiset.map_map associates.out], refine congr rfl _, apply multiset.map_mk_eq_map_mk_of_rel, apply factors_unique, { intros x hx, rcases multiset.mem_add.1 hx with hx | hx; exact irreducible_of_normalized_factor x hx }, { exact irreducible_of_normalized_factor }, { rw multiset.prod_add, exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans (normalized_factors_prod (mul_ne_zero hx hy)).symm } end @[simp] lemma normalized_factors_pow {x : α} (n : ℕ) : normalized_factors (x ^ n) = n • normalized_factors x := begin induction n with n ih, { simp }, by_cases h0 : x = 0, { simp [h0, zero_pow n.succ_pos, smul_zero] }, rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih], end lemma dvd_iff_normalized_factors_le_normalized_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : x ∣ y ↔ normalized_factors x ≤ normalized_factors y := begin split, { rintro ⟨c, rfl⟩, simp [hx, right_ne_zero_of_mul hy] }, { rw [← (normalized_factors_prod hx).dvd_iff_dvd_left, ← (normalized_factors_prod hy).dvd_iff_dvd_right], apply multiset.prod_dvd_prod_of_le } end lemma zero_not_mem_normalized_factors (x : α) : (0 : α) ∉ normalized_factors x := λ h, prime.ne_zero (prime_of_normalized_factor _ h) rfl lemma dvd_of_mem_normalized_factors {a p : α} (H : p ∈ normalized_factors a) : p ∣ a := begin by_cases hcases : a = 0, { rw hcases, exact dvd_zero p }, { exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) }, end end unique_factorization_monoid namespace unique_factorization_monoid open_locale classical open multiset associates noncomputable theory variables [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] /-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/ protected def normalization_monoid : normalization_monoid α := normalization_monoid_of_monoid_hom_right_inverse { to_fun := λ a : associates α, if a = 0 then 0 else ((normalized_factors a).map (classical.some mk_surjective.has_right_inverse : associates α → α)).prod, map_one' := by simp, map_mul' := λ x y, by { by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, simp [hx, hy] } } begin intro x, dsimp, by_cases hx : x = 0, { simp [hx] }, have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) = (id : associates α → associates α), { ext x, rw [function.comp_apply, mk_monoid_hom_apply, classical.some_spec mk_surjective.has_right_inverse x], refl }, rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id, ← associated_iff_eq], apply normalized_factors_prod hx end instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩ end unique_factorization_monoid namespace unique_factorization_monoid variables {R : Type*} [cancel_comm_monoid_with_zero R] [unique_factorization_monoid R] lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0) (h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d := λ d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (λ x hx _ _, hx) (λ d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) : (∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (λ h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0) (no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b, ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) : ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩ section multiplicity variables [nontrivial R] [normalization_monoid R] [decidable_eq R] variables [decidable_rel (has_dvd.dvd : R → R → Prop)] open multiplicity multiset lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : ℕ} (ha : irreducible a) (hb : b ≠ 0) : ↑n ≤ multiplicity a b ↔ repeat (normalize a) n ≤ normalized_factors b := begin rw ← pow_dvd_iff_le_multiplicity, revert b, induction n with n ih, { simp }, intros b hb, split, { rintro ⟨c, rfl⟩, rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb, rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ, normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, ← ih hb.2], apply dvd.intro _ rfl }, { rw [multiset.le_iff_exists_add], rintro ⟨u, hu⟩, rw [← (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat], exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) } end lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b ≠ 0) : multiplicity a b = (normalized_factors b).count (normalize a) := begin apply le_antisymm, { apply enat.le_of_lt_add_one, rw [← nat.cast_one, ← nat.cast_add, lt_iff_not_ge, ge_iff_le, le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], simp }, rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], end end multiplicity end unique_factorization_monoid namespace associates open unique_factorization_monoid associated multiset variables [cancel_comm_monoid_with_zero α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `normalized_factors` are only unique up to associated elements, while the multisets in `factor_set α` are unique by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [cancel_comm_monoid_with_zero α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑(a + b) : factor_set α) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_rfl | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h theorem factor_set.prod_eq_zero_iff [nontrivial α] (p : factor_set α) : p.prod = 0 ↔ p = ⊤ := begin induction p using with_top.rec_top_coe, { simp only [iff_self, eq_self_iff_true, associates.prod_top] }, simp only [prod_coe, with_top.coe_ne_top, iff_false, prod_eq_zero_iff, multiset.mem_map], rintro ⟨⟨a, ha⟩, -, eq⟩, rw [subtype.coe_mk] at eq, exact ha.ne_zero eq, end /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) : factor_set α → ℕ | none := 0 | (some s) := s.count p variables [dec_irr : Π (p : associates α), decidable (irreducible p)] include dec_irr /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count [decidable_eq (associates α)] (p : associates α) : factor_set α → ℕ := if hp : irreducible p then bcount ⟨p, hp⟩ else 0 @[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) (s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:= by { dunfold count, split_ifs, refl } @[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) : count p (0 : factor_set α) = 0 := by { dunfold count, split_ifs, refl } lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) : count p = 0 := dif_neg hp omit dec_irr /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop | _ ⊤ := true | p (some l) := p ∈ l include dec_irr /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set α`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem (p : associates α) (s : factor_set α) : Prop := if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩ @[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) : factor_set_mem p s = (p ∈ s) := rfl lemma mem_factor_set_top {p : associates α} {hp : irreducible p} : p ∈ (⊤ : factor_set α) := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial end lemma mem_factor_set_some {p : associates α} {hp : irreducible p} {l : multiset {a : associates α // irreducible a }} : p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl end lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p) (s : factor_set α) : ¬ p ∈ s := λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false), by rwa [dif_neg hp] at h omit dec_irr variable [unique_factorization_monoid α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _), { exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end theorem factor_set.unique [nontrivial α] {p q : factor_set α} (h : p.prod = q.prod) : p = q := begin induction p using with_top.rec_top_coe; induction q using with_top.rec_top_coe, { refl }, { rw [eq_comm, ←factor_set.prod_eq_zero_iff, ←h, associates.prod_top] }, { rw [←factor_set.prod_eq_zero_iff, h, associates.prod_top] }, { congr' 1, rw ←multiset.map_eq_map subtype.coe_injective, apply unique' _ _ h; { intros a ha, obtain ⟨⟨a', irred⟩, -, rfl⟩ := multiset.mem_map.mp ha, rwa [subtype.coe_mk] } }, end theorem prod_le_prod_iff_le [nontrivial α] {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin classical, rintros ⟨c, eqc⟩, refine multiset.le_iff_exists_add.2 ⟨factors c, unique' hq (λ x hx, _) _⟩, { obtain h|h := multiset.mem_add.1 hx, { exact hp x h }, { exact irreducible_of_factor _ h } }, { rw [eqc, multiset.prod_add], congr, refine associated_iff_eq.mp (factors_prod (λ hc, _)).symm, refine not_irreducible_zero (hq _ _), rw [←prod_eq_zero_iff, eqc, hc, mul_zero] } end prod_le_prod variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)] include dec /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors' (a : α) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩) (irreducible_of_factor) @[simp] theorem map_subtype_coe_factors' {a : α} : (factors' a).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (h : a ~ᵤ b) : factors' a = factors' b := begin obtain rfl|hb := eq_or_ne b 0, { rw associated_zero_iff_eq_zero at h, rw h }, have ha : a ≠ 0, { contrapose! hb with ha, rw [←associated_zero_iff_eq_zero, ←ha], exact h.symm }, rw [←multiset.map_eq_map subtype.coe_injective, map_subtype_coe_factors', map_subtype_coe_factors', ←rel_associated_iff_map_eq_map], exact factors_unique irreducible_of_factor irreducible_of_factor ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), end include dec' /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a := by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) } @[simp] theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem prod_factors [nontrivial α] (s : factor_set α) : s.prod.factors = s := factor_set.unique $ factors_prod _ @[nontriviality] lemma factors_subsingleton [subsingleton α] {a : associates α} : a.factors = option.none := by { convert factors_0; apply_instance } lemma factors_eq_none_iff_zero {a : associates α} : a.factors = option.none ↔ a = 0 := begin nontriviality α, exact ⟨λ h, by rwa [← factors_prod a, factor_set.prod_eq_zero_iff], λ h, h.symm ▸ factors_0⟩ end lemma factors_eq_some_iff_ne_zero {a : associates α} : (∃ (s : multiset {p : associates α // irreducible p}), a.factors = some s) ↔ a ≠ 0 := by rw [← option.is_some_iff_exists, ← option.ne_none_iff_is_some, ne.def, ne.def, factors_eq_none_iff_zero] theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec dec' theorem eq_of_prod_eq_prod [nontrivial α] {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec dec' dec_irr theorem eq_factors_of_eq_counts {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (h : ∀ (p : associates α) (hp : irreducible p), p.count a.factors = p.count b.factors) : a.factors = b.factors := begin obtain ⟨sa, h_sa⟩ := factors_eq_some_iff_ne_zero.mpr ha, obtain ⟨sb, h_sb⟩ := factors_eq_some_iff_ne_zero.mpr hb, rw [h_sa, h_sb] at h ⊢, rw option.some_inj, have h_count : ∀ (p : associates α) (hp : irreducible p), sa.count ⟨p, hp⟩ = sb.count ⟨p, hp⟩, { intros p hp, rw [← count_some, ← count_some, h p hp] }, apply multiset.to_finsupp.injective, ext ⟨p, hp⟩, rw [multiset.to_finsupp_apply, multiset.to_finsupp_apply, h_count p hp] end theorem eq_of_eq_counts {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (h : ∀ (p : associates α), irreducible p → p.count a.factors = p.count b.factors) : a = b := eq_of_factors_eq_factors (eq_factors_of_eq_counts ha hb h) omit dec_irr @[simp] theorem factors_mul [nontrivial α] (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono [nontrivial α] : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le [nontrivial α] {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec dec' theorem prod_le [nontrivial α] {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec dec' noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ noncomputable instance [nontrivial α] : lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order } lemma sup_mul_inf [nontrivial α] (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end include dec_irr lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := begin by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p }, obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0, rw [← associates.factors_prod a], rw [← ha', factors_mk a0 nza] at hm ⊢, erw prod_coe, apply multiset.dvd_prod, apply multiset.mem_map.mpr, exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩ end omit dec' lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0} (h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a := by { haveI := classical.dec_eq (associates α), apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp, rw factors_mk _ hz, apply mem_factor_set_some.2 h_mem } omit dec_irr lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a := begin obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd, apply multiset.mem_pmap.mpr, use q, use hq, exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq)) end include dec_irr lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 }, { apply mem_factors'_of_dvd ha0 } end include dec' lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : (associates.mk p) ∈ factors (associates.mk a) := begin rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd) end lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp }, { apply mem_factors_of_dvd ha0 hp } end lemma exists_prime_dvd_of_not_inf_one {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) : ∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b := begin have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0, { contrapose! h with hf, change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1, rw hf, exact multiset.prod_zero }, rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz, obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz), rw multiset.inf_eq_inter at p0_mem, obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0, refine ⟨p, _, _, _⟩, { rw [← irreducible_iff_prime, ← irreducible_mk], exact p0_irr }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left, apply ha, }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right, apply hb } end theorem coprime_iff_inf_one [nontrivial α] {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) : (associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d := begin split, { intros hg p ha hb hp, refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _), rw ← hg, exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) }, { contrapose, intros hg hc, obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg, exact hc hpa hpb hp } end omit dec_irr theorem factors_prime_pow [nontrivial α] {p : associates α} (hp : irreducible p) (k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) := eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat, multiset.prod_repeat, subtype.coe_mk]) include dec_irr theorem prime_pow_dvd_iff_le [nontrivial α] {m p : associates α} (h₁ : m ≠ 0) (h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors := begin obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁, rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le, ← factors_le, factors_prime_pow h₂, factors_mk _ nz], exact with_top.coe_le_coe end theorem le_of_count_ne_zero [nontrivial α] {m p : associates α} (h0 : m ≠ 0) (hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m := begin rw [← pos_iff_ne_zero], intro h, rw [← pow_one p], apply (prime_pow_dvd_iff_le h0 hp).2, simpa only end theorem count_ne_zero_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p).count (associates.mk a).factors ≠ 0 ↔ p ∣ a := begin nontriviality α, rw ← associates.mk_le_mk_iff_dvd_iff, refine ⟨λ h, associates.le_of_count_ne_zero (associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp) h, λ h, _⟩, { rw [← pow_one (associates.mk p), associates.prime_pow_dvd_iff_le (associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp)] at h, exact (zero_lt_one.trans_le h).ne' } end theorem count_mul [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) : count p (factors (a * b)) = count p a.factors + count p b.factors := begin obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha, obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb, rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add, ← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp, multiset.count_add, count_some hp, count_some hp] end theorem count_of_coprime [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) : count p a.factors = 0 ∨ count p b.factors = 0 := begin rw [or_iff_not_imp_left, ← ne.def], intro hca, contrapose! hab with hcb, exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb, (irreducible_iff_prime.mp hp)⟩, end theorem count_mul_of_coprime [nontrivial α] {a : associates α} {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors := begin by_cases ha : a = 0, { simp [ha], }, cases count_of_coprime ha hb hab hp with hz hb0, { tauto }, apply or.intro_right, rw [count_mul ha hb hp, hb0, add_zero] end theorem count_mul_of_coprime' [nontrivial α] {a b : associates α} {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p (a * b).factors = count p a.factors ∨ count p (a * b).factors = count p b.factors := begin by_cases ha : a = 0, { simp [ha], }, by_cases hb : b = 0, { simp [hb], }, rw [count_mul ha hb hp], cases count_of_coprime ha hb hab hp with ha0 hb0, { apply or.intro_right, rw [ha0, zero_add] }, { apply or.intro_left, rw [hb0, add_zero] } end theorem dvd_count_of_dvd_count_mul [nontrivial α] {a b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors := begin by_cases ha : a = 0, { simpa [*] using habk, }, cases count_of_coprime ha hb hab hp with hz h, { rw hz, exact dvd_zero k }, { rw [count_mul ha hb hp, h] at habk, exact habk } end omit dec_irr @[simp] lemma factors_one [nontrivial α] : factors (1 : associates α) = 0 := begin apply eq_of_prod_eq_prod, rw associates.factors_prod, exact multiset.prod_zero, end @[simp] theorem pow_factors [nontrivial α] {a : associates α} {k : ℕ} : (a ^ k).factors = k • a.factors := begin induction k with n h, { rw [zero_nsmul, pow_zero], exact factors_one }, { rw [pow_succ, succ_nsmul, factors_mul, h] } end include dec_irr lemma count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : count p (a ^ k).factors = k * count p a.factors := begin induction k with n h, { rw [pow_zero, factors_one, zero_mul, count_zero hp] }, { rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring } end theorem dvd_count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right } theorem is_pow_of_dvd_count [nontrivial α] {a : associates α} (ha : a ≠ 0) {k : ℕ} (hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) : ∃ (b : associates α), a = b ^ k := begin obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha, rw [factors_mk a0 hz] at hk, have hk' : ∀ p, p ∈ (factors' a0) → k ∣ (factors' a0).count p, { rintros p -, have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] }, rw [pp, ← count_some p.2], exact hk p.val p.2 }, obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk', use (u : factor_set α).prod, apply eq_of_factors_eq_factors, rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu], exact with_bot.coe_nsmul u k end omit dec omit dec_irr omit dec' theorem eq_pow_of_mul_eq_pow [nontrivial α] {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : associates α), a = d ^ k := begin classical, by_cases hk0 : k = 0, { use 1, rw [hk0, pow_zero] at h ⊢, apply (mul_eq_one_iff.1 h).1 }, { refine is_pow_of_dvd_count ha _, intros p hp, apply dvd_count_of_dvd_count_mul hb hp hab, rw h, apply dvd_count_pow _ hp, rintros rfl, rw zero_pow' _ hk0 at h, cases mul_eq_zero.mp h; contradiction } end end associates section open associates unique_factorization_monoid lemma associates.quot_out {α : Type*} [comm_monoid α] (a : associates α): associates.mk (quot.out (a)) = a := by rw [←quot_mk_eq_mk, quot.out_eq] /-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α := { gcd := λa b, quot.out (associates.mk a ⊓ associates.mk b : associates α), lcm := λa b, quot.out (associates.mk a ⊔ associates.mk b : associates α), gcd_dvd_left := λ a b, by { rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le], exact inf_le_left }, gcd_dvd_right := λ a b, by { rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le], exact inf_le_right }, dvd_gcd := λ a b c hac hab, by { rw [←mk_dvd_mk, (associates.mk c ⊓ associates.mk b).quot_out, dvd_eq_le, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff], exact ⟨hac, hab⟩ }, lcm_zero_left := λ a, by { have : associates.mk (0 : α) = ⊤ := rfl, rw [this, top_sup_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, lcm_zero_right := λ a, by { have : associates.mk (0 : α) = ⊤ := rfl, rw [this, sup_top_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, gcd_mul_lcm := λ a b, by { rw [←mk_eq_mk_iff_associated, ←associates.mk_mul_mk, ←associated_iff_eq, associates.quot_out, associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } } /-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : normalized_gcd_monoid α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, by { rw [← out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk], exact normalize_associated (a * b) }, normalize_gcd := assume a b, by convert normalize_out _, normalize_lcm := assume a b, by convert normalize_out _, .. ‹normalization_monoid α› } end namespace unique_factorization_monoid /-- If `y` is a nonzero element of a unique factorization monoid with finitely many units (e.g. `ℤ`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/ noncomputable def fintype_subtype_dvd {M : Type*} [cancel_comm_monoid_with_zero M] [unique_factorization_monoid M] [fintype Mˣ] (y : M) (hy : y ≠ 0) : fintype {x // x ∣ y} := begin haveI : nontrivial M := ⟨⟨y, 0, hy⟩⟩, haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid, haveI := classical.dec_eq M, haveI := classical.dec_eq (associates M), -- We'll show `λ (u : Mˣ) (f ⊆ factors y) → u * Π f` is injective -- and has image exactly the divisors of `y`. refine fintype.of_finset (((normalized_factors y).powerset.to_finset.product (finset.univ : finset Mˣ)).image (λ s, (s.snd : M) * s.fst.prod)) (λ x, _), simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true, multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map], split, { rintros ⟨s, hs, rfl⟩, have prod_s_ne : s.fst.prod ≠ 0, { intro hz, apply hy (eq_zero_of_zero_dvd _), have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz, rw ← (normalized_factors_prod hy).dvd_iff_dvd_right, exact multiset.dvd_prod (multiset.mem_of_le hs hz) }, show (s.snd : M) * s.fst.prod ∣ y, rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul, ← (normalized_factors_prod hy).dvd_iff_dvd_right], exact multiset.prod_dvd_prod_of_le hs }, { rintro (h : x ∣ y), have hx : x ≠ 0, { refine mt (λ hx, _) hy, rwa [hx, zero_dvd_iff] at h }, obtain ⟨u, hu⟩ := normalized_factors_prod hx, refine ⟨⟨normalized_factors x, u⟩, _, (mul_comm _ _).trans hu⟩, exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h } end end unique_factorization_monoid section finsupp variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α] variables [normalization_monoid α] [decidable_eq α] open unique_factorization_monoid /-- This returns the multiset of irreducible factors as a `finsupp` -/ noncomputable def factorization (n : α) : α →₀ ℕ := (normalized_factors n).to_finsupp lemma factorization_eq_count {n p : α} : factorization n p = multiset.count p (normalized_factors n) := by simp [factorization] @[simp] lemma factorization_zero : factorization (0 : α) = 0 := by simp [factorization] @[simp] lemma factorization_one : factorization (1 : α) = 0 := by simp [factorization] /-- The support of `factorization n` is exactly the finset of normalized factors -/ @[simp] lemma support_factorization {n : α} : (factorization n).support = (normalized_factors n).to_finset := by simp [factorization, multiset.to_finsupp_support] /-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ @[simp] lemma factorization_mul {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : factorization (a * b) = factorization a + factorization b := by simp [factorization, normalized_factors_mul ha hb] /-- For any `p`, the power of `p` in `x^n` is `n` times the power in `x` -/ lemma factorization_pow {x : α} {n : ℕ} : factorization (x^n) = n • factorization x := by { ext, simp [factorization] } lemma associated_of_factorization_eq (a b: α) (ha: a ≠ 0) (hb: b ≠ 0) (h: factorization a = factorization b) : associated a b := begin simp only [factorization, add_equiv.apply_eq_iff_eq] at h, have ha' := normalized_factors_prod ha, rw h at ha', exact associated.trans ha'.symm (normalized_factors_prod hb), end end finsupp
22c8c0622fb694590e451ff52c86041e58eb75c4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/exceptional.lean
23a12dc203d60ae263b4fc9170014f34798521bd
[]
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
554
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.control.monad import Mathlib.Lean3Lib.init.meta.format import Mathlib.Lean3Lib.init.util namespace Mathlib /- Remark: we use a function that produces a format object as the exception information. Motivation: the formatting object may be big, and we may create it on demand. -/ /-- An exceptional is similar to `Result` in Haskell.-/
811b0f62afe28aa45c274834e527562b9b4c2443
d642a6b1261b2cbe691e53561ac777b924751b63
/src/analysis/specific_limits.lean
b00b7efc62a61f17f977ff8f0165531dc098d544
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
8,024
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 A collection of specific limit computations. -/ import analysis.normed_space.basic algebra.geom_sum import topology.instances.ennreal noncomputable theory open_locale classical open classical function lattice filter finset metric variables {α : Type*} {β : Type*} {ι : Type*} lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (nhds r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : r > 1) : tendsto (λn:ℕ, r ^ n) at_top at_top := tendsto_infi.2 $ assume p, tendsto_principal.2 $ let ⟨n, hn⟩ := exists_nat_gt (p / (r - 1)) in have hn_nn : (0:ℝ) ≤ n, from nat.cast_nonneg n, have r - 1 > 0, from sub_lt_iff_lt_add.mp $ by simp; assumption, have p ≤ r ^ n, from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm ... ≤ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn ... ≤ 1 + n * (r - 1) : le_add_of_nonneg_of_le zero_le_one (le_refl _) ... = 1 + add_monoid.smul n (r - 1) : by rw [add_monoid.smul_eq_mul] ... ≤ (1 + (r - 1)) ^ n : one_add_mul_le_pow (le_of_lt this) _ ... ≤ r ^ n : by simp; exact le_refl _, show {n | p ≤ r ^ n} ∈ at_top, from mem_at_top_sets.mpr ⟨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)⟩ lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (nhds 0) := tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu, mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb, have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb, ⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this, lt_of_one_div_lt_one_div hu $ begin rw [inv_eq_one_div], simp [-one_div_eq_inv, div_div_eq_mul_div, div_one], simp [this] end⟩⟩ lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (nhds 0) := by_cases (assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds]) (assume : r ≠ 0, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (nhds 0), from tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂), tendsto.congr' (univ_mem_sets' $ by simp *) this) lemma tendsto_pow_at_top_nhds_0_of_lt_1_normed_field {K : Type*} [normed_field K] {ξ : K} (_ : ∥ξ∥ < 1) : tendsto (λ n : ℕ, ξ^n) at_top (nhds 0) := begin rw[tendsto_iff_norm_tendsto_zero], convert tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg ξ) ‹∥ξ∥ < 1›, ext n, simp end lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) : tendsto (λn:ℕ, k ^ n) at_top at_top := tendsto_coe_nat_real_at_top_iff.1 $ have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h, by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (nhds 0) := tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_coe_nat_real_at_top_iff.2 tendsto_id) lemma tendsto_one_div_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1/(n : ℝ)) at_top (nhds 0) := by simpa only [inv_eq_one_div] using tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (nhds 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (nhds 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 tendsto_one_div_at_top_nhds_0_nat lemma has_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 / (1 - r)) := have r ≠ 1, from ne_of_lt h₂, have r + -1 ≠ 0, by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (nhds ((0 - 1) * (r - 1)⁻¹)), from tendsto_mul (tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂) tendsto_const_nhds) tendsto_const_nhds, have (λ n, (range n).sum (λ i, r ^ i)) = (λ n, geom_series r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at * lemma summable_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric h₁ h₂⟩ lemma tsum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑n:ℕ, r ^ n) = 1 / (1 - r) := tsum_eq_has_sum (has_sum_geometric h₁ h₂) lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : (∑n:ℕ, ((1:ℝ)/2) ^ n) = 2 := tsum_eq_has_sum has_sum_geometric_two lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum_mul_left (a / 2) (has_sum_geometric (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, rw ← pow_inv; [refl, exact two_ne_zero] }, { norm_num, rw div_mul_cancel _ two_ne_zero } end def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases summable_comp_of_summable_of_injective f (summable_spec hf) (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end lemma cauchy_seq_of_le_geometric [metric_space α] (r C : ℝ) (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) : cauchy_seq f := begin refine cauchy_seq_of_summable_dist (summable_of_norm_bounded (λn, C * r^n) _ _), { by_cases h : C = 0, { simp [h, summable_zero] }, { have Cpos : C > 0, { have := le_trans dist_nonneg (hu 0), simp only [mul_one, pow_zero] at this, exact lt_of_le_of_ne this (ne.symm h) }, have rnonneg: r ≥ 0, { have := le_trans dist_nonneg (hu 1), simp only [pow_one] at this, exact nonneg_of_mul_nonneg_left this Cpos }, refine summable_mul_left C _, exact summable_spec (@has_sum_geometric r rnonneg hr) }}, show ∀n, abs (dist (f n) (f (n+1))) ≤ C * r^n, { assume n, rw abs_of_nonneg (dist_nonneg), exact hu n } end namespace nnreal theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := dense hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε := begin rcases dense hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end end ennreal
a2745859e616f389faea6c469b83ab6001327304
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/lazy_list2.lean
5a56ba6ca5cef9d30c8a2c1bbfd316553a8d21d3
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,435
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Traversable instance for lazy_lists. -/ import category.traversable.equiv category.traversable.instances data.lazy_list universes u namespace thunk /-- Creates a thunk with a (non-lazy) constant value. -/ def mk {α} (x : α) : thunk α := λ _, x instance {α : Type u} [decidable_eq α] : decidable_eq (thunk α) | a b := have a = b ↔ a () = b (), from ⟨by cc, by intro; ext x; cases x; assumption⟩, by rw this; apply_instance end thunk namespace lazy_list open function def list_equiv_lazy_list (α : Type*) : list α ≃ lazy_list α := { to_fun := lazy_list.of_list, inv_fun := lazy_list.to_list, right_inv := by { intro, induction x, refl, simp! [*], ext, cases x, refl }, left_inv := by { intro, induction x, refl, simp! [*] } } instance {α : Type u} : inhabited (lazy_list α) := ⟨nil⟩ instance {α : Type u} [decidable_eq α] : decidable_eq (lazy_list α) | nil nil := is_true rfl | (cons x xs) (cons y ys) := if h : x = y then match decidable_eq (xs ()) (ys ()) with | is_false h2 := is_false (by intro; cc) | is_true h2 := have xs = ys, by ext u; cases u; assumption, is_true (by cc) end else is_false (by intro; cc) | nil (cons _ _) := is_false (by cc) | (cons _ _) nil := is_false (by cc) protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (f : α → m β) : lazy_list α → m (lazy_list β) | lazy_list.nil := pure lazy_list.nil | (lazy_list.cons x xs) := lazy_list.cons <$> f x <*> (thunk.mk <$> traverse (xs ())) instance : traversable lazy_list := { map := @lazy_list.traverse id _, traverse := @lazy_list.traverse } instance : is_lawful_traversable lazy_list := begin apply equiv.is_lawful_traversable' list_equiv_lazy_list; intros ; resetI; ext, { induction x, refl, simp! [equiv.map,functor.map] at *, simp [*], refl, }, { induction x, refl, simp! [equiv.map,functor.map_const] at *, simp [*], refl, }, { induction x, { simp! [traversable.traverse,equiv.traverse] with functor_norm, refl }, simp! [equiv.map,functor.map_const,traversable.traverse] at *, rw x_ih, dsimp [list_equiv_lazy_list,equiv.traverse,to_list,traversable.traverse,list.traverse], simp! with functor_norm, refl }, end end lazy_list
c4a7797b7f894c4c19ef51cd7783216a964ff0f5
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/metric_space/basic.lean
6e7507e211b4f18342ad90426bc81aae23b5310d
[ "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
102,428
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.int.interval import topology.algebra.ordered.compact import topology.metric_space.emetric_space /-! # Metric spaces This file defines metric spaces. Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity ## Main definitions * `has_dist α`: Endows a space `α` with a function `dist a b`. * `pseudo_metric_space α`: A space endowed with a distance function, which can be zero even if the two elements are non-equal. * `metric.ball x ε`: The set of all points `y` with `dist y x < ε`. * `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded. * `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`. Additional useful definitions: * `nndist a b`: `dist` as a function to the non-negative reals. * `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`. * `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`. * `proper_space α`: A `pseudo_metric_space` where all closed balls are compact. * `metric.diam s` : The `supr` of the distances of members of `s`. Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite. TODO (anyone): Add "Main results" section. ## Implementation notes Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize to `metric_space` at the end. ## Tags metric, pseudo_metric, dist -/ open set filter topological_space noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Construct a uniform structure core from a distance function and metric space axioms. This is a technical construction that can be immediately used to construct a uniform structure from a distance function and metric space axioms but is also useful when discussing metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/ def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α := { uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle) /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. -/ class pseudo_metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ℝ≥0∞ := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) variables [pseudo_metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := pseudo_metric_space.to_uniform_space @[priority 200] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩ /-- Construct a pseudo-metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) : pseudo_metric_space α := { dist := dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := { is_open_uniformity := begin dsimp only [uniform_space.core_of_dist], intros s, change is_open s ↔ _, rw H s, apply forall_congr, intro x, apply forall_congr, intro x_in, erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff, { apply exists_congr, intros ε, apply exists_congr, intros ε_pos, simp only [prod.forall, set_of_subset_set_of], split, { rintros h _ y H rfl, exact h y H }, { intros h y hxy, exact h _ _ hxy rfl } }, { exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ }, { apply_instance } end, ..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle }, uniformity_dist := rfl } @[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := pseudo_metric_space.edist_dist x y theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := pseudo_metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 } lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 } /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico_self, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) := nat.Ico_zero_eq_range n ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this zero_lt_two @[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b := abs_of_nonneg dist_nonneg /-- A version of `has_dist` that takes value in `ℝ≥0`. -/ class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0) export has_nndist (nndist) /-- Distance as a nonnegative real number. -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] } @[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y := (edist_nndist x y).symm @[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} : edist x y < c ↔ nndist x y < c := by rw [edist_nndist, ennreal.coe_lt_coe] @[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} : edist x y ≤ c ↔ nndist x y ≤ c := by rw [edist_nndist, ennreal.coe_le_coe] /--In a pseudometric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ := (edist_dist x y).symm ▸ ennreal.of_real_lt_top /--In a pseudometric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl @[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y := (dist_nndist x y).symm @[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} : dist x y < c ↔ nndist x y < c := iff.rfl @[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} : dist x y ≤ c ↔ nndist x y ≤ c := iff.rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) := by rw [dist_nndist, real.to_nnreal_coe] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := dist_triangle _ _ _ theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := dist_triangle_left _ _ _ theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := dist_triangle_right _ _ _ /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate pseudometric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := dist_nonneg.trans_lt hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption @[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε := ⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩ @[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt] @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty] lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } @[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x) @[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ := Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn, hn.trans (lt_add_one _) /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by { rw dist_comm, refl } theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption @[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε := ⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩ @[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le] theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq lemma ball_disjoint_ball (x y : α) (rx ry : ℝ) (h : rx + ry ≤ dist x y) : disjoint (ball x rx) (ball y ry) := begin rw disjoint_left, assume a ax ay, apply lt_irrefl (dist x y), calc dist x y ≤ dist x a + dist a y : dist_triangle _ _ _ ... < rx + ry : add_lt_add (mem_ball'.1 ax) (mem_ball.1 ay) ... ≤ dist x y : h end theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm] theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... < ε₁ + dist x y : add_lt_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_ball (h : ε₁ < ε₂) : closed_ball x ε₁ ⊆ ball x ε₂ := λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball (h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y ≤ ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2 lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2 lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := begin rw inter_comm at h, rw [add_comm, dist_comm], exact dist_lt_add_of_nonempty_closed_ball_inter_ball h end lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := dist_lt_add_of_nonempty_closed_ball_inter_ball $ h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl) @[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x) theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@zero_lt_two ℝ _ _)] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw ← pseudo_metric_space.uniformity_dist.symm, refine has_basis_binfi_principal _ nonempty_Ioi, exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, hn.le⟩) theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) := metric.mk_uniformity_basis (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) : (𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ r, and.left) $ λ r hr, ⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩, min_le_left _ _⟩ /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) := metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε := metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem eventually_nhds_iff {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y := mem_nhds_iff lemma eventually_nhds_iff_ball {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y := mem_nhds_iff theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1) theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1) theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open.mem_nhds is_open_ball (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball] theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] theorem continuous_iff [pseudo_metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } /-- A variant of `tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_top_order β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε := (at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} : is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x := by simp [is_open_iff, subset_singleton_iff, mem_ball] /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball centered at `x` and intersecting `s` only at `x`. -/ lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.ball x ε ∩ s = {x} := nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball of positive radius centered at `x` and intersecting `s` only at `x`. -/ lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.closed_ball x ε ∩ s = {x} := nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx end metric open metric /-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma pseudo_metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := pseudo_metric.uniformity_basis_edist.eq_binfi /-- A pseudometric space induces a pseudoemetric space -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α := { edist := edist, edist_self := by simp [edist_dist], edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹pseudo_metric_space α› } /-- In a pseudometric space, an open ball of infinite radius is the whole space -/ lemma metric.eball_top_eq_univ (x : α) : emetric.ball x ∞ = set.univ := set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x) /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h /-- Closed balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } @[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ := eq_univ_of_forall $ λ y, edist_lt_top _ _ /-- Build a new pseudometric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space') : pseudo_metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans pseudo_metric_space.uniformity_dist } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : pseudo_metric_space α := let m : pseudo_metric_space α := { dist := dist, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the emetric space. -/ def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a pseudometric space. -/ instance real.pseudo_metric_space : pseudo_metric_space ℝ := { dist := λx y, |x - y|, dist_self := by simp [abs_zero], dist_comm := assume x y, abs_sub_comm _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _ theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| := by simp [real.dist_eq] theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) : dist x y ≤ dist x z := by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) : dist y z ≤ dist x z := by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y') (hy : y ∈ interval x' y') : dist x y ≤ dist x' y' := abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap) theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ y' - x' := by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub] using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy) theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) : dist x y ≤ 1 := by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm] lemma real.ball_eq (x r : ℝ) : ball x r = Ioo (x - r) (x + r) := set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq, abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt] lemma real.closed_ball_eq {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] section metric_ordered variables [conditionally_complete_linear_order α] [order_topology α] lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) := is_compact_Icc.totally_bounded lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) := totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) := totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) := totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b) end metric_ordered /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the pseudometric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ |b N| : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) := λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, le_cSup (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq /-- Pseudometric space structure pulled back by a function. -/ def pseudo_metric_space.induced {α β} (f : α → β) (m : pseudo_metric_space β) : pseudo_metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β] (f : α → β) (h : uniform_inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.psudo_metric_space {α : Type*} {p : α → Prop} [t : pseudo_metric_space α] : pseudo_metric_space (subtype p) := pseudo_metric_space.induced coe t theorem subtype.pseudo_dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl section nnreal instance : pseudo_metric_space ℝ≥0 := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl lemma nnreal.nndist_eq (a b : ℝ≥0) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [sub_eq_zero_iff_le.2 h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs_eq_max_neg, neg_sub], apply max_eq_right, linarith [nnreal.coe_le_coe.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod instance prod.pseudo_metric_space_max [pseudo_metric_space β] : pseudo_metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, ← this.map_max] end, uniformity_dist := begin refine uniformity_prod.trans _, simp only [uniformity_basis_dist.eq_binfi, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [pseudo_metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl theorem ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] theorem closed_ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] end prod theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous.dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist.comp (hf.prod_mk hg) @[continuity] theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist.continuous @[continuity] theorem continuous.dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist.comp (hf.prod_mk hg : _) theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist _ lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist.continuous lemma continuous.nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist.comp (hf.prod_mk hg : _) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-characterization of the closure in pseudometric spaces-/ theorem mem_closure_iff {α : Type u} [pseudo_metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a end metric section pi open finset variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] /-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/ instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) := begin /- we construct the instance from the pseudoemetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ℝ≥0∞) < ⊤ := ennreal.coe_lt_top, simp [edist_pi_def, finset.sup_lt_iff this, edist_lt_top] }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, simp only [edist_nndist], norm_cast } end lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) := subtype.eta _ _ lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl @[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b := by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b) @[simp] lemma nndist_pi_const [nonempty β] (a b : α) : nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to ℝ≥0 using hr.le, simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)], end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to ℝ≥0 using hr, simp [nndist_pi_def] end lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g := by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) } lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g := by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b] /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'` for a version assuming `nonempty β` instead of `0 < r`. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = set.pi univ (λ b, ball (x b) r) := by { ext p, simp [dist_pi_lt_iff hr] } /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi` for a version assuming `0 < r` instead of `nonempty β`. -/ lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : ball x r = set.pi univ (λ b, ball (x b) r) := (lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr] /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'` for a version assuming `nonempty β` instead of `0 ≤ r`. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := by { ext p, simp [dist_pi_le_iff hr] } /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi` for a version assuming `0 ≤ r` instead of `nonempty β`. -/ lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := (le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr] lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ dist x' y' := begin refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans (dist_le_pi_dist _ _ b)); refine Icc_subset_interval _, exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩] end end pi section compact /-- Any compact set in a pseudometric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls end compact section proper_space open metric /-- A pseudometric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [pseudo_metric_space α] : Prop := (is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) /-- In a proper pseudometric space, all spheres are compact. -/ lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : is_compact (sphere x r) := compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) is_closed_sphere sphere_subset_closed_ball /-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/ instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : compact_space (sphere x r) := is_compact_iff_compact_space.mp (is_compact_sphere _ _) /-- A proper pseudo metric space is sigma compact, and therefore second countable. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin -- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't -- add an instance for `sigma_compact_space`. suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α, rcases em (nonempty α) with ⟨⟨x⟩⟩|hn, { exact ⟨⟨λ n, closed_ball x n, λ n, proper_space.is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ }, { exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ } end lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) : tendsto (λ y, dist y x) (cocompact α) at_top := (has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr, ⟨closed_ball x r, proper_space.is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩ lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) : tendsto (dist x) (cocompact α) at_top := by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact pseudometric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, is_closed_ball.is_compact⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $ λ x ε ε0, proper_space.is_compact_closed_ball _ _ /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩, have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y x yt xt).le), rcases (compact_iff_totally_bounded_complete.1 (proper_space.is_compact_closed_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, -, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply is_compact_univ_pi (λb, _), apply (h b).is_compact_closed_ball end variables [proper_space α] {x : α} {r : ℝ} {s : set α} /-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' ∈ Ioo 0 r, s ⊆ ball x r' := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne }, { exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ }, have : is_compact s, from compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) hs (subset.trans h ball_subset_closed_ball), obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x), from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on, have hyr : dist y x < r, from h hys, rcases exists_between hyr with ⟨r', hyr', hrr'⟩, exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩ end /-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' < r, s ⊆ ball x r' := begin cases le_or_lt r 0 with hr hr, { rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s }, exact (no_bot r).imp (λ r' hr', ⟨hr', empty_subset _⟩) }, { exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) } end end proper_space namespace metric section second_countable open topological_space /-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which is `ε`-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _), rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩, choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0), refine ⟨s, hsc, bUnion_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩, exact_mod_cast hyx x end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a pseudometric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.mono ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.mono hC } end lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r := (bounded_iff_subset_ball c).1 h lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := let ⟨C, h⟩ := h in ⟨C, λ a b ha hb, (is_closed_le' C).closure_subset $ map_mem_closure2 continuous_dist ha hb h⟩ alias bounded_closure_of_bounded ← metric.bounded.closure @[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s := ⟨λ h, h.mono subset_closure, λ h, h.closure⟩ /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.mono (by simp), h.mono (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A totally bounded set is bounded -/ lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s := -- We cover the totally bounded set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball /-- A compact set is bounded -/ lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s := -- A compact set is totally bounded, thus bounded h.totally_bounded.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.is_compact.bounded alias bounded_of_finite ← set.finite.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.mono (subset_univ _) lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) : is_compact s := begin unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) }, { exact is_compact_empty }, { rcases hb.subset_ball x with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) hc hr } end /-- The Heine–Borel theorem: In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [t2_space α] [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩ lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) := ⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩ section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] lemma bounded_Icc (a b : α) : bounded (Icc a b) := (totally_bounded_Icc a b).bounded lemma bounded_Ico (a b : α) : bounded (Ico a b) := (totally_bounded_Ico a b).bounded lemma bounded_Ioc (a b : α) : bounded (Ioc a b) := (totally_bounded_Ioc a b).bounded lemma bounded_Ioo (a b : α) : bounded (Ioo a b) := (totally_bounded_Ioo a b).bounded /-- In a pseudo metric space with a conditionally complete linear order such that the order and the metric structure give the same topology, any order-bounded set is metric-bounded. -/ lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) : bounded s := let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u) end conditionally_complete_linear_order end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top (ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy)) (λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ := by rwa [bounded_iff_ediam_ne_top, not_not] at h /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := by rw [diam, ediam_of_unbounded h, ennreal.top_to_real] /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.mono (subset_union_left _ _), have ht : bounded t, from H.mono (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (le_of_lt zero_lt_two) h) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α := begin refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _), rcases hs.bounded.subset_ball x with ⟨r, hr⟩, exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩ end lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α := by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) : comap (λ y, dist y x) at_top = cocompact α := (comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) : comap (dist x) at_top = cocompact α := (comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α) (h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) := by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff } namespace int open metric /-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/ lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) := begin refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _, simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball], change ∀ r : ℝ, finite (coe ⁻¹' (ball (0 : ℝ) r)), simp [real.ball_eq, set.finite_Ioo], end end int /-- We now define `metric_space`, extending `pseudo_metric_space`. -/ class metric_space (α : Type u) extends pseudo_metric_space α : Type u := (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) /-- Construct a metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) (eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α := { eq_of_dist_eq_zero := eq_of_dist_eq_zero, ..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H } variables {γ : Type w} [metric_space γ] theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero @[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y := by simpa only [not_iff_not] using dist_eq_zero @[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist] namespace metric variables {x : γ} {s : set γ} @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- If a `pseudo_metric_space` is separated, then it is a `metric_space`. -/ def of_t2_pseudo_metric_space {α : Type*} [pseudo_metric_space α] (h : separated_space α) : metric_space α := { eq_of_dist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_dist.1 hs, exact H (show dist x y < ε, by rwa [hdist]) end ..‹pseudo_metric_space α› } /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space γ := { eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, ..pseudo_metric_space.to_pseudo_emetric_space, } lemma is_closed_of_pairwise_on_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε) (hs : pairwise_on s (λ x y, ε ≤ dist x y)) : is_closed s := is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α] {ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : closed_embedding f := closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf /-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then `f` is a uniform embedding with respect to the discrete uniformity on `β`. -/ lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f := uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf end metric /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') : metric_space γ := { eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, ..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, ..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : metric_space β) : metric_space γ := { eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), ..pseudo_metric_space.induced f m.to_pseudo_metric_space } /-- Pull back a metric space structure by a uniform embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_embedding.comap_metric_space {α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) : metric_space α := (metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced coe (λ x y, subtype.ext) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl instance : metric_space empty := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, } instance : metric_space punit := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, } section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h, ..real.pseudo_metric_space } end real section nnreal instance : metric_space ℝ≥0 := subtype.metric_space end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (γ × β) := { eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, ..prod.pseudo_metric_space_max, } end prod section pi open finset variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ { eq_of_dist_eq_zero := assume f g eq0, begin have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero], have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1, simp only [finset.sup_le_iff] at eq2, exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b) end, ..pseudo_metric_space_pi } end pi namespace metric section second_countable open topological_space /-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric section eq_rel /-- The canonical equivalence relation on a pseudometric space. -/ def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α := setoid.mk (λx y, dist x y = 0) begin unfold equivalence, repeat { split }, { exact pseudo_metric_space.dist_self }, { assume x y h, rwa pseudo_metric_space.dist_comm }, { assume x y z hxy hyz, refine le_antisymm _ dist_nonneg, calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _ ... = 0 + 0 : by rw [hxy, hyz] ... = 0 : by simp } end local attribute [instance] pseudo_metric.dist_setoid /-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/ @[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* := quotient (pseudo_metric.dist_setoid α) instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] : has_dist (pseudo_metric_quot α) := { dist := quotient.lift₂ (λp q : α, dist p q) begin assume x y x' y' hxx' hyy', have Hxx' : dist x x' = 0 := hxx', have Hyy' : dist y y' = 0 := hyy', have A : dist x y ≤ dist x' y' := calc dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _ ... = dist x' y : by simp [Hxx'] ... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _ ... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'], have B : dist x' y' ≤ dist x y := calc dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _ ... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx'] ... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _ ... = dist x y : by simp [Hyy'], exact le_antisymm A B end } lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) : dist ⟦p⟧ ⟦q⟧ = dist p q := rfl instance metric_space_quot {α : Type u} [pseudo_metric_space α] : metric_space (pseudo_metric_quot α) := { dist_self := begin refine quotient.ind (λy, _), exact pseudo_metric_space.dist_self _ end, eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H), dist_comm := λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _), dist_triangle := λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) } end eq_rel
03d353e2381e22032aa855ab96959aba410ad830
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/metric_space/premetric_space.lean
e8051bc291d2bdfb913991c42fe5d966328d2390
[ "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
3,517
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Premetric spaces. Author: Sébastien Gouëzel -/ import topology.metric_space.basic /-! # Premetric spaces Metric spaces are often defined as quotients of spaces endowed with a "distance" function satisfying the triangular inequality, but for which `dist x y = 0` does not imply x = y. We call such a space a premetric space. `dist x y = 0` defines an equivalence relation, and the quotient is canonically a metric space. -/ noncomputable theory universes u v variables {α : Type u} class premetric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) namespace premetric section protected lemma dist_nonneg {α : Type u} [premetric_space α] {x y : α} : 0 ≤ dist x y := begin have := calc 0 = dist x x : (premetric_space.dist_self _).symm ... ≤ dist x y + dist y x : premetric_space.dist_triangle _ _ _ ... = dist x y + dist x y : by simp [premetric_space.dist_comm], by linarith end /-- The canonical equivalence relation on a premetric space. -/ def dist_setoid (α : Type u) [premetric_space α] : setoid α := setoid.mk (λx y, dist x y = 0) begin unfold equivalence, repeat { split }, { exact premetric_space.dist_self }, { assume x y h, rwa premetric_space.dist_comm }, { assume x y z hxy hyz, refine le_antisymm _ premetric.dist_nonneg, calc dist x z ≤ dist x y + dist y z : premetric_space.dist_triangle _ _ _ ... = 0 + 0 : by rw [hxy, hyz] ... = 0 : by simp } end local attribute [instance] dist_setoid /-- The canonical quotient of a premetric space, identifying points at distance 0. -/ @[reducible] definition metric_quot (α : Type u) [premetric_space α] : Type* := quotient (premetric.dist_setoid α) instance has_dist_metric_quot {α : Type u} [premetric_space α] : has_dist (metric_quot α) := { dist := quotient.lift₂ (λp q : α, dist p q) begin assume x y x' y' hxx' hyy', have Hxx' : dist x x' = 0 := hxx', have Hyy' : dist y y' = 0 := hyy', have A : dist x y ≤ dist x' y' := calc dist x y ≤ dist x x' + dist x' y : premetric_space.dist_triangle _ _ _ ... = dist x' y : by simp [Hxx'] ... ≤ dist x' y' + dist y' y : premetric_space.dist_triangle _ _ _ ... = dist x' y' : by simp [premetric_space.dist_comm, Hyy'], have B : dist x' y' ≤ dist x y := calc dist x' y' ≤ dist x' x + dist x y' : premetric_space.dist_triangle _ _ _ ... = dist x y' : by simp [premetric_space.dist_comm, Hxx'] ... ≤ dist x y + dist y y' : premetric_space.dist_triangle _ _ _ ... = dist x y : by simp [Hyy'], exact le_antisymm A B end } lemma metric_quot_dist_eq {α : Type u} [premetric_space α] (p q : α) : dist ⟦p⟧ ⟦q⟧ = dist p q := rfl instance metric_space_quot {α : Type u} [premetric_space α] : metric_space (metric_quot α) := { dist_self := begin refine quotient.ind (λy, _), exact premetric_space.dist_self _ end, eq_of_dist_eq_zero := λxc yc, quotient.induction_on₂ xc yc (λx y H, quotient.sound H), dist_comm := λxc yc, quotient.induction_on₂ xc yc (λx y, premetric_space.dist_comm _ _), dist_triangle := λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, premetric_space.dist_triangle _ _ _) } end --section end premetric --namespace
9ec2753e09d394c724617c00f6bec0f23c8d4a55
618003631150032a5676f229d13a079ac875ff77
/src/group_theory/free_group.lean
349cee0460f99faba954d358ec4fd35f1a5cad55
[ "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
30,912
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Free groups as a quotient over the reduction relation `a * x * x⁻¹ * b = a * b`. First we introduce the one step reduction relation `free_group.red.step`: w * x * x⁻¹ * v ~> w * v its reflexive transitive closure: `free_group.red.trans` and proof that its join is an equivalence relation. Then we introduce `free_group α` as a quotient over `free_group.red.step`. -/ import data.fintype.basic import group_theory.subgroup open relation universes u v w variables {α : Type u} local attribute [simp] list.append_eq_has_append namespace free_group variables {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- Reduction step: `w * x * x⁻¹ * v ~> w * v` -/ inductive red.step : list (α × bool) → list (α × bool) → Prop | bnot {L₁ L₂ x b} : red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂) attribute [simp] red.step.bnot /-- Reflexive-transitive closure of red.step -/ def red : list (α × bool) → list (α × bool) → Prop := refl_trans_gen red.step @[refl] lemma red.refl : red L L := refl_trans_gen.refl @[trans] lemma red.trans : red L₁ L₂ → red L₂ L₃ → red L₁ L₃ := refl_trans_gen.trans namespace red /-- Predicate asserting that word `w₁` can be reduced to `w₂` in one step, i.e. there are words `w₃ w₄` and letter `x` such that `w₁ = w₃xx⁻¹w₄` and `w₂ = w₃w₄` -/ theorem step.length : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.length + 2 = L₁.length | _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl @[simp] lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: L₂) (L₁ ++ L₂) := by cases b; from step.bnot @[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L := @step.bnot _ [] _ _ _ @[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L := @red.step.bnot_rev _ [] _ _ _ theorem step.append_left : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₂ L₃ → step (L₁ ++ L₂) (L₁ ++ L₃) | _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor theorem step.cons {x} (H : red.step L₁ L₂) : red.step (x :: L₁) (x :: L₂) := @step.append_left _ [x] _ _ H theorem step.append_right : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₁ L₂ → step (L₁ ++ L₃) (L₂ ++ L₃) | _ _ _ red.step.bnot := by simp lemma not_step_nil : ¬ step [] L := begin generalize h' : [] = L', assume h, cases h with L₁ L₂, simp [list.nil_eq_append_iff] at h', contradiction end lemma step.cons_left_iff {a : α} {b : bool} : step ((a, b) :: L₁) L₂ ↔ (∃L, step L₁ L ∧ L₂ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::L₂) := begin split, { generalize hL : ((a, b) :: L₁ : list _) = L, assume h, rcases h with ⟨_ | ⟨p, s'⟩, e, a', b'⟩, { simp at hL, simp [*] }, { simp at hL, rcases hL with ⟨rfl, rfl⟩, refine or.inl ⟨s' ++ e, step.bnot, _⟩, simp } }, { assume h, rcases h with ⟨L, h, rfl⟩ | rfl, { exact step.cons h }, { exact step.cons_bnot } } end lemma not_step_singleton : ∀ {p : α × bool}, ¬ step [p] L | (a, b) := by simp [step.cons_left_iff, not_step_nil] lemma step.cons_cons_iff : ∀{p : α × bool}, step (p :: L₁) (p :: L₂) ↔ step L₁ L₂ := by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt} lemma step.append_left_iff : ∀L, step (L ++ L₁) (L ++ L₂) ↔ step L₁ L₂ | [] := by simp | (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff] private theorem step.diamond_aux : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)} {x1 b1 x2 b2}, L₁ ++ (x1, b1) :: (x1, bnot b1) :: L₂ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: L₄ → L₁ ++ L₂ = L₃ ++ L₄ ∨ ∃ L₅, red.step (L₁ ++ L₂) L₅ ∧ red.step (L₃ ++ L₄) L₅ | [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp | [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩ | ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩ | ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H := let ⟨H1, H2⟩ := list.cons.inj H in match step.diamond_aux H2 with | or.inl H3 := or.inl $ by simp [H1, H3] | or.inr ⟨L₅, H3, H4⟩ := or.inr ⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩ end theorem step.diamond : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)}, red.step L₁ L₃ → red.step L₂ L₄ → L₁ = L₂ → L₃ = L₄ ∨ ∃ L₅, red.step L₃ L₅ ∧ red.step L₄ L₅ | _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H lemma step.to_red : step L₁ L₂ → red L₁ L₂ := refl_trans_gen.single /-- Church-Rosser theorem for word reduction: If `w1 w2 w3` are words such that `w1` reduces to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4` respectively. -/ theorem church_rosser : red L₁ L₂ → red L₁ L₃ → join red L₂ L₃ := relation.church_rosser (assume a b c hab hac, match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩ end) lemma cons_cons {p} : red L₁ L₂ → red (p :: L₁) (p :: L₂) := refl_trans_gen_lift (list.cons p) (assume a b, step.cons) lemma cons_cons_iff (p) : red (p :: L₁) (p :: L₂) ↔ red L₁ L₂ := iff.intro begin generalize eq₁ : (p :: L₁ : list _) = LL₁, generalize eq₂ : (p :: L₂ : list _) = LL₂, assume h, induction h using relation.refl_trans_gen.head_induction_on with L₁ L₂ h₁₂ h ih generalizing L₁ L₂, { subst_vars, cases eq₂, constructor }, { subst_vars, cases p with a b, rw [step.cons_left_iff] at h₁₂, rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl, { exact (ih rfl rfl).head h₁₂ }, { exact (cons_cons h).tail step.cons_bnot_rev } } end cons_cons lemma append_append_left_iff : ∀L, red (L ++ L₁) (L ++ L₂) ↔ red L₁ L₂ | [] := iff.rfl | (p :: L) := by simp [append_append_left_iff L, cons_cons_iff] lemma append_append (h₁ : red L₁ L₃) (h₂ : red L₂ L₄) : red (L₁ ++ L₂) (L₃ ++ L₄) := (refl_trans_gen_lift (λL, L ++ L₂) (assume a b, step.append_right) h₁).trans ((append_append_left_iff _).2 h₂) lemma to_append_iff : red L (L₁ ++ L₂) ↔ (∃L₃ L₄, L = L₃ ++ L₄ ∧ red L₃ L₁ ∧ red L₄ L₂) := iff.intro begin generalize eq : L₁ ++ L₂ = L₁₂, assume h, induction h with L' L₁₂ hLL' h ih generalizing L₁ L₂, { exact ⟨_, _, eq.symm, by refl, by refl⟩ }, { cases h with s e a b, rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩, { have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) = (L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁, h₂.tail step.bnot⟩ }, { have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ L₂ = s ++ ((a, b) :: (a, bnot b) :: (e' ++ L₂)), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁.tail step.bnot, h₂⟩ }, } end (assume ⟨L₃, L₄, eq, h₃, h₄⟩, eq.symm ▸ append_append h₃ h₄) /-- The empty word `[]` only reduces to itself. -/ theorem nil_iff : red [] L ↔ L = [] := refl_trans_gen_iff_eq (assume l, red.not_step_nil) /-- A letter only reduces to itself. -/ theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] := refl_trans_gen_iff_eq (assume l, not_step_singleton) /-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces to `x⁻¹` -/ theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] := iff.intro (assume h, have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h, have h₂ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev, let ⟨L', h₁, h₂⟩ := church_rosser h₁ h₂ in by rw [singleton_iff] at h₁; subst L'; assumption) (assume h, (cons_cons h).tail step.cons_bnot) theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) ≠ (x2, b2)) : red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] := begin apply refl_trans_gen_iff_eq, generalize eq : [(x1, bnot b1), (x2, b2)] = L', assume L h', cases h', simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq, rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars, simp at h, contradiction end /-- If `x` and `y` are distinct letters and `w₁ w₂` are words such that `xw₁` reduces to `yw₂`, then `w₁` reduces to `x⁻¹yw₂`. -/ theorem inv_of_red_of_ne {x1 b1 x2 b2} (H1 : (x1, b1) ≠ (x2, b2)) (H2 : red ((x1, b1) :: L₁) ((x2, b2) :: L₂)) : red L₁ ((x1, bnot b1) :: (x2, b2) :: L₂) := begin have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ L₂), from H2, rcases to_append_iff.1 this with ⟨_ | ⟨p, L₃⟩, L₄, eq, h₁, h₂⟩, { simp [nil_iff] at h₁, contradiction }, { cases eq, show red (L₃ ++ L₄) ([(x1, bnot b1), (x2, b2)] ++ L₂), apply append_append _ h₂, have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)], { exact cons_cons h₁ }, have h₂ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃, { exact step.cons_bnot_rev.to_red }, rcases church_rosser h₁ h₂ with ⟨L', h₁, h₂⟩, rw [red_iff_irreducible H1] at h₁, rwa [h₁] at h₂ } end theorem step.sublist (H : red.step L₁ L₂) : L₂ <+ L₁ := by cases H; simp; constructor; constructor; refl /-- If `w₁ w₂` are words such that `w₁` reduces to `w₂`, then `w₂` is a sublist of `w₁`. -/ theorem sublist : red L₁ L₂ → L₂ <+ L₁ := refl_trans_gen_of_transitive_reflexive (λl, list.sublist.refl l) (λa b c hab hbc, list.sublist.trans hbc hab) (λa b, red.step.sublist) theorem sizeof_of_step : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.sizeof < L₁.sizeof | _ _ (@step.bnot _ L1 L2 x b) := begin induction L1 with hd tl ih, case list.nil { dsimp [list.sizeof], have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2) = (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1), { ac_refl }, rw H, exact nat.le_add_right _ _ }, case list.cons { dsimp [list.sizeof], exact nat.add_lt_add_left ih _ } end theorem length (h : red L₁ L₂) : ∃ n, L₁.length = L₂.length + 2 * n := begin induction h with L₂ L₃ h₁₂ h₂₃ ih, { exact ⟨0, rfl⟩ }, { rcases ih with ⟨n, eq⟩, existsi (1 + n), simp [mul_add, eq, (step.length h₂₃).symm, add_assoc] } end theorem antisymm (h₁₂ : red L₁ L₂) : red L₂ L₁ → L₁ = L₂ := match L₁, h₁₂.cases_head with | _, or.inl rfl := assume h, rfl | L₁, or.inr ⟨L₃, h₁₃, h₃₂⟩ := assume h₂₁, let ⟨n, eq⟩ := length (h₃₂.trans h₂₁) in have list.length L₃ + 0 = list.length L₃ + (2 * n + 2), by simpa [(step.length h₁₃).symm, add_comm, add_assoc] using eq, (nat.no_confusion $ nat.add_left_cancel this) end end red theorem equivalence_join_red : equivalence (join (@red α)) := equivalence_join_refl_trans_gen $ assume a b c hab hac, (match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩ end) theorem join_red_of_step (h : red.step L₁ L₂) : join red L₁ L₂ := join_of_single reflexive_refl_trans_gen h.to_red theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ L₂ ↔ join red L₁ L₂ := iff.intro (assume h, have eqv_gen (join red) L₁ L₂ := eqv_gen_mono (assume a b, join_red_of_step) h, (eqv_gen_iff_of_equivalence $ equivalence_join_red).1 this) (join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b, refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel) end free_group /-- The free group over a type, i.e. the words formed by the elements of the type and their formal inverses, quotient by one step reduction. -/ def free_group (α : Type u) : Type u := quot $ @free_group.red.step α namespace free_group variables {α} {L L₁ L₂ L₃ L₄ : list (α × bool)} def mk (L) : free_group α := quot.mk red.step L @[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl @[simp] lemma quot_lift_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift f H (mk L) = f L := rfl @[simp] lemma quot_lift_on_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift_on (mk L) f H = f L := rfl instance : has_one (free_group α) := ⟨mk []⟩ lemma one_eq_mk : (1 : free_group α) = mk [] := rfl instance : inhabited (free_group α) := ⟨1⟩ instance : has_mul (free_group α) := ⟨λ x y, quot.lift_on x (λ L₁, quot.lift_on y (λ L₂, mk $ L₁ ++ L₂) (λ L₂ L₃ H, quot.sound $ red.step.append_left H)) (λ L₁ L₂ H, quot.induction_on y $ λ L₃, quot.sound $ red.step.append_right H)⟩ @[simp] lemma mul_mk : mk L₁ * mk L₂ = mk (L₁ ++ L₂) := rfl instance : has_inv (free_group α) := ⟨λx, quot.lift_on x (λ L, mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse) (assume a b h, quot.sound $ by cases h; simp)⟩ @[simp] lemma inv_mk : (mk L)⁻¹ = mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse := rfl instance : group (free_group α) := { mul := (*), one := 1, inv := has_inv.inv, mul_assoc := by rintros ⟨L₁⟩ ⟨L₂⟩ ⟨L₃⟩; simp, one_mul := by rintros ⟨L⟩; refl, mul_one := by rintros ⟨L⟩; simp [one_eq_mk], mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $ λ ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [one_eq_mk]) ih) } /-- `of x` is the canonical injection from the type to the free group over that type by sending each element to the equivalence class of the letter that is the element. -/ def of (x : α) : free_group α := mk [(x, tt)] theorem red.exact : mk L₁ = mk L₂ ↔ join red L₁ L₂ := calc (mk L₁ = mk L₂) ↔ eqv_gen red.step L₁ L₂ : iff.intro (quot.exact _) quot.eqv_gen_sound ... ↔ join red L₁ L₂ : eqv_gen_step_iff_join_red /-- The canonical injection from the type to the free group is an injection. -/ theorem of.inj {x y : α} (H : of x = of y) : x = y := let ⟨L₁, hx, hy⟩ := red.exact.1 H in by simp [red.singleton_iff] at hx hy; cc section to_group variables {β : Type v} [group β] (f : α → β) {x y : free_group α} def to_group.aux : list (α × bool) → β := λ L, list.prod $ L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹ theorem red.step.to_group {f : α → β} (H : red.step L₁ L₂) : to_group.aux f L₁ = to_group.aux f L₂ := by cases H with _ _ _ b; cases b; simp [to_group.aux] /-- If `β` is a group, then any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to `β` -/ def to_group : free_group α → β := quot.lift (to_group.aux f) $ λ L₁ L₂ H, red.step.to_group H variable {f} @[simp] lemma to_group.mk : to_group f (mk L) = list.prod (L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹) := rfl @[simp] lemma to_group.of {x} : to_group f (of x) = f x := one_mul _ instance to_group.is_group_hom : is_group_hom (to_group f) := { map_mul := by rintros ⟨L₁⟩ ⟨L₂⟩; simp } @[simp] lemma to_group.mul : to_group f (x * y) = to_group f x * to_group f y := is_mul_hom.map_mul _ _ _ @[simp] lemma to_group.one : to_group f 1 = 1 := is_group_hom.map_one _ @[simp] lemma to_group.inv : to_group f x⁻¹ = (to_group f x)⁻¹ := is_group_hom.map_inv _ _ theorem to_group.unique (g : free_group α → β) [is_group_hom g] (hg : ∀ x, g (of x) = f x) : ∀{x}, g x = to_group f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = _), bool.rec_on b (show g ((of x)⁻¹ * mk t) = to_group f (mk ((x, ff) :: t)), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih, to_group, to_group.aux]) (show g (of x * mk t) = to_group f (mk ((x, tt) :: t)), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih, to_group, to_group.aux])) theorem to_group.of_eq (x : free_group α) : to_group of x = x := eq.symm $ to_group.unique id (λ x, rfl) theorem to_group.range_subset {s : set β} [is_subgroup s] (H : set.range f ⊆ s) : set.range (to_group f) ⊆ s := by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L is_submonoid.one_mem (λ ⟨x, b⟩ tl ih, bool.rec_on b (by simp at ih ⊢; from is_submonoid.mul_mem (is_subgroup.inv_mem $ H ⟨x, rfl⟩) ih) (by simp at ih ⊢; from is_submonoid.mul_mem (H ⟨x, rfl⟩) ih)) theorem to_group.range_eq_closure : set.range (to_group f) = group.closure (set.range f) := set.subset.antisymm (to_group.range_subset group.subset_closure) (group.closure_subset $ λ y ⟨x, hx⟩, ⟨of x, by simpa⟩) end to_group section map variables {β : Type v} (f : α → β) {x y : free_group α} def map.aux (L : list (α × bool)) : list (β × bool) := L.map $ λ x, (f x.1, x.2) /-- Any function from `α` to `β` extends uniquely to a group homomorphism from the free group ver `α` to the free group over `β`. -/ def map (x : free_group α) : free_group β := x.lift_on (λ L, mk $ map.aux f L) $ λ L₁ L₂ H, quot.sound $ by cases H; simp [map.aux] instance map.is_group_hom : is_group_hom (map f) := { map_mul := by rintros ⟨L₁⟩ ⟨L₂⟩; simp [map, map.aux] } variable {f} @[simp] lemma map.mk : map f (mk L) = mk (L.map (λ x, (f x.1, x.2))) := rfl @[simp] lemma map.id : map id x = x := have H1 : (λ (x : α × bool), x) = id := rfl, by rcases x with ⟨L⟩; simp [H1] @[simp] lemma map.id' : map (λ z, z) x = x := map.id theorem map.comp {γ : Type w} {f : α → β} {g : β → γ} {x} : map g (map f x) = map (g ∘ f) x := by rcases x with ⟨L⟩; simp @[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl @[simp] lemma map.mul : map f (x * y) = map f x * map f y := is_mul_hom.map_mul _ x y @[simp] lemma map.one : map f 1 = 1 := is_group_hom.map_one _ @[simp] lemma map.inv : map f x⁻¹ = (map f x)⁻¹ := is_group_hom.map_inv _ x theorem map.unique (g : free_group α → free_group β) [is_group_hom g] (hg : ∀ x, g (of x) = of (f x)) : ∀{x}, g x = map f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b (show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih]) (show g (of x * mk t) = map f (of x * mk t), by simp [is_mul_hom.map_mul g, hg, ih])) /-- Equivalent types give rise to equivalent free groups. -/ def free_group_congr {α β} (e : α ≃ β) : free_group α ≃ free_group β := ⟨map e, map e.symm, λ x, by simp [function.comp, map.comp], λ x, by simp [function.comp, map.comp]⟩ theorem map_eq_to_group : map f x = to_group (of ∘ f) x := eq.symm $ map.unique _ $ λ x, by simp end map section prod variables [group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the multiplicative version of `sum`. -/ def prod : α := to_group id x variables {x y} @[simp] lemma prod_mk : prod (mk L) = list.prod (L.map $ λ x, cond x.2 x.1 x.1⁻¹) := rfl @[simp] lemma prod.of {x : α} : prod (of x) = x := to_group.of instance prod.is_group_hom : is_group_hom (@prod α _) := to_group.is_group_hom @[simp] lemma prod.mul : prod (x * y) = prod x * prod y := to_group.mul @[simp] lemma prod.one : prod (1:free_group α) = 1 := to_group.one @[simp] lemma prod.inv : prod x⁻¹ = (prod x)⁻¹ := to_group.inv lemma prod.unique (g : free_group α → α) [is_group_hom g] (hg : ∀ x, g (of x) = x) {x} : g x = prod x := to_group.unique g hg end prod theorem to_group_eq_prod_map {β : Type v} [group β] {f : α → β} {x} : to_group f x = prod (map f x) := have is_group_hom (prod ∘ map f) := is_group_hom.comp _ _, by exactI (eq.symm $ to_group.unique (prod ∘ map f) $ λ _, by simp) section sum variables [add_group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the additive version of `prod`. -/ def sum : α := @prod (multiplicative _) _ x variables {x y} @[simp] lemma sum_mk : sum (mk L) = list.sum (L.map $ λ x, cond x.2 x.1 (-x.1)) := rfl @[simp] lemma sum.of {x : α} : sum (of x) = x := prod.of instance sum.is_group_hom : is_group_hom (@sum α _) := prod.is_group_hom @[simp] lemma sum.mul : sum (x * y) = sum x + sum y := prod.mul @[simp] lemma sum.one : sum (1:free_group α) = 0 := prod.one @[simp] lemma sum.inv : sum x⁻¹ = -sum x := prod.inv end sum def free_group_empty_equiv_unit : free_group empty ≃ unit := { to_fun := λ _, (), inv_fun := λ _, 1, left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl, right_inv := λ ⟨⟩, rfl } def free_group_unit_equiv_int : free_group unit ≃ int := { to_fun := λ x, sum $ map (λ _, 1) x, inv_fun := λ x, of () ^ x, left_inv := by rintros ⟨L⟩; exact list.rec_on L rfl (λ ⟨⟨⟩, b⟩ tl ih, by cases b; simp [gpow_add] at ih ⊢; rw ih; refl), right_inv := λ x, int.induction_on x (by simp) (λ i ih, by simp at ih; simp [gpow_add, ih]) (λ i ih, by simp at ih; simp [gpow_add, ih, sub_eq_add_neg]) } section category variables {β : Type u} instance : monad free_group.{u} := { pure := λ α, of, map := λ α β, map, bind := λ α β x f, to_group f x } @[elab_as_eliminator] protected theorem induction_on {C : free_group α → Prop} (z : free_group α) (C1 : C 1) (Cp : ∀ x, C $ pure x) (Ci : ∀ x, C (pure x) → C (pure x)⁻¹) (Cm : ∀ x y, C x → C y → C (x * y)) : C z := quot.induction_on z $ λ L, list.rec_on L C1 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih) @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_group α) = pure (f x) := map.of @[simp] lemma map_one (f : α → β) : f <$> (1 : free_group α) = 1 := map.one @[simp] lemma map_mul (f : α → β) (x y : free_group α) : f <$> (x * y) = f <$> x * f <$> y := map.mul @[simp] lemma map_inv (f : α → β) (x : free_group α) : f <$> (x⁻¹) = (f <$> x)⁻¹ := map.inv @[simp] lemma pure_bind (f : α → free_group β) (x) : pure x >>= f = f x := to_group.of @[simp] lemma one_bind (f : α → free_group β) : 1 >>= f = 1 := @@to_group.one _ f @[simp] lemma mul_bind (f : α → free_group β) (x y : free_group α) : x * y >>= f = (x >>= f) * (y >>= f) := to_group.mul @[simp] lemma inv_bind (f : α → free_group β) (x : free_group α) : x⁻¹ >>= f = (x >>= f)⁻¹ := to_group.inv instance : is_lawful_monad free_group.{u} := { id_map := λ α x, free_group.induction_on x (map_one id) (λ x, map_pure id x) (λ x ih, by rw [map_inv, ih]) (λ x y ihx ihy, by rw [map_mul, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_group.induction_on x (by iterate 3 { rw one_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw inv_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]), bind_pure_comp_eq_map := λ α β f x, free_group.induction_on x (by rw [one_bind, map_one]) (λ x, by rw [pure_bind, map_pure]) (λ x ih, by rw [inv_bind, map_inv, ih]) (λ x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) } end category section reduce variable [decidable_eq α] /-- The maximal reduction of a word. It is computable iff `α` has decidable equality. -/ def reduce (L : list (α × bool)) : list (α × bool) := list.rec_on L [] $ λ hd1 tl1 ih, list.cases_on ih [hd1] $ λ hd2 tl2, if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2 else hd1 :: hd2 :: tl2 @[simp] lemma reduce.cons (x) : reduce (x :: L) = list.cases_on (reduce L) [x] (λ hd tl, if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl else x :: hd :: tl) := rfl /-- The first theorem that characterises the function `reduce`: a word reduces to its maximal reduction. -/ theorem reduce.red : red L (reduce L) := begin induction L with hd1 tl1 ih, case list.nil { constructor }, case list.cons { dsimp, revert ih, generalize htl : reduce tl1 = TL, intro ih, cases TL with hd2 tl2, case list.nil { exact red.cons_cons ih }, case list.cons { dsimp, by_cases h : hd1.fst = hd2.fst ∧ hd1.snd = bnot (hd2.snd), { rw [if_pos h], transitivity, { exact red.cons_cons ih }, { cases hd1, cases hd2, cases h, dsimp at *, subst_vars, exact red.step.cons_bnot_rev.to_red } }, { rw [if_neg h], exact red.cons_cons ih } } } end theorem reduce.not {p : Prop} : ∀ {L₁ L₂ L₃ : list (α × bool)} {x b}, reduce L₁ = L₂ ++ (x, b) :: (x, bnot b) :: L₃ → p | [] L2 L3 _ _ := λ h, by cases L2; injections | ((x,b)::L1) L2 L3 x' b' := begin dsimp, cases r : reduce L1, { dsimp, intro h, have := congr_arg list.length h, simp [-add_comm] at this, exact absurd this dec_trivial }, cases hd with y c, by_cases x = y ∧ b = bnot c; simp [h]; intro H, { rw H at r, exact @reduce.not L1 ((y,c)::L2) L3 x' b' r }, rcases L2 with _|⟨a, L2⟩, { injections, subst_vars, simp at h, cc }, { refine @reduce.not L1 L2 L3 x' b' _, injection H with _ H, rw [r, H], refl } end /-- The second theorem that characterises the function `reduce`: the maximal reduction of a word only reduces to itself. -/ theorem reduce.min (H : red (reduce L₁) L₂) : reduce L₁ = L₂ := begin induction H with L1 L' L2 H1 H2 ih, { refl }, { cases H1 with L4 L5 x b, exact reduce.not H2 } end /-- `reduce` is idempotent, i.e. the maximal reduction of the maximal reduction of a word is the maximal reduction of the word. -/ theorem reduce.idem : reduce (reduce L) = reduce L := eq.symm $ reduce.min reduce.red theorem reduce.step.eq (H : red.step L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If a word reduces to another word, then they have a common maximal reduction. -/ theorem reduce.eq_of_red (H : red L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If two words correspond to the same element in the free group, then they have a common maximal reduction. This is the proof that the function that sends an element of the free group to its maximal reduction is well-defined. -/ theorem reduce.sound (H : mk L₁ = mk L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, H13, H23⟩ := red.exact.1 H in (reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm /-- If two words have a common maximal reduction, then they correspond to the same element in the free group. -/ theorem reduce.exact (H : reduce L₁ = reduce L₂) : mk L₁ = mk L₂ := red.exact.2 ⟨reduce L₂, H ▸ reduce.red, reduce.red⟩ /-- A word and its maximal reduction correspond to the same element of the free group. -/ theorem reduce.self : mk (reduce L) = mk L := reduce.exact reduce.idem /-- If words `w₁ w₂` are such that `w₁` reduces to `w₂`, then `w₂` reduces to the maximal reduction of `w₁`. -/ theorem reduce.rev (H : red L₁ L₂) : red L₂ (reduce L₁) := (reduce.eq_of_red H).symm ▸ reduce.red /-- The function that sends an element of the free group to its maximal reduction. -/ def to_word : free_group α → list (α × bool) := quot.lift reduce $ λ L₁ L₂ H, reduce.step.eq H lemma to_word.mk : ∀{x : free_group α}, mk (to_word x) = x := by rintros ⟨L⟩; exact reduce.self lemma to_word.inj : ∀(x y : free_group α), to_word x = to_word y → x = y := by rintros ⟨L₁⟩ ⟨L₂⟩; exact reduce.exact /-- Constructive Church-Rosser theorem (compare `church_rosser`). -/ def reduce.church_rosser (H12 : red L₁ L₂) (H13 : red L₁ L₃) : { L₄ // red L₂ L₄ ∧ red L₃ L₄ } := ⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩ instance : decidable_eq (free_group α) := function.injective.decidable_eq to_word.inj instance red.decidable_rel : decidable_rel (@red α) | [] [] := is_true red.refl | [] (hd2::tl2) := is_false $ λ H, list.no_confusion (red.nil_iff.1 H) | ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with | is_true H := is_true $ red.trans (red.cons_cons H) $ (@red.step.bnot _ [] [] _ _).to_red | is_false H := is_false $ λ H2, H $ red.cons_nil_iff_singleton.1 H2 end | ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2) then match red.decidable_rel tl1 tl2 with | is_true H := is_true $ h ▸ red.cons_cons H | is_false H := is_false $ λ H2, H $ h ▸ (red.cons_cons_iff _).1 $ H2 end else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with | is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot | is_false H := is_false $ λ H2, H $ red.inv_of_red_of_ne h H2 end /-- A list containing every word that `w₁` reduces to. -/ def red.enum (L₁ : list (α × bool)) : list (list (α × bool)) := list.filter (λ L₂, red L₁ L₂) (list.sublists L₁) theorem red.enum.sound (H : L₂ ∈ red.enum L₁) : red L₁ L₂ := list.of_mem_filter H theorem red.enum.complete (H : red L₁ L₂) : L₂ ∈ red.enum L₁ := list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H instance : fintype { L₂ // red L₁ L₂ } := fintype.subtype (list.to_finset $ red.enum L₁) $ λ L₂, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H, λ H, list.mem_to_finset.2 $ red.enum.complete H⟩ end reduce end free_group
1b5af755b0a4cd6f14eebbe7da14a2b96aa7dc7c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/sheaves/presheaf_of_functions.lean
8af745cef2109e38bb1d9ef0d0a4f8a68c6f7870
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,821
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.yoneda import Mathlib.topology.sheaves.presheaf import Mathlib.topology.category.TopCommRing import Mathlib.topology.algebra.continuous_functions import Mathlib.PostPort universes v u_1 u namespace Mathlib /-! # Presheaves of functions We construct some simple examples of presheaves of functions on a topological space. * `presheaf_to_Type X f`, where `f : X → Type`, is the presheaf of dependently-typed (not-necessarily continuous) functions * `presheaf_to_Type X T`, where `T : Type`, is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T` * `presheaf_to_Top X T`, where `T : Top`, is the presheaf of continuous functions into a topological space `T` * `presheaf_To_TopCommRing X R`, where `R : TopCommRing` is the presheaf valued in `CommRing` of functions functions into a topological ring `R` * as an example of the previous construction, `presheaf_to_TopCommRing X (TopCommRing.of ℂ)` is the presheaf of rings of continuous complex-valued functions on `X`. -/ namespace Top /-- The presheaf of dependently typed functions on `X`, with fibres given by a type family `f`. There is no requirement that the functions are continuous, here. -/ def presheaf_to_Types (X : Top) (T : ↥X → Type v) : presheaf (Type v) X := category_theory.functor.mk (fun (U : topological_space.opens ↥Xᵒᵖ) => (x : ↥(opposite.unop U)) → T ↑x) fun (U V : topological_space.opens ↥Xᵒᵖ) (i : U ⟶ V) (g : (x : ↥(opposite.unop U)) → T ↑x) (x : ↥(opposite.unop V)) => g (coe_fn (category_theory.has_hom.hom.unop i) x) @[simp] theorem presheaf_to_Types_obj (X : Top) {T : ↥X → Type v} {U : topological_space.opens ↥Xᵒᵖ} : category_theory.functor.obj (presheaf_to_Types X T) U = ((x : ↥(opposite.unop U)) → T ↑x) := rfl @[simp] theorem presheaf_to_Types_map (X : Top) {T : ↥X → Type v} {U : topological_space.opens ↥Xᵒᵖ} {V : topological_space.opens ↥Xᵒᵖ} {i : U ⟶ V} {f : category_theory.functor.obj (presheaf_to_Types X T) U} : category_theory.functor.map (presheaf_to_Types X T) i f = fun (x : ↥(opposite.unop V)) => f (coe_fn (category_theory.has_hom.hom.unop i) x) := rfl /-- The presheaf of functions on `X` with values in a type `T`. There is no requirement that the functions are continuous, here. -/ -- We don't just define this in terms of `presheaf_to_Types`, -- as it's helpful later to see (at a syntactic level) that `(presheaf_to_Type X T).obj U` -- is a non-dependent function. -- We don't use `@[simps]` to generate the projection lemmas here, -- as it turns out to be useful to have `presheaf_to_Type_map` -- written as an equality of functions (rather than being applied to some argument). def presheaf_to_Type (X : Top) (T : Type v) : presheaf (Type v) X := category_theory.functor.mk (fun (U : topological_space.opens ↥Xᵒᵖ) => ↥(opposite.unop U) → T) fun (U V : topological_space.opens ↥Xᵒᵖ) (i : U ⟶ V) (g : ↥(opposite.unop U) → T) => g ∘ ⇑(category_theory.has_hom.hom.unop i) @[simp] theorem presheaf_to_Type_obj (X : Top) {T : Type v} {U : topological_space.opens ↥Xᵒᵖ} : category_theory.functor.obj (presheaf_to_Type X T) U = (↥(opposite.unop U) → T) := rfl @[simp] theorem presheaf_to_Type_map (X : Top) {T : Type v} {U : topological_space.opens ↥Xᵒᵖ} {V : topological_space.opens ↥Xᵒᵖ} {i : U ⟶ V} {f : category_theory.functor.obj (presheaf_to_Type X T) U} : category_theory.functor.map (presheaf_to_Type X T) i f = f ∘ ⇑(category_theory.has_hom.hom.unop i) := rfl /-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/ def presheaf_to_Top (X : Top) (T : Top) : presheaf (Type v) X := category_theory.functor.op (topological_space.opens.to_Top X) ⋙ category_theory.functor.obj category_theory.yoneda T @[simp] theorem presheaf_to_Top_obj (X : Top) (T : Top) (U : topological_space.opens ↥Xᵒᵖ) : category_theory.functor.obj (presheaf_to_Top X T) U = (category_theory.functor.obj (topological_space.opens.to_Top X) (opposite.unop U) ⟶ T) := rfl /-- The (bundled) commutative ring of continuous functions from a topological space to a topological commutative ring, with pointwise multiplication. -/ -- TODO upgrade the result to TopCommRing? def continuous_functions (X : Topᵒᵖ) (R : TopCommRing) : CommRing := CommRing.of (opposite.unop X ⟶ category_theory.functor.obj (category_theory.forget₂ TopCommRing Top) R) namespace continuous_functions /-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/ def pullback {X : Topᵒᵖ} {Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) : continuous_functions X R ⟶ continuous_functions Y R := ring_hom.mk (fun (g : ↥(continuous_functions X R)) => category_theory.has_hom.hom.unop f ≫ g) sorry sorry sorry sorry /-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`; this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/ def map (X : Topᵒᵖ) {R : TopCommRing} {S : TopCommRing} (φ : R ⟶ S) : continuous_functions X R ⟶ continuous_functions X S := ring_hom.mk (fun (g : ↥(continuous_functions X R)) => g ≫ category_theory.functor.map (category_theory.forget₂ TopCommRing Top) φ) sorry sorry sorry sorry end continuous_functions /-- An upgraded version of the Yoneda embedding, observing that the continuous maps from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/ def CommRing_yoneda : TopCommRing ⥤ Topᵒᵖ ⥤ CommRing := category_theory.functor.mk (fun (R : TopCommRing) => category_theory.functor.mk (fun (X : Topᵒᵖ) => continuous_functions X R) fun (X Y : Topᵒᵖ) (f : X ⟶ Y) => continuous_functions.pullback f R) fun (R S : TopCommRing) (φ : R ⟶ S) => category_theory.nat_trans.mk fun (X : Topᵒᵖ) => continuous_functions.map X φ /-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with values in some topological commutative ring `T`. For example, we could construct the presheaf of continuous complex valued functions of `X` as ``` presheaf_to_TopCommRing X (TopCommRing.of ℂ) ``` (this requires `import topology.instances.complex`). -/ def presheaf_to_TopCommRing (X : Top) (T : TopCommRing) : presheaf CommRing X := category_theory.functor.op (topological_space.opens.to_Top X) ⋙ category_theory.functor.obj CommRing_yoneda T
1818aebf13769c9d26bc42b5973de347b3f793d1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/witt_vector/witt_polynomial_auto.lean
7b612002268ae95fefcc0a3bb34054498456f092
[]
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
7,757
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.invertible import Mathlib.data.mv_polynomial.variables import Mathlib.data.mv_polynomial.comm_ring import Mathlib.data.mv_polynomial.expand import Mathlib.data.zmod.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial -/ /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ def witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] (n : ℕ) : mv_polynomial ℕ R := finset.sum (finset.range (n + 1)) fun (i : ℕ) => mv_polynomial.monomial (finsupp.single i (p ^ (n - i))) (↑p ^ i) theorem witt_polynomial_eq_sum_C_mul_X_pow (p : ℕ) (R : Type u_1) [comm_ring R] (n : ℕ) : witt_polynomial p R n = finset.sum (finset.range (n + 1)) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * mv_polynomial.X i ^ p ^ (n - i) := sorry /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit -- Notation with ring of coefficients implicit /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ @[simp] theorem map_witt_polynomial (p : ℕ) {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] (f : R →+* S) (n : ℕ) : coe_fn (mv_polynomial.map f) (witt_polynomial p R n) = witt_polynomial p S n := sorry @[simp] theorem constant_coeff_witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_polynomial p R n) = 0 := sorry @[simp] theorem witt_polynomial_zero (p : ℕ) (R : Type u_1) [comm_ring R] : witt_polynomial p R 0 = mv_polynomial.X 0 := sorry @[simp] theorem witt_polynomial_one (p : ℕ) (R : Type u_1) [comm_ring R] : witt_polynomial p R 1 = coe_fn mv_polynomial.C ↑p * mv_polynomial.X 1 + mv_polynomial.X 0 ^ p := sorry theorem aeval_witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] {A : Type u_2} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : coe_fn (mv_polynomial.aeval f) (witt_polynomial p R n) = finset.sum (finset.range (n + 1)) fun (i : ℕ) => ↑p ^ i * f i ^ p ^ (n - i) := sorry /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th witt polynomial by `p`. -/ @[simp] theorem witt_polynomial_zmod_self (p : ℕ) (n : ℕ) : witt_polynomial p (zmod (p ^ (n + 1))) (n + 1) = coe_fn (mv_polynomial.expand p) (witt_polynomial p (zmod (p ^ (n + 1))) n) := sorry -- in fact, `0 < p` would be sufficient theorem witt_polynomial_vars (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] [char_zero R] (n : ℕ) : mv_polynomial.vars (witt_polynomial p R n) = finset.range (n + 1) := sorry theorem witt_polynomial_vars_subset (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (witt_polynomial p R n) ⊆ finset.range (n + 1) := sorry /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ def X_in_terms_of_W (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] : ℕ → mv_polynomial ℕ R := sorry theorem X_in_terms_of_W_eq (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] {n : ℕ} : X_in_terms_of_W p R n = (mv_polynomial.X n - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * X_in_terms_of_W p R i ^ p ^ (n - i)) * coe_fn mv_polynomial.C (⅟ ^ n) := sorry @[simp] theorem constant_coeff_X_in_terms_of_W (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] [invertible ↑p] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (X_in_terms_of_W p R n) = 0 := sorry @[simp] theorem X_in_terms_of_W_zero (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] : X_in_terms_of_W p R 0 = mv_polynomial.X 0 := sorry theorem X_in_terms_of_W_vars_aux (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : n ∈ mv_polynomial.vars (X_in_terms_of_W p ℚ n) ∧ mv_polynomial.vars (X_in_terms_of_W p ℚ n) ⊆ finset.range (n + 1) := sorry theorem X_in_terms_of_W_vars_subset (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (X_in_terms_of_W p ℚ n) ⊆ finset.range (n + 1) := and.right (X_in_terms_of_W_vars_aux p n) theorem X_in_terms_of_W_aux (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] (n : ℕ) : X_in_terms_of_W p R n * coe_fn mv_polynomial.C (↑p ^ n) = mv_polynomial.X n - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * X_in_terms_of_W p R i ^ p ^ (n - i) := sorry @[simp] theorem bind₁_X_in_terms_of_W_witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] (k : ℕ) : coe_fn (mv_polynomial.bind₁ (X_in_terms_of_W p R)) (witt_polynomial p R k) = mv_polynomial.X k := sorry @[simp] theorem bind₁_witt_polynomial_X_in_terms_of_W (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] (n : ℕ) : coe_fn (mv_polynomial.bind₁ (witt_polynomial p R)) (X_in_terms_of_W p R n) = mv_polynomial.X n := sorry end Mathlib
c5984a90aa311be184a76b73baab5c169b852a9d
367134ba5a65885e863bdc4507601606690974c1
/src/data/sym.lean
4ec063baf4fbb80967f70c552691755b3a64aca4
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
4,623
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller. -/ import data.multiset.basic import data.vector2 import tactic.tidy /-! # Symmetric powers This file defines symmetric powers of a type. The nth symmetric power consists of homogeneous n-tuples modulo permutations by the symmetric group. The special case of 2-tuples is called the symmetric square, which is addressed in more detail in `data.sym2`. TODO: This was created as supporting material for `data.sym2`; it needs a fleshed-out interface. ## Tags symmetric powers -/ universes u /-- The nth symmetric power is n-tuples up to permutation. We define it as a subtype of `multiset` since these are well developed in the library. We also give a definition `sym.sym'` in terms of vectors, and we show these are equivalent in `sym.sym_equiv_sym'`. -/ def sym (α : Type u) (n : ℕ) := {s : multiset α // s.card = n} /-- This is the `list.perm` setoid lifted to `vector`. -/ def vector.perm.is_setoid (α : Type u) (n : ℕ) : setoid (vector α n) := { r := λ a b, list.perm a.1 b.1, iseqv := by { rcases list.perm.eqv α with ⟨hr, hs, ht⟩, tidy, } } local attribute [instance] vector.perm.is_setoid namespace sym variables {α : Type u} {n : ℕ} /-- This is the quotient map that takes a list of n elements as an n-tuple and produces an nth symmetric power. -/ def of_vector (x : vector α n) : sym α n := ⟨↑x.val, by { rw multiset.coe_card, exact x.2 }⟩ instance : has_lift (vector α n) (sym α n) := { lift := of_vector } /-- The unique element in `sym α 0`. -/ @[pattern] def nil : sym α 0 := ⟨0, by tidy⟩ /-- Inserts an element into the term of `sym α n`, increasing the length by one. -/ @[pattern] def cons : α → sym α n → sym α (nat.succ n) | a ⟨s, h⟩ := ⟨a ::ₘ s, by rw [multiset.card_cons, h]⟩ notation a :: b := cons a b @[simp] lemma cons_inj_right (a : α) (s s' : sym α n) : a :: s = a :: s' ↔ s = s' := by { cases s, cases s', delta cons, simp, } @[simp] lemma cons_inj_left (a a' : α) (s : sym α n) : a :: s = a' :: s ↔ a = a' := by { cases s, delta cons, simp, } lemma cons_swap (a b : α) (s : sym α n) : a :: b :: s = b :: a :: s := by { cases s, ext, delta cons, rw subtype.coe_mk, dsimp, exact multiset.cons_swap a b s_val } /-- `α ∈ s` means that `a` appears as one of the factors in `s`. -/ def mem (a : α) (s : sym α n) : Prop := a ∈ s.1 instance : has_mem α (sym α n) := ⟨mem⟩ instance decidable_mem [decidable_eq α] (a : α) (s : sym α n) : decidable (a ∈ s) := by { cases s, change decidable (a ∈ s_val), apply_instance } @[simp] lemma mem_cons {a b : α} {s : sym α n} : a ∈ b :: s ↔ a = b ∨ a ∈ s := begin cases s, change a ∈ b ::ₘ s_val ↔ a = b ∨ a ∈ s_val, simp, end lemma mem_cons_of_mem {a b : α} {s : sym α n} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 (or.inr h) @[simp] lemma mem_cons_self (a : α) (s : sym α n) : a ∈ a :: s := mem_cons.2 (or.inl rfl) lemma cons_of_coe_eq (a : α) (v : vector α n) : a :: (↑v : sym α n) = ↑(a ::ᵥ v) := by { unfold_coes, delta of_vector, delta cons, delta vector.cons, tidy } lemma sound {a b : vector α n} (h : a.val ~ b.val) : (↑a : sym α n) = ↑b := begin cases a, cases b, unfold_coes, dunfold of_vector, simp only [subtype.mk_eq_mk, multiset.coe_eq_coe], exact h, end /-- Another definition of the nth symmetric power, using vectors modulo permutations. (See `sym`.) -/ def sym' (α : Type u) (n : ℕ) := quotient (vector.perm.is_setoid α n) /-- This is `cons` but for the alternative `sym'` definition. -/ def cons' {α : Type u} {n : ℕ} : α → sym' α n → sym' α (nat.succ n) := λ a, quotient.map (vector.cons a) (λ ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ h, list.perm.cons _ h) notation a :: b := cons' a b /-- Multisets of cardinality n are equivalent to length-n vectors up to permutations. -/ def sym_equiv_sym' {α : Type u} {n : ℕ} : sym α n ≃ sym' α n := equiv.subtype_quotient_equiv_quotient_subtype _ _ (λ _, by refl) (λ _ _, by refl) lemma cons_equiv_eq_equiv_cons (α : Type u) (n : ℕ) (a : α) (s : sym α n) : a :: sym_equiv_sym' s = sym_equiv_sym' (a :: s) := by tidy section inhabited -- Instances to make the linter happy instance inhabited_sym [inhabited α] (n : ℕ) : inhabited (sym α n) := ⟨⟨multiset.repeat (default α) n, multiset.card_repeat _ _⟩⟩ instance inhabited_sym' [inhabited α] (n : ℕ) : inhabited (sym' α n) := ⟨quotient.mk' (vector.repeat (default α) n)⟩ end inhabited end sym
34ba6599ff439f259f4f2a2a344062750a42496e
47181b4ef986292573c77e09fcb116584d37ea8a
/src/for_mathlib/specific_limits.lean
193fe7dc4e6d8f1a50a90c7d50384d30b2ceda3a
[ "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
5,816
lean
import analysis.special_functions.pow import data.set.function import analysis.calculus.lhopital import analysis.calculus.mean_value import analysis.asymptotics.asymptotics import analysis.asymptotics.asymptotic_equivalent import analysis.asymptotics.specific_asymptotics open filter asymptotics open_locale filter topological_space asymptotics lemma tendsto_root_at_top_nhds_1_of_pos {C: ℝ} (c_pos: C > 0): filter.tendsto (λ (n: ℕ), C^((1: ℝ) / n)) filter.at_top (nhds 1) := begin have h_exp_form: (λ (n: ℕ), C^((1: ℝ)/n)) = (λ (n: ℕ), real.exp((real.log C) / n)), { ext, simp, rw div_eq_mul_inv, rw real.exp_mul, rw real.exp_log c_pos, }, { rw h_exp_form, apply filter.tendsto.comp, apply real.tendsto_exp_nhds_0_nhds_1, apply tendsto_const_div_at_top_nhds_0_nat, } end lemma eventually_nonzero_of_tendsto_at_top {f: ℝ → ℝ} {l: filter ℝ} (htop: tendsto f l at_top): ∀ᶠ x in l, f x ≠ 0 := begin have: ∀ᶠ (y: ℝ) in at_top, y ≠ 0, { simp [eventually_at_top], exact ⟨ 1, λ b hb, by linarith only [hb] ⟩, }, convert tendsto.eventually htop this, end lemma eventually_false_of_not {α} {p q: α → Prop} {l: filter α} (hnp: ∀ᶠ x in l, ¬ p x): (∀ᶠ x in l, p x → q x) := eventually.mono hnp (λ x hnpx hpx, absurd hpx hnpx) lemma asymptotics.is_o.of_tendsto_at_top {f: ℝ → ℝ} {l: filter ℝ} (htop: tendsto f l at_top): is_o (1: ℝ → ℝ) f l := begin refine (asymptotics.is_o_iff_tendsto' _).2 _, exact eventually_false_of_not (eventually_nonzero_of_tendsto_at_top htop), convert tendsto.inv_tendsto_at_top htop, ext, simp, end lemma asymptotics.is_equivalent.left_comp_log {f g: ℝ → ℝ} {l: filter ℝ} (h: f ~[l] g) (htop: tendsto f l at_top): real.log ∘ f ~[l] real.log ∘ g := begin have fact1 : is_o (real.log ∘ f - real.log ∘ g) (1: ℝ → ℝ) l, { have hnonvanish: ∀ᶠ x in l, g x ≠ 0 := (eventually_nonzero_of_tendsto_at_top (is_equivalent.tendsto_at_top h htop)), refine (asymptotics.is_o_iff_tendsto _).2 _, simp only [forall_false_left, forall_const, pi.one_apply, one_ne_zero], simp only [function.comp_app, pi.one_apply, div_one, pi.sub_apply], refine tendsto.congr' (_: real.log ∘ (f / g) =ᶠ[l] (λ (x: ℝ), real.log (f x) - real.log (g x))) _, convert eventually.mono _ (λ (x: ℝ) (hx: f x ≠ 0 ∧ g x ≠ 0), @real.log_div (f x) (g x) hx.1 hx.2), exact (eventually_nonzero_of_tendsto_at_top htop).and hnonvanish, convert (real.continuous_at_log _).tendsto.comp ((is_equivalent_iff_tendsto_one hnonvanish).1 h), all_goals { simp, }, }, have fact2 : is_o 1 (real.log ∘ g) l := asymptotics.is_o.of_tendsto_at_top (real.tendsto_log_at_top.comp ((asymptotics.is_equivalent.tendsto_at_top_iff h).1 htop)), exact is_o.trans fact1 fact2, end lemma asymptotics.is_equivalent.left_comp_log' {f g: ℝ → ℝ} {l: filter ℝ} (h: f ~[l] g) (htop: tendsto g l at_top): real.log ∘ f ~[l] real.log ∘ g := asymptotics.is_equivalent.left_comp_log h ((asymptotics.is_equivalent.tendsto_at_top_iff h).2 htop) lemma asymptotics.is_equivalent.is_o_of_equivalent_of_o {u v w: ℝ → ℝ} {l: filter ℝ} (h_equiv: u ~[l] v) (ho: is_o v w l): is_o u w l := begin convert is_o.add (is_o.trans h_equiv ho) ho, simp, end lemma log_is_o_of_id: is_o real.log id at_top := begin refine asymptotics.is_o.congr' (_: id ∘ real.log =ᶠ[at_top] real.log) (_: real.exp ∘ real.log =ᶠ[at_top] id) _, simp, { refine eventually.mono _ (λ (x: ℝ) (hx: 0 < x), real.exp_log hx), rw [eventually_at_top], exact ⟨ 1, λ a ha, by linarith [ha] ⟩, }, { refine asymptotics.is_o.comp_tendsto _ real.tendsto_log_at_top, refine (asymptotics.is_o_iff_tendsto' (eventually_false_of_not (eventually_of_forall real.exp_ne_zero))).2 _, convert real.tendsto_pow_mul_exp_neg_at_top_nhds_0 1, field_simp [real.exp_neg], } end lemma tendsto_log1_plus_x_under_x_at_top_nhds_1: tendsto (λ (x: ℝ), real.log (1 + x) / x) at_top (𝓝 0) := begin suffices : asymptotics.is_o real.log id at_top, { apply asymptotics.is_o.tendsto_0, refine asymptotics.is_equivalent.is_o_of_equivalent_of_o (_: (λ (x: ℝ), real.log (1 + x)) ~[at_top] real.log) this, convert asymptotics.is_equivalent.left_comp_log' (_: (λ (x: ℝ), 1 + x) ~[at_top] id) tendsto_id, convert (asymptotics.is_equivalent.refl).add_is_o _, convert asymptotics.is_o_pow_pow_at_top_of_lt zero_lt_one, simp, exactI real.order_topology, }, exact log_is_o_of_id, end lemma tendsto_comparison_at_top_nhds_1_of_pos {C: ℝ} (C_pos: C > 0): filter.tendsto (λ (n: ℕ), (C*(n + 1))^((1: ℝ) / n)) filter.at_top (nhds 1) := begin have h_exp_form: (λ (n: ℕ), (C*(n + 1))^((1: ℝ) / n)) = (λ (n: ℕ), real.exp((real.log (C*(n + 1)) / n))), { ext, simp, rw [div_eq_mul_inv, real.exp_mul, real.exp_log _], exact (zero_lt_mul_right (by exact_mod_cast nat.zero_lt_succ _)).2 C_pos, }, { rw h_exp_form, apply filter.tendsto.comp, apply real.tendsto_exp_nhds_0_nhds_1, have : (λ (x: ℕ), real.log (C * (x + 1)) / x) = (λ (x: ℕ), ((real.log C / x) + real.log (1 + x) / x)), { ext, rw_mod_cast [real.log_mul (ne_of_gt C_pos) _, add_comm x 1, add_div _ _], exact_mod_cast nat.succ_ne_zero _, }, rw [this], convert filter.tendsto.add (tendsto_const_div_at_top_nhds_0_nat (real.log C)) (tendsto_log1_plus_x_under_x_at_top_nhds_1.comp tendsto_coe_nat_at_top_at_top), simp, } end
9f7f6eb46b66cee9741e647de2501075cedf550b
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/meta/widget/tactic_component.lean
781fdd8dd7d2083b8eb5b5b402800d9121b14b52
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
2,456
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ prelude import init.meta.widget.basic namespace widget /-- A component that implicitly depends on tactic_state. For efficiency we always assume that the tactic_state is unchanged between component renderings. -/ meta def tc (π : Type) (α : Type) := component (tactic_state × π) (α) namespace tc variables {π ρ α β : Type} meta def of_component : component π α → tc π α := component.map_props prod.snd meta def map_action (f : α → β) : tc π α → tc π β := component.map_action f meta def map_props (f : π → ρ) : tc ρ α → tc π α := component.map_props (prod.map id f) open interaction_monad open interaction_monad.result /-- Make a tactic component from some init, update, views which are expecting a tactic. The tactic_state never mutates. -/ meta def mk_simple [decidable_eq π] (β σ : Type) (init : π → tactic σ) (update : π → σ → β → tactic (σ × option α)) (view : π → σ → tactic (list (html β))) : tc π α := component.with_should_update (λ ⟨_,old_p⟩ ⟨_,new_p⟩, old_p ≠ new_p) $ @component.stateful (tactic_state × π) α β (interaction_monad.result tactic_state σ) (λ ⟨ts,p⟩ last, match last with | (some x) := x | none := init p ts end) (λ ⟨ts,p⟩ s b, match s with | (success s _) := match update p s b ts with | (success ⟨s,a⟩ _) := prod.mk (success s ts) (a) | (exception m p ts') := prod.mk (exception m p ts') none end | x := ⟨x,none⟩ end ) (λ ⟨ts,p⟩ s, match s with | (success s _) := match view p s ts with | (success h _) := h | (exception msg pos s) := ["rendering tactic failed "] end | (exception msg pos s) := ["state of tactic component has failed!"] end ) meta def stateless [decidable_eq π] (view : π → tactic (list (html α))) : tc π α := tc.mk_simple α unit (λ p, pure ()) (λ _ _ b, pure ((),some b)) (λ p _, view p) meta def to_html : tc π α → π → tactic (html α) | c p ts := success (html.of_component (ts,p) c) ts meta def to_component : tc unit α → component tactic_state α | c := component.map_props (λ tc, (tc,())) c meta instance cfn : has_coe_to_fun (tc π α) := ⟨λ x, π → tactic (html α), to_html⟩ end tc end widget
260eb1ba4b65ea888d012d52574e844eacb77be3
4727251e0cd73359b15b664c3170e5d754078599
/src/field_theory/minpoly.lean
7e557e7356c60b55d54a6987ed08b3b2f222c784
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
19,196
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import data.polynomial.field_division import ring_theory.integral_closure import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ open_locale classical polynomial open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`is_integral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ noncomputable def minpoly (x : B) : A[X] := if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /-- A minimal polynomial is monic. -/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := (monic hx).ne_zero lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (well_founded.min_mem degree_lt_wf _ hx).2 }, { exact aeval_zero _ } end /-- A minimal polynomial is not `1`. -/ lemma ne_one [nontrivial B] : minpoly A x ≠ 1 := begin intro h, refine (one_ne_zero : (1 : B) ≠ 0) _, simpa using congr_arg (polynomial.aeval x) h end lemma map_ne_one [nontrivial B] {R : Type*} [semiring R] [nontrivial R] (f : A →+* R) : (minpoly A x).map f ≠ 1 := begin by_cases hx : is_integral A x, { exact mt ((monic hx).eq_one_of_map_eq_one f) (ne_one A x) }, { rw [eq_zero hx, polynomial.map_zero], exact zero_ne_one }, end /-- A minimal polynomial is not a unit. -/ lemma not_is_unit [nontrivial B] : ¬ is_unit (minpoly A x) := begin haveI : nontrivial A := (algebra_map A B).domain_nontrivial, by_cases hx : is_integral A x, { exact mt (eq_one_of_is_unit_of_monic (monic hx)) (ne_one A x) }, { rw [eq_zero hx], exact not_is_unit_zero } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, key.symm⟩, end /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ lemma min {p : A[X]} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end @[nontriviality] lemma subsingleton [subsingleton B] : minpoly A x = 1 := begin nontriviality A, have := minpoly.min A x monic_one (subsingleton.elim _ _), rw degree_one at this, cases le_or_lt (minpoly A x).degree 0 with h h, { rwa (monic ⟨1, monic_one, by simp⟩ : (minpoly A x).monic).degree_le_zero_iff_eq_one at h }, { exact (this.not_lt h).elim }, end end ring section comm_ring variables [comm_ring A] section ring variables [ring B] [algebra A B] [nontrivial B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin nontriviality A, have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1, { apply with_bot.coe_le_coe.1, rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)), with_top.coe_one, ←degree_X_sub_C a], refine min A (algebra_map A B a) (monic_X_sub_C a) _, simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] }, have hdeg : (minpoly A (algebra_map A B a)).degree = 1, { apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2, apply le_antisymm hdegle (nat_degree_pos (@is_integral_algebra_map A B _ _ _ a)) }, have hrw := eq_X_add_C_of_degree_eq_one hdeg, simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul, monic.leading_coeff, ring_hom.map_one] at hrw, have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a, { have hroot := aeval A (algebra_map A B a), rw [hrw, add_comm] at hroot, simp only [aeval_C, aeval_X, aeval_add] at hroot, replace hroot := eq_neg_of_add_eq_zero_left hroot, rw [←ring_hom.map_neg _ a] at hroot, exact (hf hroot) }, rw hrw, simp only [h0, ring_hom.map_neg, sub_eq_add_neg], end end ring section is_domain variables [is_domain A] [ring B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : A[X]} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minpoly.min A x hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end variables [is_domain B] /-- A minimal polynomial is irreducible. -/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minpoly A x : hab_eq }, have hzero := aeval A x, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end is_domain end comm_ring section field variables [field A] section ring variables [ring B] [algebra A B] variables {x : B} variables (A x) /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/ lemma degree_le_of_ne_zero {p : A[X]} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := calc degree (minpoly A x) ≤ degree (p * C (leading_coeff p)⁻¹) : min A x (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz lemma ne_zero_of_finite_field_extension (e : B) [finite_dimensional A B] : minpoly A e ≠ 0 := minpoly.ne_zero $ is_integral_of_noetherian (is_noetherian.iff_fg.2 infer_instance) _ /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. -/ lemma unique {p : A[X]} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : A[X], q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minpoly A x := begin have hx : is_integral A x := ⟨p, pmonic, hp⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero A x hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min A x pmonic hp) (pmin (minpoly A x) (monic hx) (aeval A x)) } end /-- If an element `x` is a root of a polynomial `p`, then the minimal polynomial of `x` divides `p`. -/ lemma dvd {p : A[X]} (hp : polynomial.aeval x p = 0) : minpoly A x ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, dvd_zero] }, have hx : is_integral A x, { rw ← is_algebraic_iff_is_integral, exact ⟨p, hp0, hp⟩ }, rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero A x hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower (A K : Type*) {R : Type*} [comm_ring A] [field K] [comm_ring R] [algebra A K] [algebra A R] [algebra K R] [is_scalar_tower A K R] (x : R) : minpoly K x ∣ (minpoly A x).map (algebra_map A K) := by { refine minpoly.dvd K x _, rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } /-- If `y` is a conjugate of `x` over a field `K`, then it is a conjugate over a subring `R`. -/ lemma aeval_of_is_scalar_tower (R : Type*) {K T U : Type*} [comm_ring R] [field K] [comm_ring T] [algebra R K] [algebra K T] [algebra R T] [is_scalar_tower R K T] [comm_semiring U] [algebra K U] [algebra R U] [is_scalar_tower R K U] (x : T) (y : U) (hy : polynomial.aeval y (minpoly K x) = 0) : polynomial.aeval y (minpoly R x) = 0 := by { rw is_scalar_tower.aeval_apply R K, exact eval₂_eq_zero_of_dvd_of_eval₂_eq_zero (algebra_map K U) y (minpoly.dvd_map_of_is_scalar_tower R K x) hy } variables {A x} theorem eq_of_irreducible_of_monic [nontrivial B] {p : A[X]} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minpoly A x := let ⟨q, hq⟩ := dvd A x hp2 in eq_of_monic_of_associated hp3 (monic ⟨p, ⟨hp3, hp2⟩⟩) $ mul_one (minpoly A x) ▸ hq.symm ▸ associated.mul_left _ $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit A x lemma eq_of_irreducible [nontrivial B] {p : A[X]} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) : p * C p.leading_coeff⁻¹ = minpoly A x := begin have : p.leading_coeff ≠ 0 := leading_coeff_ne_zero.mpr hp1.ne_zero, apply eq_of_irreducible_of_monic, { exact associated.irreducible ⟨⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rwa [←C_mul, inv_mul_cancel, C_1], by rwa [←C_mul, mul_inv_cancel, C_1]⟩, rfl⟩ hp1 }, { rw [aeval_mul, hp2, zero_mul] }, { rwa [polynomial.monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel] }, end /-- If `y` is the image of `x` in an extension, their minimal polynomials coincide. We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails since `is_integral R y` depends on y. -/ lemma eq_of_algebra_map_eq {K S T : Type*} [field K] [comm_ring S] [comm_ring T] [algebra K S] [algebra K T] [algebra S T] [is_scalar_tower K S T] (hST : function.injective (algebra_map S T)) {x : S} {y : T} (hx : is_integral K x) (h : y = algebra_map S T x) : minpoly K x = minpoly K y := minpoly.unique _ _ (minpoly.monic hx) (by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval, ring_hom.map_zero]) (λ q q_monic root_q, minpoly.min _ _ q_monic (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST (h ▸ root_q : polynomial.aeval (algebra_map S T x) q = 0))) lemma add_algebra_map {B : Type*} [comm_ring B] [algebra A B] {x : B} (hx : is_integral A x) (a : A) : minpoly A (x + (algebra_map A B a)) = (minpoly A x).comp (X - C a) := begin refine (minpoly.unique _ _ ((minpoly.monic hx).comp_X_sub_C _) _ (λ q qmo hq, _)).symm, { simp [aeval_comp] }, { have : (polynomial.aeval x) (q.comp (X + C a)) = 0 := by simpa [aeval_comp] using hq, have H := minpoly.min A x (qmo.comp_X_add_C _) this, rw [degree_eq_nat_degree qmo.ne_zero, degree_eq_nat_degree ((minpoly.monic hx).comp_X_sub_C _).ne_zero, with_bot.coe_le_coe, nat_degree_comp, nat_degree_X_sub_C, mul_one], rwa [degree_eq_nat_degree (minpoly.ne_zero hx), degree_eq_nat_degree (qmo.comp_X_add_C _).ne_zero, with_bot.coe_le_coe, nat_degree_comp, nat_degree_X_add_C, mul_one] at H } end lemma sub_algebra_map {B : Type*} [comm_ring B] [algebra A B] {x : B} (hx : is_integral A x) (a : A) : minpoly A (x - (algebra_map A B a)) = (minpoly A x).comp (X + C a) := by simpa [sub_eq_add_neg] using add_algebra_map hx (-a) section gcd_domain /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. -/ lemma gcd_domain_eq_field_fractions {A R : Type*} (K : Type*) [comm_ring A] [is_domain A] [normalized_gcd_monoid A] [field K] [comm_ring R] [is_domain R] [algebra A K] [is_fraction_ring A K] [algebra K R] [algebra A R] [is_scalar_tower A K R] {x : R} (hx : is_integral A x) : minpoly K x = (minpoly A x).map (algebra_map A K) := begin symmetry, refine eq_of_irreducible_of_monic _ _ _, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply A K R x (minpoly A x), rwa [aeval, eq_comm] at htower }, { exact (monic hx).map _ } end /-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. -/ lemma gcd_domain_dvd {A R : Type*} (K : Type*) [comm_ring A] [is_domain A] [normalized_gcd_monoid A] [field K] [comm_ring R] [is_domain R] [algebra A K] [is_fraction_ring A K] [algebra K R] [algebra A R] [is_scalar_tower A K R] {x : R} (hx : is_integral A x) {P : A[X]} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) : minpoly A x ∣ P := begin apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map K (monic.is_primitive (monic hx)) hprim).2, rw ← gcd_domain_eq_field_fractions K hx, refine dvd _ _ _, rwa ← is_scalar_tower.aeval_apply end end gcd_domain variables (B) [nontrivial B] /-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`, then the minimal polynomial of `algebra_map K B x` is `X - C x`. -/ lemma eq_X_sub_C (a : A) : minpoly A (algebra_map A B a) = X - C a := eq_X_sub_C_of_algebra_map_inj a (algebra_map A B).injective lemma eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a variables (A) /-- The minimal polynomial of `0` is `X`. -/ @[simp] lemma zero : minpoly A (0:B) = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using eq_X_sub_C B (0:A) /-- The minimal polynomial of `1` is `X - 1`. -/ @[simp] lemma one : minpoly A (1:B) = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1:A) end ring section is_domain variables [ring B] [is_domain B] [algebra A B] variables {x : B} /-- A minimal polynomial is prime. -/ lemma prime (hx : is_integral A x) : prime (minpoly A x) := begin refine ⟨ne_zero hx, not_is_unit A x, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval A x], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd A x) (dvd A x) this end /-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/ lemma root {x : B} (hx : is_integral A x) {y : A} (h : is_root (minpoly A x) y) : algebra_map A B y = x := have key : minpoly A x = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd ((irreducible_X_sub_C y).dvd_symm (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval A x, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /-- The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/ @[simp] lemma coeff_zero_eq_zero (hx : is_integral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /-- The minimal polynomial of a nonzero element has nonzero constant coefficient. -/ lemma coeff_zero_ne_zero (hx : is_integral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 := by { contrapose! h, simpa only [hx, coeff_zero_eq_zero] using h } end is_domain end field end minpoly
b7026490bedf292687dbb9caa8f95b9dd3a75268
e30ff3aabdac29f8ea40ad76887544d0f9be9018
/ircbot/unicode.lean
ab0033e8f926a605187bb0c955e12ed6a5d0c347
[]
no_license
forked-from-1kasper/leanbot
bdef0efa3e4d0eb75b06c1707fb4e35086bb57fa
c61c8c7fdad7b05877e0d232719ce23d2999557f
refs/heads/master
1,651,846,081,986
1,646,404,009,000
1,646,404,009,000
127,132,795
12
1
null
1,605,183,650,000
1,522,237,998,000
Lean
UTF-8
Lean
false
false
2,723
lean
import data.buffer system.io import ircbot.bitvec namespace unicode private def utf_8_convert_bitvec : list (bitvec 8) → option (list char) -- 0xxxxxxx -- symbols from 0 to 7Fh | (⟨ff :: tl₁, _⟩ :: chars) := list.cons (char.of_nat (bitvec.bits_to_nat tl₁)) <$> utf_8_convert_bitvec chars -- 110xxxxx 10xxxxxx -- symbols from 80h to 7FFh | (⟨tt :: tt :: ff :: tl₁, _⟩ :: ⟨tt :: ff :: tl₂, _⟩ :: chars) := list.cons (char.of_nat (bitvec.bits_to_nat $ tl₁ ++ tl₂)) <$> utf_8_convert_bitvec chars -- 1110xxxx 10xxxxxx 10xxxxxx -- symbols from 800h to FFFFh | (⟨tt :: tt :: tt :: ff :: tl₁, _⟩ :: ⟨tt :: ff :: tl₂, _⟩ :: ⟨tt :: ff :: tl₃, _⟩ :: chars) := list.cons (char.of_nat (bitvec.bits_to_nat $ tl₁ ++ tl₂ ++ tl₃)) <$> utf_8_convert_bitvec chars -- 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx -- symbols from 10000h to 10FFFFh | (⟨tt :: tt :: tt :: tt :: ff :: tl₁, _⟩ :: ⟨tt :: ff :: tl₂, _⟩ :: ⟨tt :: ff :: tl₃, _⟩ :: ⟨tt :: ff :: tl₄, _⟩ :: chars) := list.cons (char.of_nat (bitvec.bits_to_nat $ tl₁ ++ tl₂ ++ tl₃ ++ tl₄)) <$> utf_8_convert_bitvec chars | [] := some [] | _ := none -- Default Lean’s convert from char_buffer to string is incorrect -- (when we get a string using get_line, for example), -- because it does not work correctly with Unicode and UTF-8, in particular. -- This is simple realisation of correct convert from char_buffer to string -- for UTF-8 encoding. def utf8_to_string (buff : char_buffer) : option string := list.as_string <$> utf_8_convert_bitvec (list.map (bitvec.of_nat 8 ∘ char.to_nat) buff.to_list) def get_buffer (buff :char_buffer) : string := option.get_or_else (utf8_to_string buff) "" private def char_to_unicode (c : ℕ) : list ℕ := -- 0xxxxxxx -- symbols from 0 to 7Fh if c ≤ 0x7f then [ c ] -- 110xxxxx 10xxxxxx -- symbols from 80h to 7FFh else if c ≤ 0x7ff then [ nat.lor 0b11000000 (nat.shiftr c 6), nat.lor 0b10000000 (c % nat.shiftl 1 6) ] -- 1110xxxx 10xxxxxx 10xxxxxx -- symbols from 800h to FFFFh else if c ≤ 0xffff then [ nat.lor 0b11100000 (nat.shiftr c 12), nat.lor 0b10000000 (nat.shiftr c 6 % nat.shiftl 1 6), nat.lor 0b10000000 (c % nat.shiftl 1 6) ] -- 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx -- symbols from 10000h to 10FFFFh else if c ≤ 0x10ffff then [ nat.lor 0b11110000 (nat.shiftr c 18), nat.lor 0b10000000 (nat.shiftr c 12 % nat.shiftl 1 6), nat.lor 0b10000000 (nat.shiftr c 6 % nat.shiftl 1 6), nat.lor 0b10000000 (c % nat.shiftl 1 6) ] else [] def string_to_utf8 (s : string) : string := list.as_string $ list.join $ (functor.map char.of_nat ∘ char_to_unicode) <$> char.to_nat <$> s.to_list end unicode
29983be59fa40692872ae745934e923d3c403a8a
431385f9e6a07bcb49fbcb5d7d1dc527cd33580a
/src/zfc.lean
14639e171c51fd280b5572a51d82b5b7492a4627
[]
no_license
maxkaske/zfolean
c853044cbff465b92269fafe1bd8e078e192b2f0
b74bb7accf01b25a6efb3af6b06538f98e7e5a6c
refs/heads/master
1,677,841,414,729
1,613,649,566,000
1,613,649,566,000
336,965,499
1
0
null
null
null
null
UTF-8
Lean
false
false
45,477
lean
import fol import data.set import tls_tactic /-! # ZFC set theory In this file we define the signature and axioms of Zermelo–Fraenkel with axiom of choice and give a natural deduction proof of the induction principle in its set theoretical form. ## Main results - `omega_smallest_inductive_provable`: we show that ZFC proves that ω is the smallest inductive set. a direct consequence of - `omega_smallest_inductive`: a natural deduction proof that ω is the smallest inductive set ## References * [K. Kunen, *Set Theory*] [KUN83] -- for their axiomatization of ZF * [H.D. Ebbinghaus, *Einführung in die Mengenlehre*] [EBB03] -- for their formalization of axiom of choice -/ universe variable u namespace zfc open fol -- for inserting elements into a data.set local infix ` >> ` := insert section zfc_language /- We will use single predicate for membership and nothing else -/ inductive pred_symb : ℕ → Type u | elem : pred_symb 2 inductive func_symb : ℕ → Type u def σ : signature := { func_symb:= zfc.func_symb , pred_symb:= zfc.pred_symb } /-- Definition of the membership predicate.-/ def memb (t₁ t₂: term σ): formula σ := papp (papp (pred pred_symb.elem) t₁) t₂ infix ` ∈' `:100 := memb -- for the simplifier @[simp, tls] lemma lift_memb (t₁ t₂: term σ) (m i) : (t₁ ∈' t₂) ↑ m @ i = (t₁ ↑ m @ i) ∈' (t₂ ↑ m @ i) := by refl @[simp, tls] lemma subst_memb (t₁ t₂: term σ) (s k) : (t₁ ∈' t₂) [s ⁄ k] = (t₁ [s ⁄ k]) ∈' (t₂ [s ⁄ k]) := by refl -- Predicates in our meta signature /-- Definition of the subset predicate.-/ def subset (X Y : term σ) : (formula σ) := ∀' ((#0 ∈' (X ↑ 1 @ 0)) →' (#0 ∈' (Y ↑ 1 @ 0))) infix ` ⊆' `:100 := subset /-- Definition of the successor.-/ def successor_def (X Y: term σ) : formula σ := ∀'((#0 ∈' (X ↑ 1 @ 0)) ↔' ((#0 ∈' (Y ↑ 1 @ 0) ∨' (#0 =' (Y ↑ 1 @ 0))))) infix ` is_successor_of `:100 := successor_def /-- Definition of the empty set.-/ def empty_def (x : term σ) : formula σ := ∀' ((#0 ∈' (x ↑ 1 @ 0)) ↔' ¬'(#0 =' #0)) postfix ` is_empty`:100 := empty_def /-- Definition of inductive sets.-/ def inductive_def (x : term σ) : formula σ := (∀' (#0 is_empty →' (#0 ∈' (x ↑ 1 @ 0)))) ∧' (∀'(#0 ∈' (x ↑ 1 @ 0) →' (∀'(#0 is_successor_of #1 →' (#0 ∈' (x ↑ 2 @ 0)))))) postfix ` is_inductive`:100 := inductive_def /-- Definition of `ω`.-/ def omega_def (x : term σ) : formula σ := ∀' (#0 ∈' (x ↑ 1 @ 0) ↔' ∀' (#0 is_inductive →' (x ↑ 1 @ 0) ∈' #0)) postfix ` is_omega`:100 := omega_def /-- Definition of uniqueness in the first variable. -/ @[simp] def unique_in_var0 (φ: formula σ) : formula σ := ∀' ∀' ((φ ↑ 1 @ 1) ∧' (φ ↑ 1 @ 0) →' (#0 =' #1)) /-- Definition of the unique existential quantifier. -/ @[simp] def unique_ex (φ : formula σ) : formula σ := (∃'φ) ∧' (unique_in_var0 φ) prefix `∃!`:110 := unique_ex end zfc_language /- -- some notation for the pretty printer to make debugging easier -- before #check #1 ∈' #2 -- #1 ∈' #2 : formula σ #reduce #1 ∈' #2 -- ((pred pred_symb.elem).papp #1).papp #2 #reduce (#0 ∈' #2 ∧' #1 ∈' #2) ↑ 1 @ 1 -- ((pred pred_symb.elem).papp #0).papp #3 ∧' ((pred pred_symb.elem).papp #2).papp #3 notation s ` '∈ `:100 t := papp (papp (pred pred_symb.elem) s) t -- after #check #1 ∈' #2 -- #1 ∈' #2 : formula σ #reduce #1 ∈' #2 -- #1 ∈ #2 #reduce (#0 ∈' #2 ∧' #1 ∈' #2) ↑ 1 @ 1 -- (#0 ∈ #3) ∧' #2 ∈ #3 -- much better -/ section zfc_axioms /- Definitions and lemmas related to the axiom scheme of separation -/ namespace separation open fol /-- Defintion of the axiom scheme of separation with free variables. -/ @[simp] def free_formula (φ : formula σ): formula σ := ∀' ∃' ∀' ((#0 ∈' #1) ↔' (#0 ∈' #2 ∧' (φ ↑ 1 @ 1))) lemma closed{k} {φ} (H: closed (k+2) φ) : closed k (free_formula φ) := begin have h₁: ¬ k + 3 ≤ 2, by linarith, have h₂: 1 ≤ k+2, by linarith, have h₃: φ ↑ 1 @ 1 ↑ 1 @ (k + 3) = φ ↑ 1 @ 1, begin rw ←(lift_lift φ 1 1 h₂), congr, exact H, end, simp[h₁, h₃], end /-- Defintion of the axiom scheme of separation. -/ def formula (φ : fol.formula σ) {n : ℕ} (φ_h: formula.closed (n+2) φ) : fol.formula σ := formula.closure (free_formula φ) (closed φ_h) lemma formula_is_sentence {k : ℕ} (φ : fol.formula σ) (H: formula.closed (k+2) φ) : (formula φ H) is_sentence := begin exact closure_is_sentence (closed H) end lemma lift_sentence (φ) (n) (φ_h: fol.formula.closed (n+2) φ) (m i) : (formula φ φ_h) ↑ m @ i = formula φ φ_h := lift_sentence_id (formula_is_sentence _ _) /- To following definition and lemmas are used to make future proofs more explicit and readable. -/ lemma mem {Γ:set $ fol.formula σ} (φ) (k) (φ_h: formula.closed (k+2) φ) {ψ} (h : ψ = separation.formula φ φ_h) (H: (separation.formula φ φ_h) ∈ Γ) : ψ ∈ Γ := begin subst h, exact H, end /-- Defintion of the axiom scheme of separation as set. -/ def scheme : set $ fol.formula σ := { (separation.formula φ φ_h) | (φ : fol.formula σ) (k: ℕ) (φ_h : formula.closed (k+2) φ) } lemma mem_scheme (φ : fol.formula σ) {k : ℕ} (φ_h: fol.formula.closed (k+2) φ) : separation.formula φ φ_h ∈ scheme := begin existsi [φ, k, φ_h], refl end end separation /- Definitions and lemmas related to the axiom scheme of replacement. -/ namespace replacement /-- Defintion of the axiom scheme of replacement with free variables. -/ @[simp] def free_formula (φ: formula σ) := (∀'(∀'(#0 ∈' #1 →' ∃!φ) →' (∃' ∀'(#0 ∈' #2 →' (∃'(#0 ∈' #2 ∧' (φ ↑ 1 @ 2))))))) lemma closed {k} {φ} (H: closed (k+3) φ) : closed k (free_formula φ) := begin have : ¬ k+4 ≤ 3, by linarith, have : ¬ k+4 ≤ 2, by linarith, have : ¬ k+3 ≤ 2, by linarith, have h₁ : 0 ≤ k+3, from (k+3).zero_le, have h₂ : 1 ≤ k+3, by linarith, have h₃ : 2 ≤ k+3, by linarith, have H₁ : (φ ↑ 1 @ 0) ↑ 1 @ (k + 4) = φ ↑ 1 @ 0, from begin rw ←(lift_lift φ 1 1 h₁), congr, exact H, end, have H₂: (φ ↑ 1 @ 1) ↑ 1 @ (k + 4) = φ ↑ 1 @ 1, from begin rw ←(lift_lift φ 1 1 h₂), congr, exact H, end, have H₃: (φ ↑ 1 @ 2) ↑ 1 @ (k + 4) = φ ↑ 1 @ 2, from begin rw ←(lift_lift φ 1 1 h₃), congr, exact H, end, rw closed at H, clear h₂, simp[*, closed], end /-- Defintion of the axiom scheme of replacement-/ def formula (φ : fol.formula σ) {n : ℕ} (φ_h: formula.closed (n+3) φ) : fol.formula σ := formula.closure (free_formula φ) (closed φ_h) lemma formula_is_sentence (φ : fol.formula σ) {k : ℕ} (H: fol.formula.closed (k+3) φ) : (formula φ H) is_sentence := begin exact closure_is_sentence (closed H) end lemma lift_sentence (φ) (n) (φ_h: fol.formula.closed (n+3) φ) (m i) : (formula φ φ_h) ↑ m @ i = formula φ φ_h := lift_sentence_id (formula_is_sentence _ _) /- To following definition and lemmas are used to make future proofs more explicit and readable. -/ lemma mem {Γ:set $ fol.formula σ} {ψ} (φ) {k} (φ_h: formula.closed (k+3) φ) (h : ψ = formula φ φ_h) (H: (formula φ φ_h) ∈ Γ) : ψ ∈ Γ := begin subst h, exact H end /-- Defintion of the axiom scheme of replacement as set-/ def scheme : set $ fol.formula σ := { (formula φ φ_h) | (φ : fol.formula σ) (k: ℕ) (φ_h : fol.formula.closed (k+3) φ) } lemma mem_scheme (φ : fol.formula σ) {k : ℕ} (φ_h: fol.formula.closed (k+3) φ) : formula φ φ_h ∈ scheme := begin existsi [φ, k, φ_h], refl, end end replacement /- ∀b ∀a (∀x (x ∈ a ↔ x ∈ b) → a = b) -/ @[simp] def extensionality : formula σ := ∀' ∀' ((∀' (#0 ∈' #1 ↔' #0 ∈' #2)) →' (#0 =' #1)) /- ∀b ∀a ∃A ∀x (x = a ∨ x = b → x ∈ A) -/ @[simp] def pair_ax : formula σ := ∀' ∀' ∃' ∀' ((#0 =' #2) ∨' (#0 =' #3) →' (#0 ∈' #1)) /- ∀F ∃A ∀x (∃y (x ∈ y ∧ y ∈ F) → x ∈ A) -/ @[simp] def union_ax : formula σ := ∀' ∃' ∀' ((∃'(#1 ∈' #0 ∧' #0 ∈' #3)) →' (#0 ∈' #1)) /- ∀y ∃A ∀x (x ⊆ y → x ∈ A) -/ @[simp] def power_ax : formula σ := ∀' ∃' ∀' (#0 ⊆' #2 →' #0 ∈' #1) /-- ∃w (w is inductive) -/ @[simp] def infinity_ax : formula σ := ∃' (#0 is_inductive) /- x (¬(x is empty) → ∃y(y ∈ x ∧ ¬(∃z (z ∈ y ∧ z ∈ x))) -/ @[simp] def regularity : formula σ := ∀' (¬'(#0 is_empty) →' (∃' ((#0 ∈' #1) ∧' ¬' ∃'(#0 ∈' #1 ∧' #0 ∈' #2)))) /- For every set `X` of nonempty, pairwise disjoint sets, there exists a set `Y` containing exactly one element of each element of `X`. ∀X (∀x ∀y (x ∈ X ∧ y ∈ X → (¬(x is empty_def) ∧ (x=y ∨ ∀z ¬ (z ∈ x ∧ z ∈ y))) → ∃Y ∀x (x ∈ X → ∃!z (z ∈ x ∧ z ∈ Y)) -/ @[simp] def axiom_of_choice : formula σ := ∀' (∀' ∀' (#0 ∈' #2 ∧' #1 ∈' #2 →' ∃' (#0 ∈' #1) ∧' (#0 =' #1 ∨' ∀' (¬'((#0 ∈' #1 ∧' #0 ∈' #2))))) →' ∃' ∀' (#0 ∈' #2 →' ∃! (#0 ∈' #1 ∧' #0 ∈' #2))) /-- ∀A ∃B ∀x (x ∈ B ↔ x ∈ A ∧ φ ↑ 1 @ 1) -/ @[simp] def separation_ax (φ : formula σ) {n} (φ_h: closed (n+2) φ) : formula σ := separation.formula φ φ_h /-- ∀A (∀x(x ∈ A → ∃!y φ) → ∃B ∀x (x ∈ A → ∃y (y ∈ B ∧ φ) -/ @[simp] def replacement_ax (φ : formula σ) {n} (φ_h: closed (n+3) φ) : formula σ := replacement.formula φ φ_h /-- The axioms of ZFC set theory as set. -/ def zfc_ax : set $ formula σ := { extensionality, pair_ax, union_ax, power_ax, infinity_ax, regularity, axiom_of_choice} ∪ separation.scheme ∪ replacement.scheme lemma zfc_ax_set_of_sentences: ∀ x ∈ zfc_ax, (x is_sentence) := begin intros φ h, repeat{cases h,}; try {unfold sentence closed, refl, }, { cases h_h with n hn, cases hn with h hh, subst hh, apply separation.formula_is_sentence, }, { cases h_h with n hn, cases hn with h hh, subst hh, apply replacement.formula_is_sentence, }, end lemma lift_zfc_ax {m i} : (λ ϕ: formula σ, ϕ ↑ m @ i) '' zfc_ax = zfc_ax := lift_set_of_sentences_id zfc_ax_set_of_sentences /- We mainly use the following lemmas to make usage of axioms more explicit in the text. -/ -- for arbitrary sets lemma extensionality_mem {Γ: set $ formula σ}{φ}(h: φ = extensionality)(H: extensionality ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma pair_ax_mem {Γ: set $ formula σ} {φ} (h: φ = pair_ax) (H: pair_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma union_ax_mem {Γ: set $ formula σ} {φ} (h: φ = union_ax) (H: union_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma power_ax_mem {Γ: set $ formula σ} {φ} (H: power_ax ∈ Γ) (h: φ = power_ax) : φ ∈ Γ := begin subst h, exact H end lemma infinity_ax_mem {Γ: set $ formula σ} {φ} (h: φ = infinity_ax) (H: infinity_ax ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma regularity_mem {Γ: set $ formula σ}{φ}(h: φ = regularity)(H: regularity ∈ Γ) : φ ∈ Γ := begin subst h, exact H end lemma aoc_mem {Γ: set $ formula σ}{φ}(h: φ = axiom_of_choice)(H: axiom_of_choice ∈ Γ) : φ ∈ Γ := begin subst h, exact H end -- for zfc_ax lemma extensionality_mem_zfc_ax : extensionality ∈ zfc_ax := by simp[-extensionality, zfc_ax] lemma pair_ax_mem_zfc_ax : pair_ax ∈ zfc_ax := by simp[-pair_ax, zfc_ax] lemma union_ax_mem_zfc_ax : union_ax ∈ zfc_ax := by simp[-union_ax, zfc_ax] lemma power_ax_mem_zfc_ax : power_ax ∈ zfc_ax := by simp[-power_ax, zfc_ax] lemma infinity_ax_mem_zfc_ax : infinity_ax ∈ zfc_ax := by simp[-infinity_ax, zfc_ax] lemma regularity_mem_zfc_ax : regularity ∈ zfc_ax := by simp[zfc_ax] lemma aoc_mem_zfc_ax : axiom_of_choice ∈ zfc_ax := by simp[zfc_ax] namespace separation lemma mem_zfc_ax (φ k) (φ_h: formula.closed (k+2) φ) : formula φ φ_h ∈ zfc_ax := begin simp[-sentence, zfc_ax, mem_scheme], end end separation namespace replacement lemma mem_zfc_ax (φ k) (φ_h: formula.closed (k+3) φ) : formula φ φ_h ∈ zfc_ax := begin simp[-sentence, zfc_ax, mem_scheme], end end replacement end zfc_axioms section zfc_proofs /- ### On comments inside the proofs The first proof is the only one with excessive use of comments/ In the following proofs we will give readable goals and the current variable environment, hoping that the context should be clear. for example the current goal might look like (λ (ϕ : formula σ), ϕ ↑ 1 @ 0) '' (∀'(#0 ∈' #1 ↔' #0 =' #3 ∨' #0 =' #3) >> (λ (ϕ : formula σ), ϕ ↑ 1 @ 0) '' ((λ (ϕ : formula σ), ϕ ↑ 1 @ 0) '' zfc_ax)) ⊢ ((#0 ∈' #1 →' #0 =' #3) ↑ 1 @ (0 + 1 + 1))[#0 ⁄ 0 + 1] while the comment reads `a {a,a} x ⊢ x ∈ {a,a} → x = a` * a {a,a} x are sets (usually with associated properties hidden in the context, or obvious from the name) * indices pointing to 0 talk about x * indices pointing to 1 talk about {a,a} * indices pointing to 2 talk about a * the goal should be read as `x ∈ {a,a} → x = a` -//- Lastly we use "-- meta" to denote parts of a proof not directly involving terms of type `fol.proof`. This is usually the case at the leaves of of a natural deduction proof tree where we have to reason about formulas being equal or element of the context. -/ /-- A formal proof that for all sets `b,a` there exists a set containing exactly `a` and `b`. Informally: `zfc_ax ⊢ ∀b ∀a ∃A ∀x (x ∈ A ↔ x=a ∨ x=b)` -/ def pairset_ex: zfc_ax ⊢ ∀' ∀' ∃' ∀' ((#0 ∈' #1) ↔' (#0 =' #2) ∨' (#0 =' #3)) := begin apply allI, -- given a apply allI, -- given b apply exE ∀'((#0 =' #2) ∨' (#0 =' #3) →' (#0 ∈' #1)), -- let A be a set containing b and a, { -- such a set exists pair pairing: apply allE' _ #0, -- bind b --(∃' ∀'((#0 =' #2) ∧' (#0 =' #4) →' (#0 ∈' #1))) #0, apply allE' _ #1, -- bind a --(∀' ∃' ∀'((#0 =' #2) ∧' (#0 =' #3) →' (#0 ∈' #1))) #1, apply hypI, -- this is a hypothesis -- meta simp only [lift_zfc_ax], apply pair_ax_mem_zfc_ax, simp[zfc_ax], all_goals { simp } }, { -- now we can use A and its defining property for further arguments -- reminder: sets (in order) a b A apply exE (∀'(#0 ∈' #1 ↔' (#0 ∈' #2) ∧' (#0 =' #3 ∨' #0 =' #4))), -- let {b,a} be the set {x | x ∈ A ∧ (x=b ∨ x=a)} { -- such a set exists by separation: apply allE' _ #0, -- bind A apply allE' _ #1, -- bind b apply allE' _ #2, -- bind a apply hypI, -- this is a hypothesis -- meta apply separation.mem (#0 =' #2 ∨' #0 =' #3) 2 (rfl) (rfl), -- an instance of separation simp only [lift_zfc_ax], right, apply separation.mem_zfc_ax, all_goals{ simp[alls] }, refl }, { -- variables (in order) a b A { x | x ∈ A ∧ (x=b ∨ x=a)} apply exI #0, -- put X := {b,a}:= { x | x ∈ A ∧ (x=b ∨ x=a)} , we need to show that it satisfies the defining property apply allI, -- stack : a b A {b,a} x apply andI, { -- ⊢ x ∈ {b,a} → x=b ∨ x=a apply impI, -- assume x ∈ {b,a} we want to show x=b ∨ x=a apply andE₂ (#0 ∈' #2), -- it suffices to show x ∈ A ∧ (x=b ∨ x=a) apply impE_insert, -- moreover it suffices to show x ∈ {b,a} → x ∈ A ∧ (x=b ∨ x=a) apply iffE_r, -- it suffices to show x ∈ {b,a} ↔ x ∈ A ∧ (x=b ∨ x=a) apply allE_var0, -- bind x apply hypI, -- then this is a hypothesis, namely the defining property of { x | x ∈ A ∧ (x=b ∨ x=a) -- meta simp only [set.image_insert_eq], apply set.mem_insert, }, { -- ⊢ x ∈ {b,a} ← x=b ∨ x=a apply impI, -- assume x=b ∨ x=a, we need to show x ∈ {b,a} apply impE (#0 ∈' #2), -- it suffices to show x ∈ A and x ∈ A → x ∈ {b,a} { -- first we show x ∈ A apply impE ((#0 =' #3) ∨' (#0 =' #4)), -- it suffices to show x = b ∨ x=a and x = b ∨ x=a → x ∈ A { -- we show x = b ∨ x = a apply hypI1 }, -- which is true by assumption { -- we show x = b ∨ x = a → x ∈ A apply allE_var0, -- if we bind x apply hypI, -- then this is how A was defined -- meta simp only [set.image_insert_eq], right, right, apply set.mem_insert } }, { -- next we show x ∈ A → x ∈ {b,a} apply impI, -- assume x ∈ A apply impE (#0 ∈' #2 ∧' ((#0 =' #3) ∨' (#0 =' #4))), -- then it suffices to show ... { -- x ∈ A ∧ x=0 ∨ x=b apply andI, -- we need to show ... { -- ⊢ x ∈ A apply hypI1 }, -- by assumption { -- ⊢ x = 0 ∨ x=b apply hypI2 } },-- by assumption { -- ⊢ x ∈ A ∧ x=0 ∨ x=b → x ∈ {b,a} apply iffE_l, -- it suffices to show x ∈ {b,a} ↔ x ∈ A ∧ x=0 ∨ x=b apply allE_var0, -- binding x apply hypI, -- this how we defined {b,a} in the first place -- meta simp only [set.image_insert_eq], right, right, apply set.mem_insert } } } } }, end /-- Formal proof that an empty_def set exists. Informally: `zfc_ax ⊢ ∃A (∀x (x ∈ A ↔ x≠x)) ` -/ def emptyset_ex : zfc_ax ⊢ ∃' (#0 is_empty):= begin -- consider the set { x | x ∈ A ∧ ¬'(#0 =' #0) } apply exE ∀'(#0 ∈' #1 ↔' #0 ∈' #2 ∧' ¬'(#0 =' #0)), { -- such a set exists by separation apply allE_var0, -- bind A apply hypI, -- then this is true by separation apply separation.mem (¬'(#0 =' #0)) 0 (rfl) (rfl), apply separation.mem_zfc_ax, }, { -- ⊢ ∃X ∀x (x ∈ X ↔ ¬ (x = x)) apply exI #0, -- Put X:={ x | x ∈ A ∧ ¬'(#0 =' #0) } apply allI, -- given x apply andI, { -- ⊢ x ∈ X → ¬ (x = x) apply impI, apply andE₂ _, apply impE_insert, apply iffE_r, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], left, refl }, { -- ⊢ ¬ (x = x) → x ∈ X apply impI, apply botE, apply impE (#0 =' #0), apply eqI, apply hypI, -- meta left, refl } }, end /-- Formal proof that for all sets `a` there exists a set containing just `a`. Informally: `zfc_ax ⊢ ∀a ∃A (∀x (x ∈ A ↔ x = a)) ` -/ def singleton_ex : zfc_ax ⊢ ∀' ∃' ∀' (#0 ∈' #1 ↔' #0 =' #3) := begin apply allI, --given a apply exE ∀' (#0 ∈' #1 ↔' #0 =' #3 ∨' #0 =' #3), -- have the set {a,a} { -- a ⊢ ∃A (A = {a,a}) apply allE' _ #1, apply allE' _ #1, rw [lift_zfc_ax], apply pairset_ex, -- meta dsimp, refl, dsimp, refl }, { -- a ⊢ ∃ A ∀x (x ∈ A ↔ x = a) apply exI #0, -- put `A := {a,a}` apply allI, -- given x apply andI, { -- a {a,a} x ⊢ x ∈ {a,a} → x = a apply impI, -- assume `x ∈ {a,a}` apply orE (#0 =' #3) (#0 =' #3), -- suffices to show (x = a) ∨ (x = a) { -- a {a,a} x ⊢ x = a ∨ x = a apply impE_insert, apply iffE_r, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], left, refl }, { -- assume `x = a` -- a {a,a} x⊢ x = a apply hypI1 }, { -- assume `x = a` -- a {a,a} x ⊢ x = a apply hypI1 } }, { -- a {a,a} x ⊢ x = a → x ∈ {a,a} apply impI, -- assume `x = a` apply impE ((#0 =' #3) ∨' (#0 =' #3)), { -- a {a,a} ⊢ x=a ∨ x=a apply orI₁, apply hypI1 }, { -- a {a,a} x ⊢ x=a ∨ x=a → x ∈ {a,a} apply iffE_l, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, left, refl } } } end /-- Proof scheme. Provides a formal proof of uniqueness of y satisfying formulas of the form `∀x (x ∈ y ↔ φ)`, provided `y` is not free in `φ`. Informally : {extensionality} ⊢ ∀y₁ ∀y₀ (y₀ = { x | φ } ∧ y₁ = { x | φ } → y₀ = y₁) -/ def extensionality_implies_uniqueness (φ : formula σ) : {extensionality} ⊢ unique_in_var0 ∀'(#0 ∈' #1 ↔' (φ ↑ 1 @ 1)) := begin apply allI, -- y₁ apply allI, -- y₀ apply impI, -- assume `∀ x (x ∈ y₀ ↔ φ(x, y₀)) ∧ ∀ x (x ∈ y₁ ↔ φ(x,y₁))` apply impE (∀' (#0 ∈' #1 ↔' #0 ∈' #2)), { -- y₁ y₀ ⊢ (∀' (#0 ∈' #1 ↔' #0 ∈' #2)) apply allI, -- x apply iffI_trans (φ ↑ 2 @ 1), { -- y₁ y₀ x ⊢ x ∈ y₀ ↔ φ (x, y₀) apply allE_var0, apply andE₁ _ , apply hypI, -- meta argument simp [set.image_insert_eq], simp [subst_var0_for_0_lift_by_1, lift_lift_merge φ 1] }, { -- y₁ y₀ x ⊢ φ (x, y₁) ↔ x ∈ y₁ apply iffI_symm, apply allE_var0, apply andE₂ _ , apply hypI, -- meta argument simp [set.image_insert_eq] } }, { -- y₁ y₀ ⊢ ∀ x (x ∈ y₀ ↔ x ∈ y₁) → y₀ = y₁ apply allE_var0, apply allE' _ #1, apply weak1, apply hypI, -- meta argument simp, simp, }, end /-- QoL version of `extensionality_implies_uniqueness` Informally : `Γ ⊢ ∀y₁ ∀y₀ (ψ(y₀) ∧ ψ(y₁) → y₀ = y₁`, provided `ψ(y) = ∀x (x ∈ y ↔ φ)`, `y` not free in `φ` and `extensionality ∈ Γ`. -/ def extensionality_implies_uniqueness' {Γ} (φ) {ψ} (h: ψ = ∀'(#0 ∈' #1 ↔' (φ ↑ 1 @ 1))) (H: extensionality ∈ Γ) : Γ ⊢ unique_in_var0 ψ := begin subst h, apply weak_singleton extensionality (extensionality_implies_uniqueness φ), exact H, end /-- `n`-closure variant of `extensionality_implies_uniqueness` Informally : `{extensionality} ⊢ ∀xₙ ... ∀x₁ ∀y₁ ∀y₀ (y₀ = { x | φ } ∧ y₁ = { x | φ } → y₀ = y₁)` -/ def extensionality_implies_uniqueness_alls (n) (φ : formula σ) : {extensionality} ⊢ alls n (unique_in_var0 ∀'(#0 ∈' #1 ↔' (φ ↑ 1 @ 1))) := begin apply allsI, apply extensionality_implies_uniqueness' φ (rfl), rw set.mem_image, use extensionality, exact ⟨ set.mem_singleton _ , rfl ⟩, end /-- Formal proof that for all sets `b,a` the pair set `{a,b}` exists and is unique. Informally: `zfc_ax ⊢ ∀b ∀a ∃!A (∀x (x ∈ A ↔ x = a ∨ x = b))` -/ def pairset_unique_ex : zfc_ax ⊢ (∀' ∀' ∃! ∀' ((#0 ∈' #1) ↔' (#0 =' #2) ∨' (#0 =' #3))) := begin apply allI, -- b apply allI, -- a simp only [lift_zfc_ax], apply andI, { -- b a ⊢ ∃A (∀x (x ∈ A ↔ x = a ∨ x = b)) apply allE' _ #0, apply allE' _ #1, exact pairset_ex, simp, simp }, { apply extensionality_implies_uniqueness' (#0 =' #1 ∨' #0 =' #2) (rfl), simp[-extensionality, zfc_ax] }, end /-- Formal proof that there exists an unique empty_def set. Informally: `zfc_ax ⊢ ∃! A (∀x (x ∈ A ↔ ¬(x=x))) ` -/ def emptyset_unique_ex : zfc_ax ⊢ ∃! (#0 is_empty) := begin apply andI, { exact emptyset_ex, }, { apply extensionality_implies_uniqueness' (¬'(#0 =' #0)) (rfl), simp[-extensionality, zfc_ax] }, end /-- Formal proof that for all sets `a` the singleton `{a}` exists and is unique. Informally: `zfc_ax ⊢ ∀a ∃!A (A = {a}) ` -/ def singleton_unique_ex : zfc_ax ⊢ ∀' ∃! ∀' (#0 ∈' #1 ↔' #0 =' #3) := begin apply allsI 1, apply andI, { apply allsE' 1, exact singleton_ex, }, { apply extensionality_implies_uniqueness' (#0 =' #2) (rfl), simp only [lift_zfc_ax], simp[-extensionality, zfc_ax] }, end /-- Proof scheme. Provides a formal proof of `∃B ∀x(x ∈ B ↔ φ)` from `∃B ∀x (φ → x ∈ B)` by using the axiom of separation for `φ`. -/ def separation_proof_scheme (φ k) (φ_h₁: closed (k+2) φ) -- given a formula φ(x_1,...,x_{k+1}) (φ_h₂ : not_free 1 φ) -- such that the x₂ is not among its free variables {Γ} (h : separation_ax φ φ_h₁ ∈ Γ) -- ... (H : Γ ⊢ alls k ∃' ∀'(φ →' (#0 ∈' #1))) : Γ ⊢ alls k (∃' ∀'((#0 ∈' #1) ↔' φ)) := begin apply allsI, apply exE ∀'(φ →' (#0 ∈' #1)), -- A with ∀ x (φ → x ∈ A) { -- xₖ ... x₁ ⊢ ∃ A ∀x (φ → x ∈ A) apply allsE', exact H }, { -- xₖ ... x₁ A ⊢ ∃ B ∀ x (x ∈ B ↔ φ) apply exE (∀'((#0 ∈' #1) ↔' ((#0 ∈' #2) ∧' (φ ↑ 1 @ 1)))), -- B with ∀ x (x ∈ B ↔ x ∈ A ∧ φ) { -- xₖ ... x₁ A ⊢ ∃ B ∀ x (x ∈ B ↔ x ∈ A ∧ φ) apply weak1, apply allsE' 1, apply allsE' k, rw [alls,alls], apply hypI, -- meta apply separation.mem φ k φ_h₁ (rfl), assumption, }, { -- A B ⊢ ∃ B ∀ x (x ∈ B ↔ φ) apply exI #0, apply allI, -- x apply andI, { -- A B x ⊢ x ∈ B → φ apply impI, -- assume `x ∈ B` apply andE₂ (#0 ∈' #2), apply impE_insert, apply iffE_r, apply allE_var0, apply hypI, -- meta rw[set.image_insert_eq], left, cases φ_h₂ with ψ ψ_h, subst ψ_h, rw [subst_var0_lift_by_1, subst_var0_lift_by_1], rw [←lift_lift ψ _ _ (le_refl 1)], refl }, { -- A B x ⊢ φ → x ∈ B apply impI, -- assume `φ` apply impE (#0 ∈' #2), { -- A B x ⊢ x ∈ A apply impE (φ ↑ 1 @ 1), { -- A B x ⊢ φ apply hypI, left, cases φ_h₂ with ψ ψ_h, subst ψ_h, rw [subst_var0_lift_by_1, ←lift_lift ψ _ _ (le_rfl)] }, { -- A B x ⊢ φ → x ∈ A apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl } }, { -- A B x ⊢ x ∈ A → x ∈ B apply impI, -- assume `x ∈ A` apply impE (#0 ∈' #2 ∧' (φ ↑ 1 @ 1)), { -- A B x ⊢ x ∈ A ∧ φ apply andI, { -- A B x ⊢ x ∈ A apply hypI1 }, { -- A B x ⊢ φ apply hypI, -- meta right, left, cases φ_h₂ with ψ ψ_h, subst ψ_h, rw [subst_var0_lift_by_1, lift_lift ψ _ _ (le_rfl)] } }, { -- A B x ⊢ x ∈ A ∧ φ → x ∈ B apply iffE_l, apply allE_var0, apply hypI, --meta simp only [set.image_insert_eq], right, right, left, simp } } } } } end /-- QoL version of `separation_proof_scheme`. Proof scheme. Provides a formal proof `ψ` from `∃B ∀x (φ → x ∈ B)` and `ψ = ∃B ∀x(x ∈ B ↔ φ)`. -/ def separation_proof_scheme' (φ) (k) (φ_h: closed (k+2) (φ ↑ 1 @ 1)) {ψ : formula σ} (ψ_h : ψ = alls k ∃' ∀'((#0 ∈' #1) ↔' (φ ↑ 1 @ 1))) {Γ} (h : separation.formula (φ ↑ 1 @ 1) φ_h ∈ Γ) (H: Γ ⊢ alls k ∃' ∀'(φ ↑ 1 @ 1 →' (#0 ∈' #1))) : Γ ⊢ ψ := begin subst ψ_h, apply separation_proof_scheme (φ ↑ 1 @ 1) k φ_h (by use φ) h H, end /-- Formal proof that for all sets `F` there exists a set containing exactly the elements of its elements. Informally : `zfc_ax ⊢ ∀F ∃A ∀x (x ∈ A ↔ ∃y (x ∈ y ∧ y ∈ F))` -/ def unionset_ex : zfc_ax ⊢ ∀' ∃' ∀' ((#0 ∈' #1) ↔' ∃'(#1 ∈' #0 ∧' #0 ∈' #3)):= begin apply separation_proof_scheme' (∃'(#1 ∈' #0 ∧' #0 ∈' #2)) 1, -- enough to show one direction, { refl, }, { apply separation.mem_zfc_ax, }, -- which is an axiom { apply hypI, apply union_ax_mem_zfc_ax }, { dsimp, refl, }, end /-- Formal proof that for all sets `F` the union `⋃F` exists and is unique. Informally : `zfc_ax ⊢ ∀F ∃!A (A = ⋃F)` -/ def unionset_unique_ex : zfc_ax ⊢ ∀' ∃! ∀' ((#0 ∈' #1) ↔' ∃'(#1 ∈' #0 ∧' #0 ∈' #3)) := begin apply allI, simp only [lift_zfc_ax], apply andI, { apply allE' _ #0, exact unionset_ex, simp, }, { apply extensionality_implies_uniqueness' (∃'(#1 ∈' #0 ∧' #0 ∈' #2)) (rfl), simp[-extensionality, zfc_ax] }, end /-- Formal proof that for all sets `y` there exists a set containing exactly all its subsets exists. Informally : `zfc_ax ⊢ ∀y ∃!A ∀x (x ∈ A ↔ x ⊆ y)` -/ def powerset_ex: zfc_ax ⊢ ∀' ∃' ∀' ((#0 ∈' #1) ↔' (#0 ⊆' #2)) := begin apply separation_proof_scheme' (#0 ⊆' #1) 1, -- enough to show oen direction { refl }, { apply separation.mem_zfc_ax, }, -- which is an axiom { apply hypI, apply power_ax_mem_zfc_ax, }, { dsimp, refl, }, end /-- Formal proof that for all sets `y` the powerset `𝒫y` exists and is unique. Informally : `zfc_ax ⊢ ∀y ∃!A (A = 𝒫y)` -/ def powerset_unique_ex : zfc_ax ⊢ ∀' ∃! ∀' ((#0 ∈' #1) ↔' (#0 ⊆' #2)) := begin apply allI, simp only [lift_zfc_ax], apply andI, { apply allE_var0, exact powerset_ex, }, { apply extensionality_implies_uniqueness' (#0 ⊆' #1) (rfl), simp[-extensionality, zfc_ax] }, end /-- Formal proof that for all sets `b, a` there exists a set containing exactly the elements of `a` and `b`. Informally: `zfc_ax ⊢ ∀b ∀a ∃A ∀ x (x ∈ A ↔ x ∈ a ∨ x ∈ b)` -/ def binary_union_ex : zfc_ax ⊢ ∀' ∀' ∃' ∀' (#0 ∈' #1 ↔' #0 ∈' #2 ∨' #0 ∈' #3) := begin apply separation_proof_scheme' (#0 ∈' #1 ∨' #0 ∈' #2) 2, -- only need to show one direction { refl, }, { apply separation.mem_zfc_ax, }, { apply allI, -- b apply allI, -- a apply exE ∀'((#0 ∈' #1) ↔' (#0 =' #2) ∨' (#0 =' #3)), { -- b a ⊢ ∃B (B = {a,b}) apply allE' _ #0, apply allE' _ #1, simp only [lift_zfc_ax], exact pairset_ex, simp, simp }, { -- b a {a,b} ⊢ ∃A ∀x (x ∈ a ∨ x ∈ b → x ∈ A) apply exE ∀'((#0 ∈' #1) ↔' ∃'(#1 ∈' #0 ∧' #0 ∈' #3)), { -- b a {a,b} ⊢ ∃B (B = ⋃{a,b}) apply allE' _ #0, simp only [lift_zfc_ax], apply weak1, exact unionset_ex, simp }, { -- b a {a,b} ⋃{a,b} ⊢ ∃A ∀x (x ∈ a ∨ x ∈ b → x ∈ A) apply exI #0, -- let `A := ⋃{a,b}` apply allI, -- x apply impI, -- assume `x ∈ a ∨ x ∈ b` apply orE (#0 ∈' #3) (#0 ∈' #4), { apply hypI1 }, { -- assume `x ∈ a` -- b a {a,b} ⋃{a,b} ⊢ x ∈ ⋃{a,b} apply impE (∃'(#1 ∈' #0 ∧' #0 ∈' #3)), { -- b a {a,b} ⋃{a,b} ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) apply exI #3, -- put `y:= a` apply andI, { apply hypI1, }, { -- b a {a,b} ⋃{a,b} ⊢ a ∈ {a,b} apply impE (#3 =' #3 ∨' #3 =' #4), { -- b a {a,b} ⋃{a,b} y ⊢ a = a ∨ a = b apply orI₁, apply eqI, }, { -- b a {a,b} ⋃{a,b} ⊢ a = a ∨ a = b → a ∈ {a,b} apply iffE_l, apply allE' _ #3, apply hypI, -- meta simp only [set.image_insert_eq], right, right, right, left, refl, simp } } }, { -- b a {a,b} ⋃{a,b} y ⊢ ∃(x ∈ y ∧ y ∈ {a,b}) → x ∈ ⋃{a,b} apply iffE_l, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl } }, { -- assume `x ∈ b` -- b a {a,b} ⋃{a,b} ⊢ x ∈ ⋃{a,b} apply impE (∃'(#1 ∈' #0 ∧' #0 ∈' #3)), { -- -- b a {a,b} ⋃{a,b} ⊢ ∃y (x ∈ y ∧ y ∈ {a,b}) apply exI #4, -- put `y:=b` apply andI, { apply hypI1, }, { -- b a {a,b} ⋃{a,b} ⊢ b ∈ {a,b} apply impE (#4 =' #3 ∨' #4 =' #4), { -- b a {a,b} ⋃{a,b} y ⊢ b = a ∨ b = b apply orI₂, apply eqI, }, { -- b a {a,b} ⋃{a,b} ⊢ b = a ∨ b = b → b ∈ {a,b} apply iffE_l, apply allE' _ #4, apply hypI, -- meta simp only [set.image_insert_eq], right, right, right, left, refl, simp } } }, { -- b a {a,b} ⋃{a,b} y ⊢ ∃(x ∈ y ∧ y ∈ {a,b}) → x ∈ ⋃{a,b} apply iffE_l, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl } } } } }, { dsimp, refl, }, end /-- Formal proof that for all sets `b, a` the binary union `a ∪ b` exists and is unique. Informally: `zfc_ax ⊢ ∀b ∀a ∃!A (A = a ∪ b)` -/ def binary_union_unique_ex : zfc_ax ⊢ ∀' ∀' ∃! ∀' (#0 ∈' #1 ↔' #0 ∈' #2 ∨' #0 ∈' #3) := begin apply allsI 2, apply andI, { apply allsE' 2, exact binary_union_ex,}, { apply extensionality_implies_uniqueness' (#0 ∈' #1 ∨' #0 ∈' #2) (rfl), simp only [lift_zfc_ax], simp[-extensionality, zfc_ax] } end /-- Formal proof that for all sets `a` there exists a successor set containing exactly `a` and the elements of `a` . Informally: `zfc_ax ⊢ ∀a ∃A ∀x (x ∈ A ↔ x ∈ a ∨ x = a)` -/ def successor_ex : zfc_ax ⊢ ∀' ∃' (#0 is_successor_of #1) := begin apply separation_proof_scheme' (#0 ∈' #1 ∨' (#0 =' #1)) 1, -- only need to show one direction { refl, }, { apply separation.mem_zfc_ax, }, { apply allI, -- a apply exE ∀' (#0 ∈' #1 ↔' #0 =' #2), { -- a ⊢ ∃ A (A = {a}) apply allE' _ #0, simp only [lift_zfc_ax], exact singleton_ex, dsimp, refl, }, { -- a {a} ⊢ ∃ S ∀ x (x ∈ a ∨ x = {a} → x ∈ S) apply exE ∀'(#0 ∈' #1 ↔' #0 ∈' #3 ∨' #0 ∈' #2), { -- a {a} ⊢ ∃ B (B = a ∪ {a}) apply allE' _ #1, apply allE' _ #0, simp only [lift_zfc_ax], apply weak1, exact binary_union_ex, simp, dsimp, refl }, { -- a {a} (a ∪ {a}) ⊢ ∃ S ∀ x (x ∈ a ∨ x = {a} → x ∈ S) apply exI #0, -- put `S = a ∪ {a}` apply allI, -- x apply impI, -- assume `x ∈ a ∨ x = a` apply orE (#0 ∈' #3) (#0 =' #3), { apply hypI1, }, { -- case `x ∈ a` -- a {a} (a ∪ {a}) x ⊢ x ∈ a ∪ {a} apply impE (#0 ∈' #3 ∨' #0 ∈' #2), { -- a {a} (a ∪ {a}) x ⊢ x ∈ a ∨ x ∈ {a} apply orI₁, apply hypI1 }, { -- a {a} (a ∪ {a}) x ⊢ x ∈ a ∨ x ∈ {a} → x ∈ a ∪ {a} apply iffE_l, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl } }, { -- case `x = a` -- a {a} (a ∪ {a}) x ⊢ x ∈ a ∪ {a} apply impE (#0 ∈' #3 ∨' #0 ∈' #2), { -- a {a} (a ∪ {a}) x ⊢ x ∈ a ∨ x ∈ {a} apply orI₂, apply impE_insert, apply iffE_l, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl }, { -- a {a} (a ∪ {a}) x ⊢ x ∈ a ∨ x ∈ {a} → x ∈ a ∪ {a} apply iffE_l, apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, refl } } } } }, { dsimp, refl, }, end /-- Formal proof that for all sets `a` the successor set `S(a)` exists and is unique. Informally: `zfc_ax ⊢ ∀a ∃!A (A = S(a))` -/ def successor_unique_ex : zfc_ax ⊢ ∀' ∃! (#0 is_successor_of #1) := begin apply allsI 1, apply andI, { apply allsE' 1, exact successor_ex, }, { apply extensionality_implies_uniqueness' (#0 ∈' #1 ∨' (#0 =' #1)) (rfl), simp only [lift_zfc_ax], simp[-extensionality, zfc_ax] }, end /-- Formal proof that there exists a set containing exactly the elements common to all inductive sets. -/ def omega_ex : zfc_ax ⊢ ∃' (#0 is_omega) := begin apply separation_proof_scheme' (∀' (#0 is_inductive →' #1 ∈' #0)) 0, -- enough to show one direction { refl, }, { apply separation.mem_zfc_ax, }, { apply exE (#0 is_inductive), { -- ⊢ ∃A (A is inductive) apply hypI, exact infinity_ax_mem_zfc_ax }, -- this exists because of the axiom of infinity { -- A ⊢ ∃ω ∀x (∀w (w is inductive → w ∈ ω)) → x ∈ ω) apply exE ∀'(#0 ∈' #1 ↔' #0 ∈' #2 ∧' ∀' (#0 is_inductive →' #1 ∈' #0)), { -- A ⊢ ∃B ∀x (x ∈ B ↔ (x ∈ A) ∧ ∀w (w is inductive → x ∈ w) apply allE_var0, apply hypI, -- meta simp only [lift_zfc_ax], right, apply separation.mem_zfc_ax (∀'(#0 is_inductive →' #1 ∈' #0)) 0, dsimp, refl }, { -- B with `∀x (x ∈ B ↔ ((x ∈ A) ∧ ∀w (w is inductive → x ∈ w)))` -- A B ⊢ ∃ω ∀x (∀w (w is inductive → x ∈ ω)) → x ∈ ω) apply exI #0, -- let `ω := B` apply allI, apply impI, -- assume `x` with `(∀w (w is inductive → x ∈ ω))` apply iffE₁ (#0 ∈' #2 ∧' ∀' (#0 is_inductive →' #1 ∈' #0)), { -- A B x ⊢ (x ∈ A ∧ ∀w(w is inductive → x ∈ w) apply andI, { -- A B x ⊢ x ∈ A apply impE (#2 is_inductive), { -- A B x ⊢ A is inductive apply hypI, -- meta simp only [set.image_insert_eq], right, right, left, simp[inductive_def, empty_def, successor_def] }, { -- A B x ⊢ A is inductive → x ∈ A apply allE' _ #2, apply hypI, -- meta left, refl, dsimp, refl } }, { -- A B x ⊢ ∀w(w is inductive → x ∈ w) apply hypI1, } }, { -- A B x ⊢ x ∈ B ↔ (x ∈ A ∧ ∀w(w is inductive → x ∈ w)) apply allE_var0, apply hypI, -- meta simp only [set.image_insert_eq], right, left, refl } } } }, { -- meta dsimp, refl } end /-- Formal proof that `ω` exists and is unique. Informally: `zfc_ax ⊢ ∃!A (A = ω)` -/ def omega_unique_ex : zfc_ax ⊢ ∃! (#0 is_omega) := begin apply andI, { exact omega_ex, }, { apply extensionality_implies_uniqueness' (∀' (#0 is_inductive →' #1 ∈' #0)) (rfl), simp[-extensionality, zfc_ax] }, end /-- A formal proof that `ω` is a subset of all inductive sets. Informally : `zfc_ax ⊢ ∀ A (A = ω → ∀ w (w is inductive → A ⊆ w))` -/ def omega_subset_all_inductive : zfc_ax ⊢ ∀' ((#0 is_omega) →' ∀' (#0 is_inductive →' #1 ⊆' #0)) := begin apply allI, apply impI, apply allI, apply impI, apply allI, apply impI, apply impE (#1 is_inductive), { apply hypI, simp only [set.image_insert_eq], right, left, refl }, { apply allE' _ #1, apply iffE₂ (#0 ∈' #2), { apply hypI1, }, { apply allE_var0, apply hypI, simp only [set.image_insert_eq], right, right, left, refl }, { dsimp, refl, } }, end /-- A formal proof that `ω` is inductive. Informally : `zfc_ax ⊢ ∀ A (A = ω → A is inductive)` -/ def omega_inductive : zfc_ax ⊢ ∀' ((#0 is_omega) →' (#0 is_inductive)) := begin apply allI, -- ω apply impI, -- assume `ω = { x | ∀ w (w is inductive → x ∈ w) }` apply andI, { -- ω ⊢ ∀ x (x is empty_def → x ∈ ω) apply allI, -- ∅ apply impI, -- assume `∅ is empty_def` apply iffE₁ ∀'(#0 is_inductive →' #1 ∈' #0), { -- ω ∅ ⊢ ∀ w (w is inductive → ∅ ∈ w) apply allI, -- w apply impI, -- assume `w is inductive` apply impE (#1 is_empty), { -- ω ∅ w ⊢ ∅ is empty_def apply hypI, simp only [set.image_insert_eq], right, left, refl, }, { -- ω ∅ w ⊢ ∅ is empty_def → ∅ ∈ w apply allE' _ #1, apply andE₁, apply hypI1, unfold empty_def, refl } }, { -- ω ∅ ⊢ ∅ ∈ ω ↔ ∀ w (w is inductive → ∅ ∈ w) apply allE_var0, apply hypI, simp only[set.image_insert_eq], right, left, refl } }, { -- ω ⊢ ∀ (x ∈ ω → (∀ y (y = S(x) → y ∈ ω)) apply allI, -- x apply impI, -- assume `x ∈ ω` apply allI, -- y apply impI, -- assume `y=S(x)` apply impE ∀'(#0 is_inductive →' #1 ∈' #0), { -- ω x y ⊢ ∀w (w is inductive → y ∈ w) apply allI, -- w apply impI, -- assume `w is inductive` apply impE (#2 ∈' #0), { -- ω x y w ⊢ x ∈ w apply impE (#2 ∈' #3), { -- ω x y ⊢ x ∈ ω apply hypI, simp only [set.image_insert_eq], right, right, left, refl }, { -- ω x y w ⊢ x ∈ ω → x ∈ w apply allE' (#0 ∈' #4 →' #0 ∈' #1) #2, apply impE (#0 is_inductive), { -- ω x y w ⊢ w is inductive apply hypI1 }, { -- ω x y w ⊢ (w is inductive) → ω ⊆ w apply allE_var0, apply impE (∀' (#0 ∈' #4 ↔' ∀' (#0 is_inductive →' #1 ∈' #0))), { -- ω x y w ⊢ ω = ω = { x | ∀ w (w is inductive → x ∈ w) } apply hypI, simp only [set.image_insert_eq], right, right, right, left, refl }, { -- ω x y w ⊢ ω = ω = { x | ∀ w (w is inductive → x ∈ w) } → ((w is inductive) → ω ⊆ w) apply allE' _ #3, apply weak zfc_ax, exact omega_subset_all_inductive, simp only [set.image_insert_eq, lift_zfc_ax], assume y yh, simp[yh], unfold inductive_def, refl, } }, refl }, }, { -- ω x y w ⊢ x ∈ w → y ∈ w apply impI, -- assume `x ∈ w` apply impE (#1 is_successor_of #2), { -- ω x y w ⊢ y = S(x) apply hypI, simp only [set.image_insert_eq], right, right, left, unfold successor_def, refl }, { -- ω x y w ⊢ y = S(x) → y ∈ w apply allE' _ #1, apply impE (#2 ∈' #0), { -- ω x y w ⊢ x ∈ w apply hypI1, }, { -- ω x y w ⊢ x ∈ w → (∀ y (y = S(x) → y ∈ w)) apply allE' _ #2, apply andE₂, apply hypI, simp only[set.image_insert_eq], right, left, refl, unfold successor_def, refl }, { unfold successor_def, refl } } } }, { -- ω x y ⊢ ∀w (w is inductive → y ∈ w) → y ∈ ω apply iffE_l, apply allE_var0, apply hypI, simp only [set.image_insert_eq], right, right, left, refl } }, end /-- A formal proof that `ω` is the smallest inductive set. Informally : `zfc_ax ⊢ ∀ X (A = ω → (A is inductive ∧ ∀ w (w is inductive → X ⊆ w))` -/ def omega_smallest_inductive : zfc_ax ⊢ ∃!(#0 is_omega) ∧' ∀'((#0 is_omega) →' (#0 is_inductive ∧' ∀'(#0 is_inductive →' #1 ⊆' #0))) := begin apply andI, { exact omega_unique_ex, }, { apply allI, -- ω apply impI, -- ω = { x | ∀ w (w is inductive → x ∈ w) } apply andI, { -- ω ⊢ ω is inductive apply impE_insert, apply allE_var0, simp only [lift_zfc_ax], apply omega_inductive }, { -- ω ⊢ ∀ w (w is inductive → ω ⊆ w) apply impE_insert, apply allE_var0, simp only [lift_zfc_ax], apply omega_subset_all_inductive } } end end zfc_proofs /-- Main Theorem: ZFC proves that `ω` is the smallest inductive set. -/ theorem omega_smallest_inductive_provable_within_zfc : (∃!(#0 is_omega) ∧' ∀'((#0 is_omega) →' (#0 is_inductive ∧' ∀'(#0 is_inductive →' #1 ⊆' #0)))) is_provable_within zfc_ax := begin use omega_smallest_inductive, end end zfc
72dbea1539f44b3815db797ba0e27c0e43ead2b9
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/aggregateProjectMerge.lean
bca36dd1c54a5d9e58742c4560ce297313c7acb0
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,712
lean
import ..extra_constants import ..sql import ..u_semiring import ..tactics import ..cosette_tactics open SQL open Proj open Pred open Expr theorem rule : forall (Γ scm_emp : Schema) (rel_emp : relation scm_emp) (emp_empno : Column datatypes.int scm_emp) (emp_ename : Column datatypes.int scm_emp) (emp_job : Column datatypes.int scm_emp) (emp_mgr : Column datatypes.int scm_emp) (emp_hiredate : Column datatypes.int scm_emp) (emp_comm : Column datatypes.int scm_emp) (emp_sal : Column datatypes.int scm_emp) (emp_deptno : Column datatypes.int scm_emp) (emp_slacker : Column datatypes.int scm_emp), let deptnoProj : Proj (Γ ++ scm_emp) _ := right⋅emp_deptno, salProj : Proj (Γ ++ scm_emp) _ := right⋅emp_sal, empnoProj : Proj (Γ ++ scm_emp) _ := right⋅emp_empno in denoteSQL (SELECT (combineGroupByProj PLAIN(uvariable deptnoProj) (combineGroupByProj SUM(uvariable salProj) PLAIN(uvariable empnoProj))) FROM1 table rel_emp GROUP BY combine deptnoProj empnoProj : SQL Γ _) = denoteSQL (SELECT (combineGroupByProj PLAIN(uvariable deptnoProj) (combineGroupByProj SUM(uvariable salProj) PLAIN(uvariable empnoProj))) FROM1 table rel_emp GROUP BY combine empnoProj deptnoProj : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, sorry, end
d5a04ced9b62f1905d90ebd9e1893023b8cf7075
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/group/prod.lean
c2ad58d818513a1d45feea9cf5a01b4d7f90f462
[ "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
22,194
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.constructions.prod import measure_theory.group.measure /-! # Measure theory in the product of groups In this file we show properties about measure theory in products of measurable groups and properties of iterated integrals in measurable groups. These lemmas show the uniqueness of left invariant measures on measurable groups, up to scaling. In this file we follow the proof and refer to the book *Measure Theory* by Paul Halmos. The idea of the proof is to use the translation invariance of measures to prove `μ(t) = c * μ(s)` for two sets `s` and `t`, where `c` is a constant that does not depend on `μ`. Let `e` and `f` be the characteristic functions of `s` and `t`. Assume that `μ` and `ν` are left-invariant measures. Then the map `(x, y) ↦ (y * x, x⁻¹)` preserves the measure `μ × ν`, which means that ``` ∫ x, ∫ y, h x y ∂ν ∂μ = ∫ x, ∫ y, h (y * x) x⁻¹ ∂ν ∂μ ``` If we apply this to `h x y := e x * f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' s)`, we can rewrite the RHS to `μ(t)`, and the LHS to `c * μ(s)`, where `c = c(ν)` does not depend on `μ`. Applying this to `μ` and to `ν` gives `μ (t) / μ (s) = ν (t) / ν (s)`, which is the uniqueness up to scalar multiplication. The proof in [Halmos] seems to contain an omission in §60 Th. A, see `measure_theory.measure_lintegral_div_measure`. -/ noncomputable theory open set (hiding prod_eq) function measure_theory filter (hiding map) open_locale classical ennreal pointwise measure_theory variables (G : Type*) [measurable_space G] variables [group G] [has_measurable_mul₂ G] variables (μ ν : measure G) [sigma_finite ν] [sigma_finite μ] {s : set G} /-- The map `(x, y) ↦ (x, xy)` as a `measurable_equiv`. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a `measurable_equiv`."] protected def measurable_equiv.shear_mul_right [has_measurable_inv G] : G × G ≃ᵐ G × G := { measurable_to_fun := measurable_fst.prod_mk measurable_mul, measurable_inv_fun := measurable_fst.prod_mk $ measurable_fst.inv.mul measurable_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } /-- The map `(x, y) ↦ (x, y / x)` as a `measurable_equiv` with as inverse `(x, y) ↦ (x, yx)` -/ @[to_additive "The map `(x, y) ↦ (x, y - x)` as a `measurable_equiv` with as inverse `(x, y) ↦ (x, y + x)`."] protected def measurable_equiv.shear_div_right [has_measurable_inv G] : G × G ≃ᵐ G × G := { measurable_to_fun := measurable_fst.prod_mk $ measurable_snd.div measurable_fst, measurable_inv_fun := measurable_fst.prod_mk $ measurable_snd.mul measurable_fst, .. equiv.prod_shear (equiv.refl _) (equiv.div_right) } variables {G} namespace measure_theory open measure section left_invariant /-- The multiplicative shear mapping `(x, y) ↦ (x, xy)` preserves the measure `μ × ν`. This condition is part of the definition of a measurable group in [Halmos, §59]. There, the map in this lemma is called `S`. -/ @[to_additive measure_preserving_prod_add /-" The shear mapping `(x, y) ↦ (x, x + y)` preserves the measure `μ × ν`. "-/] lemma measure_preserving_prod_mul [is_mul_left_invariant ν] : measure_preserving (λ z : G × G, (z.1, z.1 * z.2)) (μ.prod ν) (μ.prod ν) := (measure_preserving.id μ).skew_product measurable_mul $ filter.eventually_of_forall $ map_mul_left_eq_self ν /-- The map `(x, y) ↦ (y, yx)` sends the measure `μ × ν` to `ν × μ`. This is the map `SR` in [Halmos, §59]. `S` is the map `(x, y) ↦ (x, xy)` and `R` is `prod.swap`. -/ @[to_additive measure_preserving_prod_add_swap /-" The map `(x, y) ↦ (y, y + x)` sends the measure `μ × ν` to `ν × μ`. "-/] lemma measure_preserving_prod_mul_swap [is_mul_left_invariant μ] : measure_preserving (λ z : G × G, (z.2, z.2 * z.1)) (μ.prod ν) (ν.prod μ) := (measure_preserving_prod_mul ν μ).comp measure_preserving_swap @[to_additive] lemma measurable_measure_mul_right (hs : measurable_set s) : measurable (λ x, μ ((λ y, y * x) ⁻¹' s)) := begin suffices : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' ((λ z : G × G, ((1 : G), z.1 * z.2)) ⁻¹' (univ ×ˢ s)))), { convert this, ext1 x, congr' 1 with y : 1, simp }, apply measurable_measure_prod_mk_right, exact measurable_const.prod_mk measurable_mul (measurable_set.univ.prod hs) end variables [has_measurable_inv G] /-- The map `(x, y) ↦ (x, x⁻¹y)` is measure-preserving. This is the function `S⁻¹` in [Halmos, §59], where `S` is the map `(x, y) ↦ (x, xy)`. -/ @[to_additive measure_preserving_prod_neg_add "The map `(x, y) ↦ (x, - x + y)` is measure-preserving."] lemma measure_preserving_prod_inv_mul [is_mul_left_invariant ν] : measure_preserving (λ z : G × G, (z.1, z.1⁻¹ * z.2)) (μ.prod ν) (μ.prod ν) := (measure_preserving_prod_mul μ ν).symm $ measurable_equiv.shear_mul_right G variables [is_mul_left_invariant μ] /-- The map `(x, y) ↦ (y, y⁻¹x)` sends `μ × ν` to `ν × μ`. This is the function `S⁻¹R` in [Halmos, §59], where `S` is the map `(x, y) ↦ (x, xy)` and `R` is `prod.swap`. -/ @[to_additive measure_preserving_prod_neg_add_swap "The map `(x, y) ↦ (y, - y + x)` sends `μ × ν` to `ν × μ`."] lemma measure_preserving_prod_inv_mul_swap : measure_preserving (λ z : G × G, (z.2, z.2⁻¹ * z.1)) (μ.prod ν) (ν.prod μ) := (measure_preserving_prod_inv_mul ν μ).comp measure_preserving_swap /-- The map `(x, y) ↦ (yx, x⁻¹)` is measure-preserving. This is the function `S⁻¹RSR` in [Halmos, §59], where `S` is the map `(x, y) ↦ (x, xy)` and `R` is `prod.swap`. -/ @[to_additive measure_preserving_add_prod_neg "The map `(x, y) ↦ (y + x, - x)` is measure-preserving."] lemma measure_preserving_mul_prod_inv [is_mul_left_invariant ν] : measure_preserving (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod ν) (μ.prod ν) := begin convert (measure_preserving_prod_inv_mul_swap ν μ).comp (measure_preserving_prod_mul_swap μ ν), ext1 ⟨x, y⟩, simp_rw [function.comp_apply, mul_inv_rev, inv_mul_cancel_right] end @[to_additive] lemma quasi_measure_preserving_inv : quasi_measure_preserving (has_inv.inv : G → G) μ μ := begin refine ⟨measurable_inv, absolutely_continuous.mk $ λ s hsm hμs, _⟩, rw [map_apply measurable_inv hsm, inv_preimage], have hf : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, suffices : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod μ) (s⁻¹ ×ˢ s⁻¹) = 0, { simpa only [(measure_preserving_mul_prod_inv μ μ).map_eq, prod_prod, mul_eq_zero, or_self] using this }, have hsm' : measurable_set (s⁻¹ ×ˢ s⁻¹) := hsm.inv.prod hsm.inv, simp_rw [map_apply hf hsm', prod_apply_symm (hf hsm'), preimage_preimage, mk_preimage_prod, inv_preimage, inv_inv, measure_mono_null (inter_subset_right _ _) hμs, lintegral_zero] end @[to_additive] lemma measure_inv_null : μ s⁻¹ = 0 ↔ μ s = 0 := begin refine ⟨λ hs, _, (quasi_measure_preserving_inv μ).preimage_null⟩, rw [← inv_inv s], exact (quasi_measure_preserving_inv μ).preimage_null hs end @[to_additive] lemma inv_absolutely_continuous : μ.inv ≪ μ := (quasi_measure_preserving_inv μ).absolutely_continuous @[to_additive] lemma absolutely_continuous_inv : μ ≪ μ.inv := begin refine absolutely_continuous.mk (λ s hs, _), simp_rw [inv_apply μ s, measure_inv_null, imp_self] end @[to_additive] lemma lintegral_lintegral_mul_inv [is_mul_left_invariant ν] (f : G → G → ℝ≥0∞) (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f (y * x) x⁻¹ ∂ν ∂μ = ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ := begin have h : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, have h2f : ae_measurable (uncurry $ λ x y, f (y * x) x⁻¹) (μ.prod ν) := hf.comp_quasi_measure_preserving (measure_preserving_mul_prod_inv μ ν).quasi_measure_preserving, simp_rw [lintegral_lintegral h2f, lintegral_lintegral hf], conv_rhs { rw [← (measure_preserving_mul_prod_inv μ ν).map_eq] }, symmetry, exact lintegral_map' (hf.mono' (measure_preserving_mul_prod_inv μ ν).map_eq.absolutely_continuous) h.ae_measurable, end @[to_additive] lemma measure_mul_right_null (y : G) : μ ((λ x, x * y) ⁻¹' s) = 0 ↔ μ s = 0 := calc μ ((λ x, x * y) ⁻¹' s) = 0 ↔ μ ((λ x, y⁻¹ * x) ⁻¹' s⁻¹)⁻¹ = 0 : by simp_rw [← inv_preimage, preimage_preimage, mul_inv_rev, inv_inv] ... ↔ μ s = 0 : by simp only [measure_inv_null μ, measure_preimage_mul] @[to_additive] lemma measure_mul_right_ne_zero (h2s : μ s ≠ 0) (y : G) : μ ((λ x, x * y) ⁻¹' s) ≠ 0 := (not_iff_not_of_iff (measure_mul_right_null μ y)).mpr h2s @[to_additive] lemma absolutely_continuous_map_mul_right (g : G) : μ ≪ map (* g) μ := begin refine absolutely_continuous.mk (λ s hs, _), rw [map_apply (measurable_mul_const g) hs, measure_mul_right_null], exact id end @[to_additive] lemma absolutely_continuous_map_div_left (g : G) : μ ≪ map (λ h, g / h) μ := begin simp_rw [div_eq_mul_inv], rw [← map_map (measurable_const_mul g) measurable_inv], conv_lhs { rw [← map_mul_left_eq_self μ g] }, exact (absolutely_continuous_inv μ).map (measurable_const_mul g) end /-- This is the computation performed in the proof of [Halmos, §60 Th. A]. -/ @[to_additive "This is the computation performed in the proof of [Halmos, §60 Th. A]."] lemma measure_mul_lintegral_eq [is_mul_left_invariant ν] (sm : measurable_set s) (f : G → ℝ≥0∞) (hf : measurable f) : μ s * ∫⁻ y, f y ∂ν = ∫⁻ x, ν ((λ z, z * x) ⁻¹' s) * f (x⁻¹) ∂μ := begin rw [← set_lintegral_one, ← lintegral_indicator _ sm, ← lintegral_lintegral_mul (measurable_const.indicator sm).ae_measurable hf.ae_measurable, ← lintegral_lintegral_mul_inv μ ν], swap, { exact (((measurable_const.indicator sm).comp measurable_fst).mul (hf.comp measurable_snd)).ae_measurable }, have ms : ∀ x : G, measurable (λ y, ((λ z, z * x) ⁻¹' s).indicator (λ z, (1 : ℝ≥0∞)) y) := λ x, measurable_const.indicator (measurable_mul_const _ sm), have : ∀ x y, s.indicator (λ (z : G), (1 : ℝ≥0∞)) (y * x) = ((λ z, z * x) ⁻¹' s).indicator (λ (b : G), 1) y, { intros x y, symmetry, convert indicator_comp_right (λ y, y * x), ext1 z, refl }, simp_rw [this, lintegral_mul_const _ (ms _), lintegral_indicator _ (measurable_mul_const _ sm), set_lintegral_one], end /-- Any two nonzero left-invariant measures are absolutely continuous w.r.t. each other. -/ @[to_additive /-" Any two nonzero left-invariant measures are absolutely continuous w.r.t. each other. "-/] lemma absolutely_continuous_of_is_mul_left_invariant [is_mul_left_invariant ν] (hν : ν ≠ 0) : μ ≪ ν := begin refine absolutely_continuous.mk (λ s sm hνs, _), have h1 := measure_mul_lintegral_eq μ ν sm 1 measurable_one, simp_rw [pi.one_apply, lintegral_one, mul_one, (measure_mul_right_null ν _).mpr hνs, lintegral_zero, mul_eq_zero, measure_univ_eq_zero.not.mpr hν, or_false] at h1, exact h1 end @[to_additive] lemma ae_measure_preimage_mul_right_lt_top [is_mul_left_invariant ν] (sm : measurable_set s) (hμs : μ s ≠ ∞) : ∀ᵐ x ∂μ, ν ((λ y, y * x) ⁻¹' s) < ∞ := begin refine ae_of_forall_measure_lt_top_ae_restrict' ν.inv _ _, intros A hA h2A h3A, simp only [ν.inv_apply] at h3A, apply ae_lt_top (measurable_measure_mul_right ν sm), have h1 := measure_mul_lintegral_eq μ ν sm (A⁻¹.indicator 1) (measurable_one.indicator hA.inv), rw [lintegral_indicator _ hA.inv] at h1, simp_rw [pi.one_apply, set_lintegral_one, ← image_inv, indicator_image inv_injective, image_inv, ← indicator_mul_right _ (λ x, ν ((λ y, y * x) ⁻¹' s)), function.comp, pi.one_apply, mul_one] at h1, rw [← lintegral_indicator _ hA, ← h1], exact ennreal.mul_ne_top hμs h3A.ne, end @[to_additive] lemma ae_measure_preimage_mul_right_lt_top_of_ne_zero [is_mul_left_invariant ν] (sm : measurable_set s) (h2s : ν s ≠ 0) (h3s : ν s ≠ ∞) : ∀ᵐ x ∂μ, ν ((λ y, y * x) ⁻¹' s) < ∞ := begin refine (ae_measure_preimage_mul_right_lt_top ν ν sm h3s).filter_mono _, refine (absolutely_continuous_of_is_mul_left_invariant μ ν _).ae_le, refine mt _ h2s, intro hν, rw [hν, measure.coe_zero, pi.zero_apply] end /-- A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A]. Note that if `f` is the characteristic function of a measurable set `t` this states that `μ t = c * μ s` for a constant `c` that does not depend on `μ`. Note: There is a gap in the last step of the proof in [Halmos]. In the last line, the equality `g(x⁻¹)ν(sx⁻¹) = f(x)` holds if we can prove that `0 < ν(sx⁻¹) < ∞`. The first inequality follows from §59, Th. D, but the second inequality is not justified. We prove this inequality for almost all `x` in `measure_theory.ae_measure_preimage_mul_right_lt_top_of_ne_zero`. -/ @[to_additive "A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A]. Note that if `f` is the characteristic function of a measurable set `t` this states that `μ t = c * μ s` for a constant `c` that does not depend on `μ`. Note: There is a gap in the last step of the proof in [Halmos]. In the last line, the equality `g(-x) + ν(s - x) = f(x)` holds if we can prove that `0 < ν(s - x) < ∞`. The first inequality follows from §59, Th. D, but the second inequality is not justified. We prove this inequality for almost all `x` in `measure_theory.ae_measure_preimage_add_right_lt_top_of_ne_zero`."] lemma measure_lintegral_div_measure [is_mul_left_invariant ν] (sm : measurable_set s) (h2s : ν s ≠ 0) (h3s : ν s ≠ ∞) (f : G → ℝ≥0∞) (hf : measurable f) : μ s * ∫⁻ y, f y⁻¹ / ν ((λ x, x * y⁻¹) ⁻¹' s) ∂ν = ∫⁻ x, f x ∂μ := begin set g := λ y, f y⁻¹ / ν ((λ x, x * y⁻¹) ⁻¹' s), have hg : measurable g := (hf.comp measurable_inv).div ((measurable_measure_mul_right ν sm).comp measurable_inv), simp_rw [measure_mul_lintegral_eq μ ν sm g hg, g, inv_inv], refine lintegral_congr_ae _, refine (ae_measure_preimage_mul_right_lt_top_of_ne_zero μ ν sm h2s h3s).mono (λ x hx , _), simp_rw [ennreal.mul_div_cancel' (measure_mul_right_ne_zero ν h2s _) hx.ne] end @[to_additive] lemma measure_mul_measure_eq [is_mul_left_invariant ν] {s t : set G} (hs : measurable_set s) (ht : measurable_set t) (h2s : ν s ≠ 0) (h3s : ν s ≠ ∞) : μ s * ν t = ν s * μ t := begin have h1 := measure_lintegral_div_measure ν ν hs h2s h3s (t.indicator (λ x, 1)) (measurable_const.indicator ht), have h2 := measure_lintegral_div_measure μ ν hs h2s h3s (t.indicator (λ x, 1)) (measurable_const.indicator ht), rw [lintegral_indicator _ ht, set_lintegral_one] at h1 h2, rw [← h1, mul_left_comm, h2], end /-- Left invariant Borel measures on a measurable group are unique (up to a scalar). -/ @[to_additive /-" Left invariant Borel measures on an additive measurable group are unique (up to a scalar). "-/] lemma measure_eq_div_smul [is_mul_left_invariant ν] (hs : measurable_set s) (h2s : ν s ≠ 0) (h3s : ν s ≠ ∞) : μ = (μ s / ν s) • ν := begin ext1 t ht, rw [smul_apply, smul_eq_mul, mul_comm, ← mul_div_assoc, mul_comm, measure_mul_measure_eq μ ν hs ht h2s h3s, mul_div_assoc, ennreal.mul_div_cancel' h2s h3s] end end left_invariant section right_invariant @[to_additive measure_preserving_prod_add_right] lemma measure_preserving_prod_mul_right [is_mul_right_invariant ν] : measure_preserving (λ z : G × G, (z.1, z.2 * z.1)) (μ.prod ν) (μ.prod ν) := (measure_preserving.id μ).skew_product (by exact measurable_snd.mul measurable_fst) $ filter.eventually_of_forall $ map_mul_right_eq_self ν /-- The map `(x, y) ↦ (y, xy)` sends the measure `μ × ν` to `ν × μ`. -/ @[to_additive measure_preserving_prod_add_swap_right /-" The map `(x, y) ↦ (y, x + y)` sends the measure `μ × ν` to `ν × μ`. "-/] lemma measure_preserving_prod_mul_swap_right [is_mul_right_invariant μ] : measure_preserving (λ z : G × G, (z.2, z.1 * z.2)) (μ.prod ν) (ν.prod μ) := (measure_preserving_prod_mul_right ν μ).comp measure_preserving_swap /-- The map `(x, y) ↦ (xy, y)` preserves the measure `μ × ν`. -/ @[to_additive measure_preserving_add_prod /-" The map `(x, y) ↦ (x + y, y)` preserves the measure `μ × ν`. "-/] lemma measure_preserving_mul_prod [is_mul_right_invariant μ] : measure_preserving (λ z : G × G, (z.1 * z.2, z.2)) (μ.prod ν) (μ.prod ν) := measure_preserving_swap.comp $ by apply measure_preserving_prod_mul_swap_right μ ν variables [has_measurable_inv G] /-- The map `(x, y) ↦ (x, y / x)` is measure-preserving. -/ @[to_additive measure_preserving_prod_sub "The map `(x, y) ↦ (x, y - x)` is measure-preserving."] lemma measure_preserving_prod_div [is_mul_right_invariant ν] : measure_preserving (λ z : G × G, (z.1, z.2 / z.1)) (μ.prod ν) (μ.prod ν) := (measure_preserving_prod_mul_right μ ν).symm (measurable_equiv.shear_div_right G).symm /-- The map `(x, y) ↦ (y, x / y)` sends `μ × ν` to `ν × μ`. -/ @[to_additive measure_preserving_prod_sub_swap "The map `(x, y) ↦ (y, x - y)` sends `μ × ν` to `ν × μ`."] lemma measure_preserving_prod_div_swap [is_mul_right_invariant μ] : measure_preserving (λ z : G × G, (z.2, z.1 / z.2)) (μ.prod ν) (ν.prod μ) := (measure_preserving_prod_div ν μ).comp measure_preserving_swap /-- The map `(x, y) ↦ (x / y, y)` preserves the measure `μ × ν`. -/ @[to_additive measure_preserving_sub_prod /-" The map `(x, y) ↦ (x - y, y)` preserves the measure `μ × ν`. "-/] lemma measure_preserving_div_prod [is_mul_right_invariant μ] : measure_preserving (λ z : G × G, (z.1 / z.2, z.2)) (μ.prod ν) (μ.prod ν) := measure_preserving_swap.comp $ by apply measure_preserving_prod_div_swap μ ν /-- The map `(x, y) ↦ (xy, x⁻¹)` is measure-preserving. -/ @[to_additive measure_preserving_add_prod_neg_right "The map `(x, y) ↦ (x + y, - x)` is measure-preserving."] lemma measure_preserving_mul_prod_inv_right [is_mul_right_invariant μ] [is_mul_right_invariant ν] : measure_preserving (λ z : G × G, (z.1 * z.2, z.1⁻¹)) (μ.prod ν) (μ.prod ν) := begin convert (measure_preserving_prod_div_swap ν μ).comp (measure_preserving_prod_mul_swap_right μ ν), ext1 ⟨x, y⟩, simp_rw [function.comp_apply, div_mul_eq_div_div_swap, div_self', one_div] end end right_invariant section quasi_measure_preserving variables [has_measurable_inv G] @[to_additive] lemma quasi_measure_preserving_inv_of_right_invariant [is_mul_right_invariant μ] : quasi_measure_preserving (has_inv.inv : G → G) μ μ := begin rw [← μ.inv_inv], exact (quasi_measure_preserving_inv μ.inv).mono (inv_absolutely_continuous μ.inv) (absolutely_continuous_inv μ.inv) end @[to_additive] lemma quasi_measure_preserving_div_left [is_mul_left_invariant μ] (g : G) : quasi_measure_preserving (λ h : G, g / h) μ μ := begin simp_rw [div_eq_mul_inv], exact (measure_preserving_mul_left μ g).quasi_measure_preserving.comp (quasi_measure_preserving_inv μ) end @[to_additive] lemma quasi_measure_preserving_div_left_of_right_invariant [is_mul_right_invariant μ] (g : G) : quasi_measure_preserving (λ h : G, g / h) μ μ := begin rw [← μ.inv_inv], exact (quasi_measure_preserving_div_left μ.inv g).mono (inv_absolutely_continuous μ.inv) (absolutely_continuous_inv μ.inv) end @[to_additive] lemma quasi_measure_preserving_div_of_right_invariant [is_mul_right_invariant μ] : quasi_measure_preserving (λ (p : G × G), p.1 / p.2) (μ.prod ν) μ := begin refine quasi_measure_preserving.prod_of_left measurable_div (eventually_of_forall $ λ y, _), exact (measure_preserving_div_right μ y).quasi_measure_preserving end @[to_additive] lemma quasi_measure_preserving_div [is_mul_left_invariant μ] : quasi_measure_preserving (λ (p : G × G), p.1 / p.2) (μ.prod ν) μ := (quasi_measure_preserving_div_of_right_invariant μ.inv ν).mono ((absolutely_continuous_inv μ).prod absolutely_continuous.rfl) (inv_absolutely_continuous μ) /-- A *left*-invariant measure is quasi-preserved by *right*-multiplication. This should not be confused with `(measure_preserving_mul_right μ g).quasi_measure_preserving`. -/ @[to_additive /-"A *left*-invariant measure is quasi-preserved by *right*-addition. This should not be confused with `(measure_preserving_add_right μ g).quasi_measure_preserving`. "-/] lemma quasi_measure_preserving_mul_right [is_mul_left_invariant μ] (g : G) : quasi_measure_preserving (λ h : G, h * g) μ μ := begin refine ⟨measurable_mul_const g, absolutely_continuous.mk $ λ s hs, _⟩, rw [map_apply (measurable_mul_const g) hs, measure_mul_right_null], exact id, end /-- A *right*-invariant measure is quasi-preserved by *left*-multiplication. This should not be confused with `(measure_preserving_mul_left μ g).quasi_measure_preserving`. -/ @[to_additive /-"A *right*-invariant measure is quasi-preserved by *left*-addition. This should not be confused with `(measure_preserving_add_left μ g).quasi_measure_preserving`. "-/] lemma quasi_measure_preserving_mul_left [is_mul_right_invariant μ] (g : G) : quasi_measure_preserving (λ h : G, g * h) μ μ := begin have := (quasi_measure_preserving_mul_right μ.inv g⁻¹).mono (inv_absolutely_continuous μ.inv) (absolutely_continuous_inv μ.inv), rw [μ.inv_inv] at this, have := (quasi_measure_preserving_inv_of_right_invariant μ).comp (this.comp (quasi_measure_preserving_inv_of_right_invariant μ)), simp_rw [function.comp, mul_inv_rev, inv_inv] at this, exact this end end quasi_measure_preserving end measure_theory
8f87ec54bbe94b6e15aab2edc4676415c2af717c
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/nat/sqrt.lean
e31b4db2452006997fcbe9fef4d4f5d44aed6883
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,869
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import data.int.basic /-! # Square root of natural numbers An efficient binary implementation of a (`sqrt n`) function that returns `s` such that ``` s*s ≤ n ≤ s*s + s + s ``` -/ namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp only [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end /-- Auxiliary function for `nat.sqrt`. See e.g. <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> -/ def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ @[pp_nodot] def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (pow_pos (show 0 < 2, from dec_trivial) m), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_comm, add_assoc, add_left_comm] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intro h; simp; [exact ⟨h₁, h⟩, exact ⟨h, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intro h, { have := sqrt_aux_is_sqrt m r h₁ h, simpa [pow_succ, mul_comm, mul_assoc] }, { rw [pow_succ', mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) h h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) @[simp] lemma sqrt_zero : sqrt 0 = 0 := by rw [sqrt, size_zero, sqrt._match_1] theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, by { rintro rfl, simp }⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (mul_le_mul_right _ _) _; exact le_add_right _ 2) _ theorem exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩ theorem sqrt_mul_sqrt_lt_succ (n : ℕ) : sqrt n * sqrt n < n + 1 := lt_succ_iff.mpr (sqrt_le _) theorem succ_le_succ_sqrt (n : ℕ) : n + 1 ≤ (sqrt n + 1) * (sqrt n + 1) := le_of_pred_lt (lt_succ_sqrt _) /-- There are no perfect squares strictly between m² and (m+1)² -/ theorem not_exists_sq {n m : ℕ} (hl : m * m < n) (hr : n < (m + 1) * (m + 1)) : ¬ ∃ t, t * t = n := begin rintro ⟨t, rfl⟩, have h1 : m < t, from nat.mul_self_lt_mul_self_iff.mpr hl, have h2 : t < m + 1, from nat.mul_self_lt_mul_self_iff.mpr hr, exact (not_lt_of_ge $ le_of_lt_succ h2) h1 end end nat
81dc655baa293e391fe02dde4cbf63b2e3924f08
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Test/importMathbin/lakefile.lean
003ffbc3c09646ca8f00b8f8956ad71044d6786c
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
246
lean
import Lake open Lake DSL System package importMathbin where defaultFacet := PackageFacet.oleans dependencies := #[{ name := "mathlib3port", src := Source.git "https://github.com/leanprover-community/mathlib3port.git" "master" }]
153f474bf371f2739a6482aa771fa787425f7ab3
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/nat/bigops.lean
5dd70a54e05da7ba284b7f54f17c419b64f042e2
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,907
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Finite products and sums on the natural numbers. -/ import data.nat.basic data.nat.order algebra.group_bigops algebra.group_set_bigops open list namespace nat open [classes] algebra local attribute nat.comm_semiring [instance] variables {A : Type} [deceqA : decidable_eq A] /- Prodl -/ definition Prodl (l : list A) (f : A → nat) : nat := algebra.Prodl l f notation `∏` binders `←` l, r:(scoped f, Prodl l f) := r theorem Prodl_nil (f : A → nat) : Prodl [] f = 1 := algebra.Prodl_nil f theorem Prodl_cons (f : A → nat) (a : A) (l : list A) : Prodl (a::l) f = f a * Prodl l f := algebra.Prodl_cons f a l theorem Prodl_append (l₁ l₂ : list A) (f : A → nat) : Prodl (l₁++l₂) f = Prodl l₁ f * Prodl l₂ f := algebra.Prodl_append l₁ l₂ f theorem Prodl_mul (l : list A) (f g : A → nat) : Prodl l (λx, f x * g x) = Prodl l f * Prodl l g := algebra.Prodl_mul l f g section deceqA include deceqA theorem Prodl_insert_of_mem (f : A → nat) {a : A} {l : list A} (H : a ∈ l) : Prodl (insert a l) f = Prodl l f := algebra.Prodl_insert_of_mem f H theorem Prodl_insert_of_not_mem (f : A → nat) {a : A} {l : list A} (H : a ∉ l) : Prodl (insert a l) f = f a * Prodl l f := algebra.Prodl_insert_of_not_mem f H theorem Prodl_union {l₁ l₂ : list A} (f : A → nat) (d : disjoint l₁ l₂) : Prodl (union l₁ l₂) f = Prodl l₁ f * Prodl l₂ f := algebra.Prodl_union f d theorem Prodl_one (l : list A) : Prodl l (λ x, nat.succ 0) = 1 := algebra.Prodl_one l end deceqA /- Prod over finset -/ namespace finset open finset definition Prod (s : finset A) (f : A → nat) : nat := algebra.finset.Prod s f notation `∏` binders `∈` s, r:(scoped f, Prod s f) := r theorem Prod_empty (f : A → nat) : Prod ∅ f = 1 := algebra.finset.Prod_empty f theorem Prod_mul (s : finset A) (f g : A → nat) : Prod s (λx, f x * g x) = Prod s f * Prod s g := algebra.finset.Prod_mul s f g section deceqA include deceqA theorem Prod_insert_of_mem (f : A → nat) {a : A} {s : finset A} (H : a ∈ s) : Prod (insert a s) f = Prod s f := algebra.finset.Prod_insert_of_mem f H theorem Prod_insert_of_not_mem (f : A → nat) {a : A} {s : finset A} (H : a ∉ s) : Prod (insert a s) f = f a * Prod s f := algebra.finset.Prod_insert_of_not_mem f H theorem Prod_union (f : A → nat) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) : Prod (s₁ ∪ s₂) f = Prod s₁ f * Prod s₂ f := algebra.finset.Prod_union f disj theorem Prod_ext {s : finset A} {f g : A → nat} (H : ∀x, x ∈ s → f x = g x) : Prod s f = Prod s g := algebra.finset.Prod_ext H theorem Prod_one (s : finset A) : Prod s (λ x, nat.succ 0) = 1 := algebra.finset.Prod_one s end deceqA end finset /- Prod over set -/ namespace set open set noncomputable definition Prod (s : set A) (f : A → nat) : nat := algebra.set.Prod s f notation `∏` binders `∈` s, r:(scoped f, Prod s f) := r theorem Prod_empty (f : A → nat) : Prod ∅ f = 1 := algebra.set.Prod_empty f theorem Prod_of_not_finite {s : set A} (nfins : ¬ finite s) (f : A → nat) : Prod s f = 1 := algebra.set.Prod_of_not_finite nfins f theorem Prod_mul (s : set A) (f g : A → nat) : Prod s (λx, f x * g x) = Prod s f * Prod s g := algebra.set.Prod_mul s f g theorem Prod_insert_of_mem (f : A → nat) {a : A} {s : set A} (H : a ∈ s) : Prod (insert a s) f = Prod s f := algebra.set.Prod_insert_of_mem f H theorem Prod_insert_of_not_mem (f : A → nat) {a : A} {s : set A} [fins : finite s] (H : a ∉ s) : Prod (insert a s) f = f a * Prod s f := algebra.set.Prod_insert_of_not_mem f H theorem Prod_union (f : A → nat) {s₁ s₂ : set A} [fins₁ : finite s₁] [fins₂ : finite s₂] (disj : s₁ ∩ s₂ = ∅) : Prod (s₁ ∪ s₂) f = Prod s₁ f * Prod s₂ f := algebra.set.Prod_union f disj theorem Prod_ext {s : set A} {f g : A → nat} (H : ∀x, x ∈ s → f x = g x) : Prod s f = Prod s g := algebra.set.Prod_ext H theorem Prod_one (s : set A) : Prod s (λ x, nat.succ 0) = 1 := algebra.set.Prod_one s end set /- Suml -/ definition Suml (l : list A) (f : A → nat) : nat := algebra.Suml l f notation `∑` binders `←` l, r:(scoped f, Suml l f) := r theorem Suml_nil (f : A → nat) : Suml [] f = 0 := algebra.Suml_nil f theorem Suml_cons (f : A → nat) (a : A) (l : list A) : Suml (a::l) f = f a + Suml l f := algebra.Suml_cons f a l theorem Suml_append (l₁ l₂ : list A) (f : A → nat) : Suml (l₁++l₂) f = Suml l₁ f + Suml l₂ f := algebra.Suml_append l₁ l₂ f theorem Suml_add (l : list A) (f g : A → nat) : Suml l (λx, f x + g x) = Suml l f + Suml l g := algebra.Suml_add l f g section deceqA include deceqA theorem Suml_insert_of_mem (f : A → nat) {a : A} {l : list A} (H : a ∈ l) : Suml (insert a l) f = Suml l f := algebra.Suml_insert_of_mem f H theorem Suml_insert_of_not_mem (f : A → nat) {a : A} {l : list A} (H : a ∉ l) : Suml (insert a l) f = f a + Suml l f := algebra.Suml_insert_of_not_mem f H theorem Suml_union {l₁ l₂ : list A} (f : A → nat) (d : disjoint l₁ l₂) : Suml (union l₁ l₂) f = Suml l₁ f + Suml l₂ f := algebra.Suml_union f d theorem Suml_zero (l : list A) : Suml l (λ x, zero) = 0 := algebra.Suml_zero l end deceqA /- Sum over a finset -/ namespace finset open finset definition Sum (s : finset A) (f : A → nat) : nat := algebra.finset.Sum s f notation `∑` binders `∈` s, r:(scoped f, Sum s f) := r theorem Sum_empty (f : A → nat) : Sum ∅ f = 0 := algebra.finset.Sum_empty f theorem Sum_add (s : finset A) (f g : A → nat) : Sum s (λx, f x + g x) = Sum s f + Sum s g := algebra.finset.Sum_add s f g section deceqA include deceqA theorem Sum_insert_of_mem (f : A → nat) {a : A} {s : finset A} (H : a ∈ s) : Sum (insert a s) f = Sum s f := algebra.finset.Sum_insert_of_mem f H theorem Sum_insert_of_not_mem (f : A → nat) {a : A} {s : finset A} (H : a ∉ s) : Sum (insert a s) f = f a + Sum s f := algebra.finset.Sum_insert_of_not_mem f H theorem Sum_union (f : A → nat) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) : Sum (s₁ ∪ s₂) f = Sum s₁ f + Sum s₂ f := algebra.finset.Sum_union f disj theorem Sum_ext {s : finset A} {f g : A → nat} (H : ∀x, x ∈ s → f x = g x) : Sum s f = Sum s g := algebra.finset.Sum_ext H theorem Sum_zero (s : finset A) : Sum s (λ x, zero) = 0 := algebra.finset.Sum_zero s end deceqA end finset /- Sum over a set -/ namespace set open set noncomputable definition Sum (s : set A) (f : A → nat) : nat := algebra.set.Sum s f notation `∏` binders `∈` s, r:(scoped f, Sum s f) := r theorem Sum_empty (f : A → nat) : Sum ∅ f = 0 := algebra.set.Sum_empty f theorem Sum_of_not_finite {s : set A} (nfins : ¬ finite s) (f : A → nat) : Sum s f = 0 := algebra.set.Sum_of_not_finite nfins f theorem Sum_add (s : set A) (f g : A → nat) : Sum s (λx, f x + g x) = Sum s f + Sum s g := algebra.set.Sum_add s f g theorem Sum_insert_of_mem (f : A → nat) {a : A} {s : set A} (H : a ∈ s) : Sum (insert a s) f = Sum s f := algebra.set.Sum_insert_of_mem f H theorem Sum_insert_of_not_mem (f : A → nat) {a : A} {s : set A} [fins : finite s] (H : a ∉ s) : Sum (insert a s) f = f a + Sum s f := algebra.set.Sum_insert_of_not_mem f H theorem Sum_union (f : A → nat) {s₁ s₂ : set A} [fins₁ : finite s₁] [fins₂ : finite s₂] (disj : s₁ ∩ s₂ = ∅) : Sum (s₁ ∪ s₂) f = Sum s₁ f + Sum s₂ f := algebra.set.Sum_union f disj theorem Sum_ext {s : set A} {f g : A → nat} (H : ∀x, x ∈ s → f x = g x) : Sum s f = Sum s g := algebra.set.Sum_ext H theorem Sum_zero (s : set A) : Sum s (λ x, 0) = 0 := algebra.set.Sum_zero s end set end nat
42ca3ccbd34b90a7ca628ba722f15cf92aeefc21
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/init/prod.lean
275505d16bcfab0271873fb9cd61c32f861f0c5a
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,693
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, Jeremy Avigad -/ prelude import init.num init.wf definition pair [constructor] := @prod.mk notation A × B := prod A B -- notation for n-ary tuples notation `(` h `, ` t:(foldl `, ` (e r, prod.mk r e) h) `)` := t namespace prod notation [parsing-only] A * B := prod A B namespace low_precedence_times reserve infixr [parsing-only] `*`:30 -- conflicts with notation for multiplication infixr `*` := prod end low_precedence_times notation `pr₁` := pr1 notation `pr₂` := pr2 namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 end ops definition destruct [reducible] := @prod.cases_on section variables {A B : Type} lemma pr1.mk (a : A) (b : B) : pr1 (mk a b) = a := rfl lemma pr2.mk (a : A) (b : B) : pr2 (mk a b) = b := rfl lemma eta : ∀ (p : A × B), mk (pr1 p) (pr2 p) = p | (a, b) := rfl end open well_founded section variables {A B : Type} variable (Ra : A → A → Prop) variable (Rb : B → B → Prop) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Prop := | left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Prop := intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {A B : Type} parameters {Ra : A → A → Prop} {Rb : B → B → Prop} local infix `≺`:50 := lex Ra Rb definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)), λb, acc.rec_on (acb b) (λxb acb (iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @prod.lex.rec_on A B Ra Rb (λp₁ p₂, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λa b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb) end end prod
01cc0f427b7829e71bfc9d44f3c8110704302ef3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/axiom_code.lean
740d9618373d02ed035fa36d7d4ec3ed0e72437a
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
87
lean
constant ax : nat noncomputable def test : nat → nat | 0 := ax | (n+1) := test n
adf04c872fc9455b600efec29069a651c2203b43
69bc7d0780be17e452d542a93f9599488f1c0c8e
/prop_logic.lean
625768ad68e617059cab7c03943857bd74477aa5
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
1,662
lean
namespace prop_logic -- syntax inductive var : Type | mkVar : ℕ → var inductive unOp : Type | notOp inductive binOp | andOp | orOp inductive pExp | litExp : bool → pExp | varExp : var → pExp -- "variable expression"—like a "box with a variable in it" | unOpExp : unOp → pExp → pExp | binOpExp : binOp → pExp → pExp → pExp def pTrue := pExp.litExp tt def pFalse := pExp.litExp ff def pNot := pExp.unOpExp unOp.notOp -- pExp → pExp #check pNot def pAnd := pExp.binOpExp binOp.andOp -- partial evlaution of binOpExp - pExp → pExp → pExp #check pAnd def pOr := pExp.binOpExp binOp.orOp -- pExp → pExp → pExp #check pOr notation e1 ∧ e2 := pAnd e1 e2 -- "Mr. or Mrs. Lean" notation e1 ∨ e2 := pOr e1 e2 notation ¬ e := pNot e -- If syntax represents the rules/structure of our formal language, what are the semantics? /- They define the meaning of syntactically legal/valid expressions -/ -- semantics! -- we interpret notOp as representing boolean not def interpUnOp : unOp → (bool → bool) | notOp := bnot -- likewise, we interpret andOp and orOp as representing boolean and and or, respectively def interpBinOp : binOp → (bool → bool → bool) | binOp.andOp := band | binOp.orOp := bor def pEval : pExp → (var → bool) → bool | (pExp.litExp b) i := b -- literals need not be interpreted | (pExp.varExp v) i := i v -- just get the current interpretation's value for the var | (pExp.unOpExp o e) i := (interpUnOp o) (pEval e i) -- apply the unary operation to this value | (pExp.binOpExp o e1 e2) i := (interpBinOp o) (pEval e1 i) (pEval e2 i) -- apply the binary operation to the values end prop_logic
13c482e61c42c14cb59675d5beda61565e5a6682
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/algebra/ordered_ring.lean
1e3c36c5be266955247ac378b0c99aa10511b6c3
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
16,013
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.ordered_group init.algebra.ring /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe u class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_comm_monoid α := (mul_le_mul_of_nonneg_left: ∀ a b c : α, a ≤ b → 0 ≤ c → c * a ≤ c * b) (mul_le_mul_of_nonneg_right: ∀ a b c : α, a ≤ b → 0 ≤ c → a * c ≤ b * c) (mul_lt_mul_of_pos_left: ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right: ∀ a b c : α, a < b → 0 < c → a * c < b * c) variable {α : Type u} section ordered_semiring variable [ordered_semiring α] lemma mul_le_mul_of_nonneg_left {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := ordered_semiring.mul_le_mul_of_nonneg_left a b c h₁ h₂ lemma mul_le_mul_of_nonneg_right {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := ordered_semiring.mul_le_mul_of_nonneg_right a b c h₁ h₂ lemma mul_lt_mul_of_pos_left {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul {a b c d : α} (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg {a b : α} (ha : a ≥ 0) (hb : b ≥ 0) : a * b ≥ 0 := have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonpos_of_nonneg_of_nonpos {a b : α} (ha : a ≥ 0) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg {a b : α} (ha : a ≤ 0) (hb : b ≥ 0) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul {a b c d : α} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : b ≥ 0) (h4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right (le_of_lt h1) h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos {a b : α} (ha : a > 0) (hb : b > 0) : a * b > 0 := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg {a b : α} (ha : a > 0) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos {a b : α} (ha : a < 0) (hb : b > 0) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_lt_mul_self {a b : α} (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2 h2 h1 (lt_of_le_of_lt h1 h2) end ordered_semiring class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_strong_order_pair α := (zero_lt_one : zero < one) section linear_ordered_semiring variable [linear_ordered_semiring α] lemma zero_lt_one : 0 < (1:α) := linear_ordered_semiring.zero_lt_one α lemma zero_le_one : 0 ≤ (1:α) := le_of_lt zero_lt_one lemma lt_of_mul_lt_mul_left {a b c : α} (h : c * a < c * b) (hc : c ≥ 0) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc, not_lt_of_ge h2 h) lemma lt_of_mul_lt_mul_right {a b c : α} (h : a * c < b * c) (hc : c ≥ 0) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc, not_lt_of_ge h2 h) lemma le_of_mul_le_mul_left {a b c : α} (h : c * a ≤ c * b) (hc : c > 0) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_mul_le_mul_right {a b c : α} (h : a * c ≤ b * c) (hc : c > 0) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, not_le_of_gt h2 h) lemma pos_of_mul_pos_left {a b : α} (h : 0 < a * b) (h1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume h2 : b ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos h1 h2, not_lt_of_ge h3 h) lemma pos_of_mul_pos_right {a b : α} (h : 0 < a * b) (h1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume h2 : a ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg h2 h1, not_lt_of_ge h3 h) lemma nonneg_of_mul_nonneg_left {a b : α} (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg h1 h2) h) lemma nonneg_of_mul_nonneg_right {a b : α} (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos h2 h1) h) lemma neg_of_mul_neg_left {a b : α} (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume h2 : b ≥ 0, not_lt_of_ge (mul_nonneg h1 h2) h) lemma neg_of_mul_neg_right {a b : α} (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume h2 : a ≥ 0, not_lt_of_ge (mul_nonneg h2 h1) h) lemma nonpos_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, not_le_of_gt (mul_pos h1 h2) h) lemma nonpos_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, not_le_of_gt (mul_pos h2 h1) h) end linear_ordered_semiring class decidable_linear_ordered_semiring (α : Type u) extends linear_ordered_semiring α, decidable_linear_order α class ordered_ring (α : Type u) extends ring α, ordered_comm_group α, zero_ne_one_class α := (mul_nonneg : ∀ a b : α, 0 ≤ a → 0 ≤ b → 0 ≤ a * b) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) lemma ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring α] {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring α] {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring α] {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply lt_of_sub_pos this end lemma ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring α] {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply lt_of_sub_pos this end instance ordered_ring.to_ordered_semiring [s : ordered_ring α] : ordered_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left α _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right α _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left α _} section ordered_ring variable [ordered_ring α] lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [-neg_mul_eq_neg_mul, -neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [-neg_mul_eq_mul_neg, -neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [-neg_mul_eq_neg_mul, -neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [-neg_mul_eq_mul_neg, -neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this end ordered_ring class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_strong_order_pair α := (zero_lt_one : lt zero one) instance linear_ordered_ring.to_linear_ordered_semiring [s : linear_ordered_ring α] : linear_ordered_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left α _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right α _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left α _ } section linear_ordered_ring variable [linear_ordered_ring α] lemma mul_self_nonneg (a : α) : a * a ≥ 0 := or.elim (le_total 0 a) (assume h : a ≥ 0, mul_nonneg h h) (assume h : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos h h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos {a b : α} (hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := or.inl ⟨hlt₁, hlt₂⟩ | or.inr (or.inl heq₂) := begin rw [-heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := absurd hab (lt_asymm (mul_neg_of_pos_of_neg hlt₁ hgt₂)) end | or.inr (or.inl heq₁) := begin rw [-heq₁, zero_mul] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := absurd hab (lt_asymm (mul_neg_of_neg_of_pos hgt₁ hlt₂)) | or.inr (or.inl heq₂) := begin rw [-heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := or.inr ⟨hgt₁, hgt₂⟩ end end lemma gt_of_mul_lt_mul_neg_left {a b c : α} (h : c * a < c * b) (hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma zero_gt_neg_one : -1 < (0:α) := begin note this := neg_lt_neg (@zero_lt_one α _), rwa neg_zero at this end lemma le_of_mul_le_of_ge_one {a b c : α} (h : a * c ≤ b) (hb : b ≥ 0) (hc : c ≥ 1) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (lt_of_lt_of_le zero_lt_one hc) lemma nonneg_le_nonneg_of_squares_le {a b : α} (ha : a ≥ 0) (hb : b ≥ 0) (h : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro hab, note hposa := lt_of_le_of_lt hb hab, note h' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt hab) hb ... < a * a : mul_lt_mul_of_pos_left hab hposa, apply (not_le_of_gt h') h end end linear_ordered_ring class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α lemma linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 < a * b, from mul_pos hlt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 > a * b, from mul_neg_of_pos_of_neg hlt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end | or.inr (or.inl heq₁) := or.inl heq₁.symm | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 > a * b, from mul_neg_of_neg_of_pos hgt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 < a * b, from mul_pos_of_neg_of_neg hgt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end end instance linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring α] : integral_domain α := {s with eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s } class decidable_linear_ordered_comm_ring (α : Type u) extends linear_ordered_comm_ring α, decidable_linear_ordered_comm_group α instance decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [d : decidable_linear_ordered_comm_ring α] : decidable_linear_ordered_semiring α := let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in {d with zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, lt_of_add_lt_add_left := @linear_ordered_semiring.lt_of_add_lt_add_left α s, mul_le_mul_of_nonneg_left := @linear_ordered_semiring.mul_le_mul_of_nonneg_left α s, mul_le_mul_of_nonneg_right := @linear_ordered_semiring.mul_le_mul_of_nonneg_right α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s}
55128de5c2402286b141ab0ea53874268311ac5b
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/linear_algebra/sesquilinear_form.lean
0ba2721ebfe3a9d6435ece1b5afef456827b5c10
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
8,614
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import algebra.module ring_theory.maps /-! # Sesquilinear form This file defines a bilinear form over a module. The definition requires a ring antiautomorphism on the scalar ring, which comes from the file ring_theory.involution. Basic ideas such as orthogonality are also introduced. A sesquilinear form on an R-module M, is a function from M x M to R, that is linear in the first argument and antilinear in the second, with respect to an antiautomorphism on R (an antiisomorphism from R to R). ## Notations Given any term S of type sesq_form, due to a coercion, can use the notation S x y to refer to the function field, ie. S x y = S.bilin x y. ## References * https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings ## Tags Sesquilinear form, -/ open ring_anti_equiv universes u v /-- A sesquilinear form over a module -/ structure sesq_form (R : Type u) (M : Type v) [ring R] (I : ring_anti_equiv R R) [add_comm_group M] [module R M] := (sesq : M → M → R) (sesq_add_left : ∀ (x y z : M), sesq (x + y) z = sesq x z + sesq y z) (sesq_smul_left : ∀ (a : R) (x y : M), sesq (a • x) y = a * (sesq x y)) (sesq_add_right : ∀ (x y z : M), sesq x (y + z) = sesq x y + sesq x z) (sesq_smul_right : ∀ (a : R) (x y : M), sesq x (a • y) = (I a) * (sesq x y)) namespace sesq_form section general_ring variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} instance : has_coe_to_fun (sesq_form R M I) := ⟨_, λ S, S.sesq⟩ lemma add_left (x y z : M) : S (x + y) z = S x z + S y z := sesq_add_left S x y z lemma smul_left (a : R) (x y : M) : S (a • x) y = a * (S x y) := sesq_smul_left S a x y lemma add_right (x y z : M) : S x (y + z) = S x y + S x z := sesq_add_right S x y z lemma smul_right (a : R) (x y : M) : S x (a • y) = (I a) * (S x y) := sesq_smul_right S a x y lemma zero_left (x : M) : S 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]} lemma zero_right (x : M) : S x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, map_zero, ring.zero_mul] lemma neg_left (x y : M) : S (-x) y = -(S x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul] lemma neg_right (x y : M) : S x (-y) = -(S x y) := by rw [←@neg_one_smul R _ _, smul_right, map_neg_one, neg_one_mul] lemma sub_left (x y z : M) : S (x - y) z = S x z - S y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl lemma sub_right (x y z : M) : S x (y - z) = S x y - S x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl variable {D : sesq_form R M I} @[ext] lemma ext (H : ∀ (x y : M), S x y = D x y) : S = D := by {cases S, cases D, congr, funext, exact H _ _} instance : add_comm_group (sesq_form R M I) := { add := λ S D, { sesq := λ x y, S x y + D x y, sesq_add_left := λ x y z, by {rw add_left, rw add_left, simp}, sesq_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]}, sesq_add_right := λ x y z, by {rw add_right, rw add_right, simp}, sesq_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }, add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq coe_fn has_coe_to_fun.coe sesq, rw add_assoc}, zero := { sesq := λ x y, 0, sesq_add_left := λ x y z, (add_zero 0).symm, sesq_smul_left := λ a x y, (mul_zero a).symm, sesq_add_right := λ x y z, (zero_add 0).symm, sesq_smul_right := λ a x y, (mul_zero (I a)).symm }, zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw zero_add}, add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw add_zero}, neg := λ S, { sesq := λ x y, - (S.1 x y), sesq_add_left := λ x y z, by rw [sesq_add_left, neg_add], sesq_smul_left := λ a x y, by rw [sesq_smul_left, mul_neg_eq_neg_mul_symm], sesq_add_right := λ x y z, by rw [sesq_add_right, neg_add], sesq_smul_right := λ a x y, by rw [sesq_smul_right, mul_neg_eq_neg_mul_symm] }, add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw neg_add_self}, add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw add_comm} } /-- The proposition that two elements of a sesquilinear form space are orthogonal -/ def is_ortho (S : sesq_form R M I) (x y : M) : Prop := S x y = 0 lemma ortho_zero (x : M) : is_ortho S (0 : M) x := zero_left x end general_ring section comm_ring variables {R : Type*} [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {J : ring_anti_equiv R R} (F : sesq_form R M J) (f : M → M) instance to_module : module R (sesq_form R M J) := { smul := λ c S, { sesq := λ x y, c * S x y, sesq_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_add_left, left_distrib]}, sesq_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_smul_left, ←mul_assoc, mul_comm c, mul_assoc]}, sesq_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_add_right, left_distrib]}, sesq_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe sesq, rw [sesq_smul_right, ←mul_assoc, mul_comm c, mul_assoc], refl} }, smul_add := λ c S D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw left_distrib}, add_smul := λ c S D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw right_distrib}, mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw mul_assoc}, one_smul := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw one_mul}, zero_smul := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw zero_mul}, smul_zero := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw mul_zero} } end comm_ring section domain variables {R : Type*} [domain R] {M : Type v} [add_comm_group M] [module R M] {K : ring_anti_equiv R R} {G : sesq_form R M K} theorem ortho_smul_left {x y : M} {a : R} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [smul_left, H, ring.mul_zero] }, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end theorem ortho_smul_right {x y : M} {a : R} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [smul_right, H, ring.mul_zero] }, { rw [smul_right, mul_eq_zero] at H, cases H, { rw map_zero_iff at H, trivial }, { exact H }} end end domain end sesq_form namespace refl_sesq_form open refl_sesq_form sesq_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} /-- The proposition that a sesquilinear form is reflexive -/ def is_refl (S : sesq_form R M I) : Prop := ∀ (x y : M), S x y = 0 → S y x = 0 variable (H : is_refl S) lemma eq_zero : ∀ {x y : M}, S x y = 0 → S y x = 0 := λ x y, H x y lemma ortho_sym {x y : M} : is_ortho S x y ↔ is_ortho S y x := ⟨eq_zero H, eq_zero H⟩ end refl_sesq_form namespace sym_sesq_form open sym_sesq_form sesq_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} /-- The proposition that a sesquilinear form is symmetric -/ def is_sym (S : sesq_form R M I) : Prop := ∀ (x y : M), I (S x y) = S y x variable (H : is_sym S) include H lemma sym (x y : M) : I (S x y) = S y x := H x y lemma is_refl : refl_sesq_form.is_refl S := λ x y H1, by rw [←H, map_zero_iff, H1] lemma ortho_sym {x y : M} : is_ortho S x y ↔ is_ortho S y x := refl_sesq_form.ortho_sym (is_refl H) end sym_sesq_form namespace alt_sesq_form open alt_sesq_form sesq_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {I : ring_anti_equiv R R} {S : sesq_form R M I} /-- The proposition that a sesquilinear form is alternating -/ def is_alt (S : sesq_form R M I) : Prop := ∀ (x : M), S x x = 0 variable (H : is_alt S) include H lemma self_eq_zero (x : M) : S x x = 0 := H x lemma neg (x y : M) : - S x y = S y x := begin have H1 : S (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end end alt_sesq_form
0839d06b6738d39df0c9fcc1dd7179ef5323a6d5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/polynomial/mirror.lean
e73d047aa1a969d34de419a809b8665c78cc0b8f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,534
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.big_operators.nat_antidiagonal import data.polynomial.ring_division /-! # "Mirror" of a univariate polynomial In this file we define `polynomial.mirror`, a variant of `polynomial.reverse`. The difference between `reverse` and `mirror` is that `reverse` will decrease the degree if the polynomial is divisible by `X`. ## Main definitions - `polynomial.mirror` ## Main results - `polynomial.mirror_mul_of_domain`: `mirror` preserves multiplication. - `polynomial.irreducible_of_mirror`: an irreducibility criterion involving `mirror` -/ namespace polynomial open_locale polynomial section semiring variables {R : Type*} [semiring R] (p q : R[X]) /-- mirror of a polynomial: reverses the coefficients while preserving `polynomial.nat_degree` -/ noncomputable def mirror := p.reverse * X ^ p.nat_trailing_degree @[simp] lemma mirror_zero : (0 : R[X]).mirror = 0 := by simp [mirror] lemma mirror_monomial (n : ℕ) (a : R) : (monomial n a).mirror = (monomial n a) := begin classical, by_cases ha : a = 0, { rw [ha, monomial_zero_right, mirror_zero] }, { rw [mirror, reverse, nat_degree_monomial n a, if_neg ha, nat_trailing_degree_monomial ha, ← C_mul_X_pow_eq_monomial, reflect_C_mul_X_pow, rev_at_le (le_refl n), tsub_self, pow_zero, mul_one] }, end lemma mirror_C (a : R) : (C a).mirror = C a := mirror_monomial 0 a lemma mirror_X : X.mirror = (X : R[X]) := mirror_monomial 1 (1 : R) lemma mirror_nat_degree : p.mirror.nat_degree = p.nat_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, nontriviality R, rw [mirror, nat_degree_mul', reverse_nat_degree, nat_degree_X_pow, tsub_add_cancel_of_le p.nat_trailing_degree_le_nat_degree], rwa [leading_coeff_X_pow, mul_one, reverse_leading_coeff, ne, trailing_coeff_eq_zero] end lemma mirror_nat_trailing_degree : p.mirror.nat_trailing_degree = p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, { rw [mirror, nat_trailing_degree_mul_X_pow ((mt reverse_eq_zero.mp) hp), reverse_nat_trailing_degree, zero_add] }, end lemma coeff_mirror (n : ℕ) : p.mirror.coeff n = p.coeff (rev_at (p.nat_degree + p.nat_trailing_degree) n) := begin by_cases h2 : p.nat_degree < n, { rw [coeff_eq_zero_of_nat_degree_lt (by rwa mirror_nat_degree)], by_cases h1 : n ≤ p.nat_degree + p.nat_trailing_degree, { rw [rev_at_le h1, coeff_eq_zero_of_lt_nat_trailing_degree], exact (tsub_lt_iff_left h1).mpr (nat.add_lt_add_right h2 _) }, { rw [←rev_at_fun_eq, rev_at_fun, if_neg h1, coeff_eq_zero_of_nat_degree_lt h2] } }, rw not_lt at h2, rw [rev_at_le (h2.trans (nat.le_add_right _ _))], by_cases h3 : p.nat_trailing_degree ≤ n, { rw [←tsub_add_eq_add_tsub h2, ←tsub_tsub_assoc h2 h3, mirror, coeff_mul_X_pow', if_pos h3, coeff_reverse, rev_at_le (tsub_le_self.trans h2)] }, rw not_le at h3, rw coeff_eq_zero_of_nat_degree_lt (lt_tsub_iff_right.mpr (nat.add_lt_add_left h3 _)), exact coeff_eq_zero_of_lt_nat_trailing_degree (by rwa mirror_nat_trailing_degree), end --TODO: Extract `finset.sum_range_rev_at` lemma. lemma mirror_eval_one : p.mirror.eval 1 = p.eval 1 := begin simp_rw [eval_eq_sum_range, one_pow, mul_one, mirror_nat_degree], refine finset.sum_bij_ne_zero _ _ _ _ _, { exact λ n hn hp, rev_at (p.nat_degree + p.nat_trailing_degree) n }, { intros n hn hp, rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right, ←mirror_nat_trailing_degree], exact nat_trailing_degree_le_of_ne_zero hp }, { exact λ n₁ n₂ hn₁ hp₁ hn₂ hp₂ h, by rw [←@rev_at_invol _ n₁, h, rev_at_invol] }, { intros n hn hp, use rev_at (p.nat_degree + p.nat_trailing_degree) n, refine ⟨_, _, rev_at_invol.symm⟩, { rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right], exact nat_trailing_degree_le_of_ne_zero hp }, { change p.mirror.coeff _ ≠ 0, rwa [coeff_mirror, rev_at_invol] } }, { exact λ n hn hp, p.coeff_mirror n }, end lemma mirror_mirror : p.mirror.mirror = p := polynomial.ext (λ n, by rw [coeff_mirror, coeff_mirror, mirror_nat_degree, mirror_nat_trailing_degree, rev_at_invol]) variables {p q} lemma mirror_involutive : function.involutive (mirror : R[X] → R[X]) := mirror_mirror lemma mirror_eq_iff : p.mirror = q ↔ p = q.mirror := mirror_involutive.eq_iff @[simp] lemma mirror_inj : p.mirror = q.mirror ↔ p = q := mirror_involutive.injective.eq_iff @[simp] lemma mirror_eq_zero : p.mirror = 0 ↔ p = 0 := ⟨λ h, by rw [←p.mirror_mirror, h, mirror_zero], λ h, by rw [h, mirror_zero]⟩ variables (p q) @[simp] lemma mirror_trailing_coeff : p.mirror.trailing_coeff = p.leading_coeff := by rw [leading_coeff, trailing_coeff, mirror_nat_trailing_degree, coeff_mirror, rev_at_le (nat.le_add_left _ _), add_tsub_cancel_right] @[simp] lemma mirror_leading_coeff : p.mirror.leading_coeff = p.trailing_coeff := by rw [←p.mirror_mirror, mirror_trailing_coeff, p.mirror_mirror] lemma coeff_mul_mirror : (p * p.mirror).coeff (p.nat_degree + p.nat_trailing_degree) = p.sum (λ n, (^ 2)) := begin rw [coeff_mul, finset.nat.sum_antidiagonal_eq_sum_range_succ_mk], refine (finset.sum_congr rfl (λ n hn, _)).trans (p.sum_eq_of_subset (λ n, (^ 2)) (λ n, zero_pow zero_lt_two) _ (λ n hn, finset.mem_range_succ_iff.mpr ((le_nat_degree_of_mem_supp n hn).trans (nat.le_add_right _ _)))).symm, rw [coeff_mirror, ←rev_at_le (finset.mem_range_succ_iff.mp hn), rev_at_invol, ←sq], end variables [no_zero_divisors R] lemma nat_degree_mul_mirror : (p * p.mirror).nat_degree = 2 * p.nat_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, nat_degree_zero, mul_zero] }, rw [nat_degree_mul hp (mt mirror_eq_zero.mp hp), mirror_nat_degree, two_mul], end lemma nat_trailing_degree_mul_mirror : (p * p.mirror).nat_trailing_degree = 2 * p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, nat_trailing_degree_zero, mul_zero] }, rw [nat_trailing_degree_mul hp (mt mirror_eq_zero.mp hp), mirror_nat_trailing_degree, two_mul], end end semiring section ring variables {R : Type*} [ring R] (p q : R[X]) lemma mirror_neg : (-p).mirror = -(p.mirror) := by rw [mirror, mirror, reverse_neg, nat_trailing_degree_neg, neg_mul_eq_neg_mul] variables [no_zero_divisors R] lemma mirror_mul_of_domain : (p * q).mirror = p.mirror * q.mirror := begin by_cases hp : p = 0, { rw [hp, zero_mul, mirror_zero, zero_mul] }, by_cases hq : q = 0, { rw [hq, mul_zero, mirror_zero, mul_zero] }, rw [mirror, mirror, mirror, reverse_mul_of_domain, nat_trailing_degree_mul hp hq, pow_add], rw [mul_assoc, ←mul_assoc q.reverse], conv_lhs { congr, skip, congr, rw [←X_pow_mul] }, repeat { rw [mul_assoc], }, end lemma mirror_smul (a : R) : (a • p).mirror = a • p.mirror := by rw [←C_mul', ←C_mul', mirror_mul_of_domain, mirror_C] end ring section comm_ring variables {R : Type*} [comm_ring R] [no_zero_divisors R] {f : R[X]} lemma irreducible_of_mirror (h1 : ¬ is_unit f) (h2 : ∀ k, f * f.mirror = k * k.mirror → k = f ∨ k = -f ∨ k = f.mirror ∨ k = -f.mirror) (h3 : ∀ g, g ∣ f → g ∣ f.mirror → is_unit g) : irreducible f := begin split, { exact h1 }, { intros g h fgh, let k := g * h.mirror, have key : f * f.mirror = k * k.mirror, { rw [fgh, mirror_mul_of_domain, mirror_mul_of_domain, mirror_mirror, mul_assoc, mul_comm h, mul_comm g.mirror, mul_assoc, ←mul_assoc] }, have g_dvd_f : g ∣ f, { rw fgh, exact dvd_mul_right g h }, have h_dvd_f : h ∣ f, { rw fgh, exact dvd_mul_left h g }, have g_dvd_k : g ∣ k, { exact dvd_mul_right g h.mirror }, have h_dvd_k_rev : h ∣ k.mirror, { rw [mirror_mul_of_domain, mirror_mirror], exact dvd_mul_left h g.mirror }, have hk := h2 k key, rcases hk with hk | hk | hk | hk, { exact or.inr (h3 h h_dvd_f (by rwa ← hk)) }, { exact or.inr (h3 h h_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, mirror_neg, dvd_neg])) }, { exact or.inl (h3 g g_dvd_f (by rwa ← hk)) }, { exact or.inl (h3 g g_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, dvd_neg])) } }, end end comm_ring end polynomial
a47e6ac5112fc41f060560a0283fef97f874804d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/proofIrrelFVar.lean
53199e57679255a9787fe5ab664e16cc0f03422c
[ "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
169
lean
universe u variable {α : Type u} {p : α → Prop} theorem ex (a : α) (h1 h2 : p a) (h : Subtype.mk a h1 = Subtype.mk a h1) : Subtype.mk a h1 = Subtype.mk a h2 := h
e54e8e6ea7673aa20dc8d549fd96a23e2fa077cc
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/computability/partrec.lean
b48d7df3547fabe8aa355cb21946c0d5aacde79b
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,900
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 computability.primrec import data.nat.psub import data.pfun /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable roption namespace nat section rfind parameter (p : ℕ →. bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : ∀m k, n ≤ k + m → acc (lbp p) k, { from λa, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} := suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m}, from this 0 (λ n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, h₂⟩, rcases lt_trichotomy m n with h₃|h₃|h₃, { exact h₂ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)), intros n h, cases decidable.lt_or_eq_of_le h with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : ℕ →. bool) : roption ℕ := ⟨_, λ h, (rfind_x p h).1⟩ theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := h.snd ▸ (rfind_x p h.fst).2.1 theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → ff ∈ p m := h.snd ▸ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom := iff.rfl theorem rfind_dom' {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom := exists_congr $ λ n, and_congr_right $ λ pn, ⟨λ H m h, (eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _), λ H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (h₂ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ λ h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ λ a h, let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in (p0 ▸ h₂ (zero_le _) : (@roption.none bool).dom) def rfind_opt {α} (f : ℕ → option α) : roption α := (rfind (λ n, (f n).is_some)).bind (λ n, f n) theorem rfind_opt_spec {α} {f : ℕ → option α} {a} (h : a ∈ rfind_opt f) : ∃ n, a ∈ f n := let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩ theorem rfind_opt_dom {α} {f : ℕ → option α} : (rfind_opt f).dom ↔ ∃ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩), λ h, begin have h' : ∃ n, (f n).is_some := h.imp (λ n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (λ n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊢, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {α} {f : ℕ → option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n := ⟨rfind_opt_spec, λ ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (ℕ →. ℕ) → Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec ↑(λ n : ℕ, n.unpair.1) | right : partrec ↑(λ n : ℕ, n.unpair.2) | pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n) | comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f) | prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n, n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f → partrec (λ a, rfind (λ n, (λ m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g := hf.of_eq (λ n, eq_some_iff.2 (H n)) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (λ n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (λ n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (λ n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (λ n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (λ a, (f a).bind (λ n, n.elim (g a) (λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ λ a, ext $ λ s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩, λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩ theorem ppred : partrec (λ n, ppred n) := have primrec₂ (λ n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).to₂, (of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $ λ n, begin cases n; simp, { exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {α σ} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec (λ n, roption.bind (decode α n) (λ a, (f a).map encode)) def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2) def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ) def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable (λ p : α × β, f p.1 p.2) theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ λ n, by simp; cases decode α n; simp theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp theorem computable.part {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf theorem computable₂.part {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : computable (λ a : α, s) := (primrec.const _).to_comp theorem of_option {f : α → option β} (hf : computable f) : partrec (λ a, (f a : roption β)) := (nat.partrec.ppred.comp hf).of_eq $ λ n, begin cases decode α n with a; simp, cases f a with b; simp end theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl protected theorem id : computable (@id α) := primrec.id.to_comp theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp theorem pair {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) := (hf.pair hg).of_eq $ λ n, by cases decode α n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length α) := primrec.list_length.to_comp theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode α _) := primrec.encode.to_comp protected theorem decode : computable (decode α) := primrec.decode.to_comp protected theorem of_nat (α) [denumerable α] : computable (of_nat α) := (primrec.of_nat _).to_comp theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some α) := primrec.option_some.to_comp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g := hf.of_eq (λ a, eq_some_iff.2 (H a)) theorem none : partrec (λ a : α, @roption.none σ) := nat.partrec.none.of_eq $ λ n, by cases decode α n; simp protected theorem some : partrec (@roption.some α) := computable.id theorem const' (s : roption σ) : partrec (λ a : α, s) := by haveI := classical.dec s.dom; exact (of_option (const (to_option s))).of_eq (λ a, of_to_option s) protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ λ n, by simp [(<*>)]; cases e : decode α n with a; simp [e, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (λ a b, roption.some (g a b)) hf hg theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ λ n, begin cases e : decode α n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [encodek] end theorem comp {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) := (hf.comp hg).of_eq $ λ n, by simp; cases e : decode α n with a; simp [e, encodek] theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrec₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := ⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp, λ h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end partrec₂ namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem comp {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, f (g a)) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ (λ a b, f (g a b)) := hf.comp hg end computable namespace computable₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end computable₂ namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) : partrec (λ a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (λ b, cond b 0 1)) .comp primrec.snd).to₂.to_comp).of_eq $ λ n, begin cases e : decode α n with a; simp [e, nat.rfind_zero_none, map_id'], congr, funext n, simp [roption.map_map, (∘)], apply map_id' (λ b, _), cases b; refl end theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) : partrec (λ a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).part.to₂).bind (of_option hf) theorem nat_cases_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec (λ a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $ λ a, begin simp, cases f a; simp, refine ext (λ b, ⟨λ H, _, λ H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ }, { have : ∀ m, (nat.elim (roption.some (g a)) (λ y IH, IH.bind (λ _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode2_iff {f : α →. σ} : partrec f ↔ nat.partrec (λ n, roption.bind (decode2 α n) (λ a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $ (map hf (computable.encode.comp snd).to₂).comp snd, λ h, map_encode_iff.1 $ by simpa [encodek2] using (nat_iff.2 h).comp (@computable.encode α _)⟩ theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) → partrec (λ (a : α), vector.m_of_fn (λ i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_roption_some {α n} : ∀ (f : fin n → α), vector.m_of_fn (λ i, roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n, (decode β n).bind (f a)) ↔ computable₂ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind (computable.comp hf fst).to₂.part) $ λ n, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; simp, λ hf, begin have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases (some option.none) (λ n, roption.map (f a.1) (decode β n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).to₂), refine this.of_eq (λ a, _), simp, cases decode β a.2; simp [encodek] end⟩ theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n, (decode β n).map (f a)) ↔ computable₂ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.part).of_eq $ λ a, by simp; induction f a; simp * theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂ theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : @computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ λ a, by cases o a; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ λ a, by cases f a; refl theorem option_map {f : α → option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_get_or_else {f : α → option β} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, (f a).get_or_else (g a)) := (computable.option_cases hf hg (show computable₂ (λ a b, b), from computable.snd)).of_eq $ λ a, by cases f a; refl theorem subtype_mk {f : α → β} {p : β → Prop} [decidable_pred p] {h : ∀ a, p (f a)} (hp : primrec_pred p) (hf : computable f) : @computable _ _ _ (primcodable.subtype hp) (λ a, (⟨f a, h a⟩ : subtype p)) := hf theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : @computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f := suffices computable₂ (λ a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_succ] end theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ λ a, by simp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem option_some_iff {f : α →. σ} : partrec (λ a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ λ n, by simp [roption.bind_assoc, bind_some_eq_map], λ hf, hf.map (option_some.comp snd).to₂⟩ theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : @partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (λ (a : α), nat.cases (roption.some (f a)) (λ n, roption.bind (decode β n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.part $ ((@computable.decode β _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).to₂, this.of_eq $ λ a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) := have partrec (λ a, (option.cases_on (sum.cases_on (f a) (λ b, option.none) option.some : option γ) (some (sum.cases_on (f a) (λ b, some (g a b)) (λ c, option.none))) (λ c, (h a c).map option.some) : roption (option σ))) := option_cases_right (sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂) (sum_cases hf (option_some.comp hg) (const option.none).to₂) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp theorem sum_cases_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $ λ a, by cases f a; simp private lemma fix_aux {f : α →. σ ⊕ α} (hf : partrec f) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in (∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩, have : ∀ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨a₂, am₂, fa₂⟩, exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) }, cases n; simp [F] at h₂, {cases h₂}, rcases h₂ with h₂ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h h₂ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), ∃ n, sum.inl b ∈ F a n ∧ ∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩, exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ }, intros a₁ h₁, apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk, rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩, { refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, h₂⟩ }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩, { refine ⟨n, hn₁, λ m mn km, _⟩, cases lt_or_eq_of_le km with km km, { exact hn₂ _ mn km }, { exact km ▸ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, am₃⟩ } } } end theorem fix {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in have hF : partrec₂ F := partrec.nat_elim snd (sum_inr.comp fst).part (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).to₂ (hf.comp snd).to₂).to₂, let p := λ a n, @roption.map _ bool (λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in have hp : partrec₂ p := hF.map ((sum_cases computable.id (const tt).to₂ (const ff).to₂).comp snd).to₂, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $ λ a, ext $ λ b, by simp; apply fix_aux hf end partrec
2ce7f3bc07d096c7a6c83963a36027f729037d2f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/filter/cofinite.lean
7c92a035b2a53a9f1ad895c7d1bc5ff439256480
[ "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,085
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.at_top_bot /-! # The cofinite filter In this file we define `cofinite`: the filter of sets with finite complement and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`. ## TODO Define filters for other cardinalities of the complement. -/ open set open_locale classical variables {α : Type*} namespace filter /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite sᶜ}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t), hs.subset $ compl_subset_compl.2 st, inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)), by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl @[simp] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in cofinite, p x) ↔ finite {x | ¬p x} := iff.rfl instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) := ⟨mt empty_mem_iff_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ }⟩ lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] /-- The coproduct of the cofinite filters on two types is the cofinite filter on their product. -/ lemma coprod_cofinite {β : Type*} : (cofinite : filter α).coprod (cofinite : filter β) = cofinite := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap, mem_cofinite], split, { rintro ⟨⟨A, hAf, hAS⟩, B, hBf, hBS⟩, rw [← compl_subset_compl, ← preimage_compl] at hAS hBS, exact (hAf.prod hBf).subset (subset_inter hAS hBS) }, { intro hS, refine ⟨⟨(prod.fst '' Sᶜ)ᶜ, _, _⟩, ⟨(prod.snd '' Sᶜ)ᶜ, _, _⟩⟩, { simpa using hS.image prod.fst }, { simpa [compl_subset_comm] using subset_preimage_image prod.fst Sᶜ }, { simpa using hS.image prod.snd }, { simpa [compl_subset_comm] using subset_preimage_image prod.snd Sᶜ } }, end /-- Finite product of finite sets is finite -/ lemma Coprod_cofinite {δ : Type*} {κ : δ → Type*} [fintype δ] : filter.Coprod (λ d, (cofinite : filter (κ d))) = cofinite := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap, mem_cofinite], split, { rintros h, rw mem_Coprod_iff at h, choose t ht1 ht2 using h, have ht1d : ∀ (d : δ), (t d)ᶜ.finite := λ d, mem_cofinite.mp (ht1 d), refine (set.finite.pi ht1d).subset _, have ht2d : ∀ (d : δ), Sᶜ ⊆ ((λ (k : Π (d1 : δ), (λ (d2 : δ), κ d2) d1), k d) ⁻¹' ((t d)ᶜ)) := λ d, compl_subset_compl.mpr (ht2 d), convert set.subset_Inter ht2d, ext, simp }, { intro hS, rw mem_Coprod_iff, intros d, refine ⟨((λ (k : Π (d1 : δ), κ d1), k d) '' (Sᶜ))ᶜ, _, _⟩, { rw [mem_cofinite, compl_compl], exact set.finite.image _ hS }, { intros x, contrapose, intros hx, simp only [not_not, mem_preimage, mem_compl_eq, not_forall], exact ⟨x, hx, rfl⟩ } }, end end filter open filter lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) := mem_cofinite.2 $ (compl_compl s).symm ▸ hs lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s := hs.compl_mem_cofinite lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s := s.finite_to_set.eventually_cofinite_nmem lemma set.infinite_iff_frequently_cofinite {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x := (set.finite_singleton x).eventually_cofinite_nmem /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (hs.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply (finite_lt_nat N).subset, assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} : (∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} := by simp only [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite] lemma filter.tendsto.exists_within_forall_le {α β : Type*} [linear_order β] {s : set α} (hs : s.nonempty) {f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_top) : ∃ a₀ ∈ s, ∀ a ∈ s, f a₀ ≤ f a := begin rcases em (∃ y ∈ s, ∃ x, f y < x) with ⟨y, hys, x, hx⟩|not_all_top, { -- the set of points `{y | f y < x}` is nonempty and finite, so we take `min` over this set have : finite {y | ¬x ≤ f y} := (filter.eventually_cofinite.mp (tendsto_at_top.1 hf x)), simp only [not_le] at this, obtain ⟨a₀, ⟨ha₀ : f a₀ < x, ha₀s⟩, others_bigger⟩ := exists_min_image _ f (this.inter_of_left s) ⟨y, hx, hys⟩, refine ⟨a₀, ha₀s, λ a has, (lt_or_le (f a) x).elim _ (le_trans ha₀.le)⟩, exact λ h, others_bigger a ⟨h, has⟩ }, { -- in this case, f is constant because all values are at top push_neg at not_all_top, obtain ⟨a₀, ha₀s⟩ := hs, exact ⟨a₀, ha₀s, λ a ha, not_all_top a ha (f a₀)⟩ } end lemma filter.tendsto.exists_forall_le {α β : Type*} [nonempty α] [linear_order β] {f : α → β} (hf : tendsto f cofinite at_top) : ∃ a₀, ∀ a, f a₀ ≤ f a := let ⟨a₀, _, ha₀⟩ := hf.exists_within_forall_le univ_nonempty in ⟨a₀, λ a, ha₀ a (mem_univ _)⟩ lemma filter.tendsto.exists_within_forall_ge {α β : Type*} [linear_order β] {s : set α} (hs : s.nonempty) {f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_bot) : ∃ a₀ ∈ s, ∀ a ∈ s, f a ≤ f a₀ := @filter.tendsto.exists_within_forall_le _ (order_dual β) _ _ hs _ hf lemma filter.tendsto.exists_forall_ge {α β : Type*} [nonempty α] [linear_order β] {f : α → β} (hf : tendsto f cofinite at_bot) : ∃ a₀, ∀ a, f a ≤ f a₀ := @filter.tendsto.exists_forall_le _ (order_dual β) _ _ _ hf /-- For an injective function `f`, inverse images of finite sets are finite. -/ lemma function.injective.tendsto_cofinite {α β : Type*} {f : α → β} (hf : function.injective f) : tendsto f cofinite cofinite := λ s h, h.preimage (hf.inj_on _)
d4dfd30740b46b3f068548b78f3c5a550c8397ba
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/abelian/transfer.lean
1ce54b6ef630ba86f5481e8a6893ac56193d5560
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,540
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.abelian.basic import category_theory.limits.preserves.shapes.kernels import category_theory.adjunction.limits /-! # Transferring "abelian-ness" across a functor If `C` is an additive category, `D` is an abelian category, we have `F : C ⥤ D` `G : D ⥤ C` (both preserving zero morphisms), `G` is left exact (that is, preserves finite limits), and further we have `adj : G ⊣ F` and `i : F ⋙ G ≅ 𝟭 C`, then `C` is also abelian. See <https://stacks.math.columbia.edu/tag/03A3> ## Notes The hypotheses, following the statement from the Stacks project, may appear suprising: we don't ask that the counit of the adjunction is an isomorphism, but just that we have some potentially unrelated isomorphism `i : F ⋙ G ≅ 𝟭 C`. However Lemma A1.1.1 from [Elephant] shows that in this situation the counit itself must be an isomorphism, and thus that `C` is a reflective subcategory of `D`. Someone may like to formalize that lemma, and restate this theorem in terms of `reflective`. (That lemma has a nice string diagrammatic proof that holds in any bicategory.) -/ noncomputable theory namespace category_theory open category_theory.limits universes v u₁ u₂ namespace abelian_of_adjunction variables {C : Type u₁} [category.{v} C] [preadditive C] variables {D : Type u₂} [category.{v} D] [abelian D] variables (F : C ⥤ D) variables (G : D ⥤ C) [functor.preserves_zero_morphisms G] variables (i : F ⋙ G ≅ 𝟭 C) (adj : G ⊣ F) include i /-- No point making this an instance, as it requires `i`. -/ lemma has_kernels [preserves_finite_limits G] : has_kernels C := { has_limit := λ X Y f, begin have := nat_iso.naturality_1 i f, simp at this, rw ←this, haveI : has_kernel (G.map (F.map f) ≫ i.hom.app _) := limits.has_kernel_comp_mono _ _, apply limits.has_kernel_iso_comp, end } include adj /-- No point making this an instance, as it requires `i` and `adj`. -/ lemma has_cokernels : has_cokernels C := { has_colimit := λ X Y f, begin haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits, have := nat_iso.naturality_1 i f, simp at this, rw ←this, haveI : has_cokernel (G.map (F.map f) ≫ i.hom.app _) := limits.has_cokernel_comp_iso _ _, apply limits.has_cokernel_epi_comp, end } variables [limits.has_cokernels C] /-- Auxiliary construction for `coimage_iso_image` -/ def cokernel_iso {X Y : C} (f : X ⟶ Y) : G.obj (cokernel (F.map f)) ≅ cokernel f := begin -- We have to write an explicit `preserves_colimits` type here, -- as `left_adjoint_preserves_colimits` has universe variables. haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits, calc G.obj (cokernel (F.map f)) ≅ cokernel (G.map (F.map f)) : (as_iso (cokernel_comparison _ G)).symm ... ≅ cokernel (_ ≫ f ≫ _) : cokernel_iso_of_eq (nat_iso.naturality_2 i f).symm ... ≅ cokernel (f ≫ _) : cokernel_epi_comp _ _ ... ≅ cokernel f : cokernel_comp_is_iso _ _ end variables [limits.has_kernels C] [preserves_finite_limits G] /-- Auxiliary construction for `coimage_iso_image` -/ def coimage_iso_image_aux {X Y : C} (f : X ⟶ Y) : kernel (G.map (cokernel.π (F.map f))) ≅ kernel (cokernel.π f) := begin haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits, calc kernel (G.map (cokernel.π (F.map f))) ≅ kernel (cokernel.π (G.map (F.map f)) ≫ cokernel_comparison (F.map f) G) : kernel_iso_of_eq (π_comp_cokernel_comparison _ _).symm ... ≅ kernel (cokernel.π (G.map (F.map f))) : kernel_comp_mono _ _ ... ≅ kernel (cokernel.π (_ ≫ f ≫ _) ≫ (cokernel_iso_of_eq _).hom) : kernel_iso_of_eq (π_comp_cokernel_iso_of_eq_hom (nat_iso.naturality_2 i f)).symm ... ≅ kernel (cokernel.π (_ ≫ f ≫ _)) : kernel_comp_mono _ _ ... ≅ kernel (cokernel.π (f ≫ i.inv.app Y) ≫ (cokernel_epi_comp (i.hom.app X) _).inv) : kernel_iso_of_eq (by simp only [cokernel.π_desc, cokernel_epi_comp_inv]) ... ≅ kernel (cokernel.π (f ≫ _)) : kernel_comp_mono _ _ ... ≅ kernel (inv (i.inv.app Y) ≫ cokernel.π f ≫ (cokernel_comp_is_iso f (i.inv.app Y)).inv) : kernel_iso_of_eq (by simp only [cokernel.π_desc, cokernel_comp_is_iso_inv, iso.hom_inv_id_app_assoc, nat_iso.inv_inv_app]) ... ≅ kernel (cokernel.π f ≫ _) : kernel_is_iso_comp _ _ ... ≅ kernel (cokernel.π f) : kernel_comp_mono _ _ end variables [functor.preserves_zero_morphisms F] /-- Auxiliary definition: the abelian coimage and abelian image agree. We still need to check that this agrees with the canonical morphism. -/ def coimage_iso_image {X Y : C} (f : X ⟶ Y) : abelian.coimage f ≅ abelian.image f := begin haveI : preserves_limits F := adj.right_adjoint_preserves_limits, haveI : preserves_colimits G := adj.left_adjoint_preserves_colimits, calc abelian.coimage f ≅ cokernel (kernel.ι f) : iso.refl _ ... ≅ G.obj (cokernel (F.map (kernel.ι f))) : (cokernel_iso _ _ i adj _).symm ... ≅ G.obj (cokernel (kernel_comparison f F ≫ (kernel.ι (F.map f)))) : G.map_iso (cokernel_iso_of_eq (by simp)) ... ≅ G.obj (cokernel (kernel.ι (F.map f))) : G.map_iso (cokernel_epi_comp _ _) ... ≅ G.obj (abelian.coimage (F.map f)) : iso.refl _ ... ≅ G.obj (abelian.image (F.map f)) : G.map_iso (abelian.coimage_iso_image _) ... ≅ G.obj (kernel (cokernel.π (F.map f))) : iso.refl _ ... ≅ kernel (G.map (cokernel.π (F.map f))) : preserves_kernel.iso _ _ ... ≅ kernel (cokernel.π f) : coimage_iso_image_aux F G i adj f ... ≅ abelian.image f : iso.refl _, end local attribute [simp] cokernel_iso coimage_iso_image coimage_iso_image_aux -- The account of this proof in the Stacks project omits this calculation. lemma coimage_iso_image_hom {X Y : C} (f : X ⟶ Y) : (coimage_iso_image F G i adj f).hom = abelian.coimage_image_comparison f := begin ext, simpa only [←G.map_comp_assoc, coimage_iso_image, nat_iso.inv_inv_app, cokernel_iso, coimage_iso_image_aux, iso.trans_symm, iso.symm_symm_eq, iso.refl_trans, iso.trans_refl, iso.trans_hom, iso.symm_hom, cokernel_comp_is_iso_inv, cokernel_epi_comp_inv, as_iso_hom, functor.map_iso_hom, cokernel_epi_comp_hom, preserves_kernel.iso_hom, kernel_comp_mono_hom, kernel_is_iso_comp_hom, cokernel_iso_of_eq_hom_comp_desc_assoc, cokernel.π_desc_assoc, category.assoc, π_comp_cokernel_iso_of_eq_inv_assoc, π_comp_cokernel_comparison_assoc, kernel.lift_ι, kernel.lift_ι_assoc, kernel_iso_of_eq_hom_comp_ι_assoc, kernel_comparison_comp_ι_assoc, abelian.coimage_image_factorisation] using nat_iso.naturality_1 i f end end abelian_of_adjunction open abelian_of_adjunction /-- If `C` is an additive category, `D` is an abelian category, we have `F : C ⥤ D` `G : D ⥤ C` (both preserving zero morphisms), `G` is left exact (that is, preserves finite limits), and further we have `adj : G ⊣ F` and `i : F ⋙ G ≅ 𝟭 C`, then `C` is also abelian. See <https://stacks.math.columbia.edu/tag/03A3> -/ def abelian_of_adjunction {C : Type u₁} [category.{v} C] [preadditive C] [has_finite_products C] {D : Type u₂} [category.{v} D] [abelian D] (F : C ⥤ D) [functor.preserves_zero_morphisms F] (G : D ⥤ C) [functor.preserves_zero_morphisms G] [preserves_finite_limits G] (i : F ⋙ G ≅ 𝟭 C) (adj : G ⊣ F) : abelian C := begin haveI := has_kernels F G i, haveI := has_cokernels F G i adj, haveI : ∀ {X Y : C} (f : X ⟶ Y), is_iso (abelian.coimage_image_comparison f), { intros X Y f, rw ←coimage_iso_image_hom F G i adj f, apply_instance, }, apply abelian.of_coimage_image_comparison_is_iso, end /-- If `C` is an additive category equivalent to an abelian category `D` via a functor that preserves zero morphisms, then `C` is also abelian. -/ def abelian_of_equivalence {C : Type u₁} [category.{v} C] [preadditive C] [has_finite_products C] {D : Type u₂} [category.{v} D] [abelian D] (F : C ⥤ D) [functor.preserves_zero_morphisms F] [is_equivalence F] : abelian C := abelian_of_adjunction F F.inv F.as_equivalence.unit_iso.symm F.as_equivalence.symm.to_adjunction end category_theory
51e4f3bc0efd749fc4e3f74f402fcec690242348
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/to_mathlib/localization/localization_of.lean
74f3ef85082f9f6c0db8e5fddf2807969c0fbbbb
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
969
lean
/- is_localization from is_localization_data. -/ import ring_theory.localization import to_mathlib.localization.localization_alt universe u open localization_alt variables {α : Type u} [comm_ring α] variables (S : set α) [is_submonoid S] open localization noncomputable lemma localization.of.is_localization_data : is_localization_data S (of : α → localization α S) := begin refine ⟨_, _, _⟩, { intros s, use [⟦⟨1, s⟩⟧], apply quotient.sound, use [1, is_submonoid.one_mem _], simp, }, { intros x, have Hx := quotient.exists_rep x, rcases (classical.indefinite_description _ Hx) with ⟨⟨p, q⟩, Hpq⟩, use [⟨q, p⟩], rw ←Hpq, apply quotient.sound, use [1, is_submonoid.one_mem _], simp, }, { intros x Hx, change localization.of x = 0 at Hx, erw quotient.eq at Hx, rcases Hx with ⟨s, ⟨Hs, Hx⟩⟩, simp at Hx, use [⟨⟨x, ⟨s, Hs⟩⟩, Hx⟩], } end
a22fcc2e68df6b05061abe2006ec2d2926634138
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Compiler/IR/Borrow.lean
baa8c9e602c24e1fdc3833ccec17918f99720950
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,049
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.Data.Nat import Init.Lean.Compiler.ExportAttr import Init.Lean.Compiler.IR.CompilerM import Init.Lean.Compiler.IR.NormIds namespace Lean namespace IR namespace Borrow namespace OwnedSet abbrev Key := FunId × Index def beq : Key → Key → Bool | (f₁, x₁), (f₂, x₂) => f₁ == f₂ && x₁ == x₂ instance : HasBeq Key := ⟨beq⟩ def getHash : Key → USize | (f, x) => mixHash (hash f) (hash x) instance : Hashable Key := ⟨getHash⟩ end OwnedSet abbrev OwnedSet := HashMap OwnedSet.Key Unit def OwnedSet.insert (s : OwnedSet) (k : OwnedSet.Key) : OwnedSet := s.insert k () def OwnedSet.contains (s : OwnedSet) (k : OwnedSet.Key) : Bool := s.contains k /- We perform borrow inference in a block of mutually recursive functions. Join points are viewed as local functions, and are identified using their local id + the name of the surrounding function. We keep a mapping from function and joint points to parameters (`Array Param`). Recall that `Param` contains the field `borrow`. -/ namespace ParamMap inductive Key | decl (name : FunId) | jp (name : FunId) (jpid : JoinPointId) def beq : Key → Key → Bool | Key.decl n₁, Key.decl n₂ => n₁ == n₂ | Key.jp n₁ id₁, Key.jp n₂ id₂ => n₁ == n₂ && id₁ == id₂ | _, _ => false instance : HasBeq Key := ⟨beq⟩ def getHash : Key → USize | Key.decl n => hash n | Key.jp n id => mixHash (hash n) (hash id) instance : Hashable Key := ⟨getHash⟩ end ParamMap abbrev ParamMap := HashMap ParamMap.Key (Array Param) def ParamMap.fmt (map : ParamMap) : Format := let fmts := map.fold (fun fmt k ps => let k := match k with | ParamMap.Key.decl n => format n | ParamMap.Key.jp n id => format n ++ ":" ++ format id; fmt ++ Format.line ++ k ++ " -> " ++ formatParams ps) Format.nil; "{" ++ (Format.nest 1 fmts) ++ "}" instance : HasFormat ParamMap := ⟨ParamMap.fmt⟩ instance : HasToString ParamMap := ⟨fun m => Format.pretty (format m)⟩ namespace InitParamMap /- Mark parameters that take a reference as borrow -/ def initBorrow (ps : Array Param) : Array Param := ps.map $ fun p => { p with borrow := p.ty.isObj } /- We do perform borrow inference for constants marked as `export`. Reason: we current write wrappers in C++ for using exported functions. These wrappers use smart pointers such as `object_ref`. When writing a new wrapper we need to know whether an argument is a borrow inference or not. We can revise this decision when we implement code for generating the wrappers automatically. -/ def initBorrowIfNotExported (exported : Bool) (ps : Array Param) : Array Param := if exported then ps else initBorrow ps partial def visitFnBody (fnid : FunId) : FnBody → StateM ParamMap Unit | FnBody.jdecl j xs v b => do modify $ fun m => m.insert (ParamMap.Key.jp fnid j) (initBorrow xs); visitFnBody v; visitFnBody b | FnBody.case _ _ _ alts => alts.forM $ fun alt => visitFnBody alt.body | e => unless (e.isTerminal) $ do let (instr, b) := e.split; visitFnBody b def visitDecls (env : Environment) (decls : Array Decl) : StateM ParamMap Unit := decls.forM $ fun decl => match decl with | Decl.fdecl f xs _ b => do let exported := isExport env f; modify $ fun m => m.insert (ParamMap.Key.decl f) (initBorrowIfNotExported exported xs); visitFnBody f b | _ => pure () end InitParamMap def mkInitParamMap (env : Environment) (decls : Array Decl) : ParamMap := (InitParamMap.visitDecls env decls *> get).run' {} /- Apply the inferred borrow annotations stored at `ParamMap` to a block of mutually recursive functions. -/ namespace ApplyParamMap partial def visitFnBody (fn : FunId) (paramMap : ParamMap) : FnBody → FnBody | FnBody.jdecl j xs v b => let v := visitFnBody v; let b := visitFnBody b; match paramMap.find? (ParamMap.Key.jp fn j) with | some ys => FnBody.jdecl j ys v b | none => unreachable! | FnBody.case tid x xType alts => FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody visitFnBody | e => if e.isTerminal then e else let (instr, b) := e.split; let b := visitFnBody b; instr.setBody b def visitDecls (decls : Array Decl) (paramMap : ParamMap) : Array Decl := decls.map $ fun decl => match decl with | Decl.fdecl f xs ty b => let b := visitFnBody f paramMap b; match paramMap.find? (ParamMap.Key.decl f) with | some xs => Decl.fdecl f xs ty b | none => unreachable! | other => other end ApplyParamMap def applyParamMap (decls : Array Decl) (map : ParamMap) : Array Decl := -- dbgTrace ("applyParamMap " ++ toString map) $ fun _ => ApplyParamMap.visitDecls decls map structure BorrowInfCtx := (env : Environment) (currFn : FunId := arbitrary _) -- Function being analyzed. (paramSet : IndexSet := {}) -- Set of all function parameters in scope. This is used to implement the heuristic at `ownArgsUsingParams` structure BorrowInfState := /- Set of variables that must be `owned`. -/ (owned : OwnedSet := {}) (modified : Bool := false) (paramMap : ParamMap) abbrev M := ReaderT BorrowInfCtx (StateM BorrowInfState) def getCurrFn : M FunId := do ctx ← read; pure ctx.currFn def markModified : M Unit := modify $ fun s => { s with modified := true } def ownVar (x : VarId) : M Unit := do -- dbgTrace ("ownVar " ++ toString x) $ fun _ => currFn ← getCurrFn; modify $ fun s => if s.owned.contains (currFn, x.idx) then s else { s with owned := s.owned.insert (currFn, x.idx), modified := true } def ownArg (x : Arg) : M Unit := match x with | Arg.var x => ownVar x | _ => pure () def ownArgs (xs : Array Arg) : M Unit := xs.forM ownArg def isOwned (x : VarId) : M Bool := do currFn ← getCurrFn; s ← get; pure $ s.owned.contains (currFn, x.idx) /- Updates `map[k]` using the current set of `owned` variables. -/ def updateParamMap (k : ParamMap.Key) : M Unit := do currFn ← getCurrFn; s ← get; match s.paramMap.find? k with | some ps => do ps ← ps.mapM $ fun (p : Param) => if !p.borrow then pure p else condM (isOwned p.x) (do markModified; pure { p with borrow := false }) (pure p); modify $ fun s => { s with paramMap := s.paramMap.insert k ps } | none => pure () def getParamInfo (k : ParamMap.Key) : M (Array Param) := do s ← get; match s.paramMap.find? k with | some ps => pure ps | none => match k with | ParamMap.Key.decl fn => do ctx ← read; match findEnvDecl ctx.env fn with | some decl => pure decl.params | none => unreachable! | _ => unreachable! /- For each ps[i], if ps[i] is owned, then mark xs[i] as owned. -/ def ownArgsUsingParams (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM $ fun i => do let x := xs.get! i; let p := ps.get! i; unless p.borrow $ ownArg x /- For each xs[i], if xs[i] is owned, then mark ps[i] as owned. We use this action to preserve tail calls. That is, if we have a tail call `f xs`, if the i-th parameter is borrowed, but `xs[i]` is owned we would have to insert a `dec xs[i]` after `f xs` and consequently "break" the tail call. -/ def ownParamsUsingArgs (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM $ fun i => do let x := xs.get! i; let p := ps.get! i; match x with | Arg.var x => whenM (isOwned x) $ ownVar p.x | _ => pure () /- Mark `xs[i]` as owned if it is one of the parameters `ps`. We use this action to mark function parameters that are being "packed" inside constructors. This is a heuristic, and is not related with the effectiveness of the reset/reuse optimization. It is useful for code such as ``` def f (x y : obj) := let z := ctor_1 x y; ret z ``` -/ def ownArgsIfParam (xs : Array Arg) : M Unit := do ctx ← read; xs.forM $ fun x => match x with | Arg.var x => when (ctx.paramSet.contains x.idx) $ ownVar x | _ => pure () def collectExpr (z : VarId) : Expr → M Unit | Expr.reset _ x => ownVar z *> ownVar x | Expr.reuse x _ _ ys => ownVar z *> ownVar x *> ownArgsIfParam ys | Expr.ctor _ xs => ownVar z *> ownArgsIfParam xs | Expr.proj _ x => do whenM (isOwned x) $ ownVar z; whenM (isOwned z) $ ownVar x | Expr.fap g xs => do ps ← getParamInfo (ParamMap.Key.decl g); -- dbgTrace ("collectExpr: " ++ toString g ++ " " ++ toString (formatParams ps)) $ fun _ => ownVar z *> ownArgsUsingParams xs ps | Expr.ap x ys => ownVar z *> ownVar x *> ownArgs ys | Expr.pap _ xs => ownVar z *> ownArgs xs | other => pure () def preserveTailCall (x : VarId) (v : Expr) (b : FnBody) : M Unit := do ctx ← read; match v, b with | (Expr.fap g ys), (FnBody.ret (Arg.var z)) => when (ctx.currFn == g && x == z) $ do -- dbgTrace ("preserveTailCall " ++ toString b) $ fun _ => do ps ← getParamInfo (ParamMap.Key.decl g); ownParamsUsingArgs ys ps | _, _ => pure () def updateParamSet (ctx : BorrowInfCtx) (ps : Array Param) : BorrowInfCtx := { ctx with paramSet := ps.foldl (fun s p => s.insert p.x.idx) ctx.paramSet } partial def collectFnBody : FnBody → M Unit | FnBody.jdecl j ys v b => do adaptReader (fun ctx => updateParamSet ctx ys) (collectFnBody v); ctx ← read; updateParamMap (ParamMap.Key.jp ctx.currFn j); collectFnBody b | FnBody.vdecl x _ v b => collectFnBody b *> collectExpr x v *> preserveTailCall x v b | FnBody.jmp j ys => do ctx ← read; ps ← getParamInfo (ParamMap.Key.jp ctx.currFn j); ownArgsUsingParams ys ps; -- for making sure the join point can reuse ownParamsUsingArgs ys ps -- for making sure the tail call is preserved | FnBody.case _ _ _ alts => alts.forM $ fun alt => collectFnBody alt.body | e => unless (e.isTerminal) $ collectFnBody e.body partial def collectDecl : Decl → M Unit | Decl.fdecl f ys _ b => adaptReader (fun ctx => let ctx := updateParamSet ctx ys; { ctx with currFn := f }) $ do collectFnBody b; updateParamMap (ParamMap.Key.decl f) | _ => pure () @[specialize] partial def whileModifingAux (x : M Unit) : Unit → M Unit | _ => do modify $ fun s => { s with modified := false }; -- s ← get; -- dbgTrace (toString s.map) $ fun _ => do x; s ← get; if s.modified then whileModifingAux () else pure () /- Keep executing `x` until it reaches a fixpoint -/ @[inline] def whileModifing (x : M Unit) : M Unit := whileModifingAux x () def collectDecls (decls : Array Decl) : M ParamMap := do whileModifing (decls.forM collectDecl); s ← get; pure s.paramMap def infer (env : Environment) (decls : Array Decl) : ParamMap := (collectDecls decls { env := env }).run' { paramMap := mkInitParamMap env decls } end Borrow def inferBorrow (decls : Array Decl) : CompilerM (Array Decl) := do env ← getEnv; let paramMap := Borrow.infer env decls; pure (Borrow.applyParamMap decls paramMap) end IR end Lean
3821b881add810ad9d96da425f0c4964bf20b4c0
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/rat/cast.lean
7c6d2bce183c1a92c22cca6a75c705c4b8625109
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
14,648
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order import data.int.char_zero import algebra.field.opposite /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ open_locale big_operators variables {F ι α β : Type*} namespace rat open_locale rat section with_div_ring variable [division_ring α] @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := (cast_def _).trans $ show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := by rw [← int.cast_coe_nat, cast_coe_int, int.cast_coe_nat] @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem cast_commute (r : ℚ) (a : α) : commute ↑r a := by simpa only [cast_def] using (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r := (cast_commute r a).eq theorem commute_cast (a : α) (r : ℚ) : commute a r := (r.cast_commute a).symm @[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul, int.cast_coe_nat]}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, rw [cast_def, div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 nat.cast_zero), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 nat.cast_zero), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv_rev, d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, (nat.cast_commute _ _).eq], simp [d₁0, mul_assoc] end @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := by simpa only [cast_def] using show (↑-n / d : α) = -(n / d), by rw [div_eq_mul_inv, div_eq_mul_inv, int.cast_neg, neg_mul_eq_neg_mul] @[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 nat.cast_zero), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 nat.cast_zero), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv_rev, d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [(d₁.commute_cast (_:α)).inv_right₀.eq] end @[simp] theorem cast_inv_nat (n : ℕ) : ((n⁻¹ : ℚ) : α) = n⁻¹ := begin cases n, { simp }, simp_rw [coe_nat_eq_mk, inv_def, mk, mk_nat, dif_neg n.succ_ne_zero, mk_pnat], simp [cast_def] end @[simp] theorem cast_inv_int (n : ℤ) : ((n⁻¹ : ℚ) : α) = n⁻¹ := begin cases n, { simp [cast_inv_nat] }, { simp only [int.cast_neg_succ_of_nat, ← nat.cast_succ, cast_neg, inv_neg, cast_inv_nat] } end @[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 int.cast_zero, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 nat.cast_zero), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂:α)).inv_left₀.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← int.cast_coe_nat d₁, ← int.cast_mul, ← int.cast_coe_nat d₂, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variables (α) [char_zero α] /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom : ⇑(cast_hom α) = coe := rfl @[simp, norm_cast] theorem cast_inv (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := map_inv₀ (cast_hom α) _ @[simp, norm_cast] theorem cast_div (m n) : ((m / n : ℚ) : α) = m / n := map_div₀ (cast_hom α) _ _ @[norm_cast] theorem cast_mk (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, norm_cast] theorem cast_pow (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k @[simp, norm_cast] lemma cast_list_sum (s : list ℚ) : (↑(s.sum) : α) = (s.map coe).sum := map_list_sum (rat.cast_hom α) _ @[simp, norm_cast] lemma cast_multiset_sum (s : multiset ℚ) : (↑(s.sum) : α) = (s.map coe).sum := map_multiset_sum (rat.cast_hom α) _ @[simp, norm_cast] lemma cast_sum (s : finset ι) (f : ι → ℚ) : (↑(∑ i in s, f i) : α) = ∑ i in s, f i := map_sum (rat.cast_hom α) _ _ @[simp, norm_cast] lemma cast_list_prod (s : list ℚ) : (↑(s.prod) : α) = (s.map coe).prod := map_list_prod (rat.cast_hom α) _ end with_div_ring section field variables [field α] [char_zero α] @[simp, norm_cast] lemma cast_multiset_prod (s : multiset ℚ) : (↑(s.prod) : α) = (s.map coe).prod := map_multiset_prod (rat.cast_hom α) _ @[simp, norm_cast] lemma cast_prod (s : finset ι) (f : ι → ℚ) : (↑(∏ i in s, f i) : α) = ∏ i in s, f i := map_prod (rat.cast_hom α) _ _ end field @[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := by { rw [num_denom', cast_mk, mk_eq_div, div_nonneg_iff, div_nonneg_iff], norm_cast } @[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := by rw [num_denom', cast_mk, mk_eq_div] @[simp] lemma cast_hom_rat : cast_hom ℚ = ring_hom.id ℚ := ring_hom.ext cast_id @[simp, norm_cast] theorem cast_min [linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min_def] @[simp, norm_cast] theorem cast_max [linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases b ≤ a; simp [h, max_def] @[simp, norm_cast] theorem cast_abs [linear_ordered_field α] {q : ℚ} : ((|q| : ℚ) : α) = |q| := by simp [abs_eq_max_neg] end rat open rat ring_hom lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r := calc f r = f (r.1 / r.2) : by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom] ... = f r.1 / f r.2 : map_div₀ f _ _ ... = r : by rw [map_nat_cast, map_int_cast, cast_def] -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer @[simp] lemma map_rat_cast [division_ring α] [division_ring β] [char_zero α] [ring_hom_class F α β] (f : F) (q : ℚ) : f q = q := ((f : α →+* β).comp $ cast_hom α).eq_rat_cast q lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g := begin ext r, refine rat.num_denom_cases_on' r _, intros a b b0, let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ), rw [rat.mk_eq_div, int.cast_coe_nat], have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0, have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ], calc f (a * b⁻¹) = f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) : by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul] ... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b] ... = g (a * b⁻¹) : by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹), ← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul] end instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) := ⟨ring_hom.ext_rat⟩ namespace monoid_with_zero_hom variables {M : Type*} [group_with_zero M] /-- If `f` and `g` agree on the integers then they are equal `φ`. See note [partially-applied ext lemmas] for why `comp` is used here. -/ @[ext] theorem ext_rat {f g : ℚ →*₀ M} (same_on_int : f.comp (int.cast_ring_hom ℚ).to_monoid_with_zero_hom = g.comp (int.cast_ring_hom ℚ).to_monoid_with_zero_hom) : f = g := begin have same_on_int' : ∀ k : ℤ, f k = g k := congr_fun same_on_int, ext x, rw [← @rat.num_denom x, rat.mk_eq_div, map_div₀ f, map_div₀ g, same_on_int' x.num, same_on_int' x.denom], end /-- Positive integer values of a morphism `φ` and its value on `-1` completely determine `φ`. -/ theorem ext_rat_on_pnat {f g : ℚ →*₀ M} (same_on_neg_one : f (-1) = g (-1)) (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g := ext_rat $ ext_int' (by simpa) ‹_› end monoid_with_zero_hom namespace mul_opposite variables [division_ring α] @[simp, norm_cast] lemma op_rat_cast (r : ℚ) : op (r : α) = (↑r : αᵐᵒᵖ) := by rw [cast_def, div_eq_mul_inv, op_mul, op_inv, op_nat_cast, op_int_cast, (commute.cast_int_right _ r.num).eq, cast_def, div_eq_mul_inv] @[simp, norm_cast] lemma unop_rat_cast (r : ℚ) : unop (r : αᵐᵒᵖ) = r := by rw [cast_def, div_eq_mul_inv, unop_mul, unop_inv, unop_nat_cast, unop_int_cast, (commute.cast_int_right _ r.num).eq, cast_def, div_eq_mul_inv] end mul_opposite
ac4f24dba17e0fe5f87ab892a9ac88ab28e3704d
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/algebra/group_with_zero.lean
4a82570d3f47c9e88c944bf54e3104550aae5263
[ "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
20,775
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.group.units import algebra.ring import tactic.push_neg /-! # Groups with an adjoined zero element This file describes structures that are not usually studied on their own right in mathematics, namely a special sort of monoid: apart from a distinguished “zero element” they form a group, or in other words, they are groups with an adjoined zero element. Examples are: * division rings; * the value monoid of a multiplicative valuation; * in particular, the non-negative real numbers. ## Main definitions * `group_with_zero` * `comm_group_with_zero` ## Implementation details As is usual in mathlib, we extend the inverse function to the zero element, and require `0⁻¹ = 0`. -/ set_option old_structure_cmd true section prio set_option default_priority 10 -- see Note [default priority] /-- A type `M` is a “monoid with zero” if it is a monoid with zero element. -/ @[protect_proj] class monoid_with_zero (G₀ : Type*) extends monoid G₀, mul_zero_class G₀. /-- A type `M` is a commutative “monoid with zero” if it is a commutative monoid with zero element. -/ @[protect_proj] class comm_monoid_with_zero (G₀ : Type*) extends comm_monoid G₀, monoid_with_zero G₀. /-- A type `G₀` is a “group with zero” if it is a monoid with zero element (distinct from `1`) such that every nonzero element is invertible. The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. Examples include division rings and the ordered monoids that are the target of valuations in general valuation theory.-/ class group_with_zero (G₀ : Type*) extends monoid_with_zero G₀, has_inv G₀ := (inv_zero : (0 : G₀)⁻¹ = 0) (mul_inv_cancel : ∀ a:G₀, a ≠ 0 → a * a⁻¹ = 1) (zero_ne_one : (0 : G₀) ≠ 1) instance group_with_zero.to_nonzero (G₀ : Type*) [group_with_zero G₀] : nonzero G₀ := ⟨group_with_zero.zero_ne_one⟩ /-- A type `G₀` is a commutative “group with zero” if it is a commutative monoid with zero element (distinct from `1`) such that every nonzero element is invertible. The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. -/ class comm_group_with_zero (G₀ : Type*) extends comm_monoid_with_zero G₀, group_with_zero G₀. /-- The division operation on a group with zero element. -/ instance group_with_zero.has_div {G₀ : Type*} [group_with_zero G₀] : has_div G₀ := ⟨λ g h, g * h⁻¹⟩ end prio lemma div_eq_mul_inv {G₀ : Type*} [group_with_zero G₀] {a b : G₀} : a / b = a * b⁻¹ := rfl section group_with_zero variables {G₀ : Type*} [group_with_zero G₀] @[simp] lemma inv_zero : (0 : G₀)⁻¹ = 0 := group_with_zero.inv_zero @[simp] lemma mul_inv_cancel' (a : G₀) (h : a ≠ 0) : a * a⁻¹ = 1 := group_with_zero.mul_inv_cancel a h @[simp] lemma mul_inv_cancel_assoc_left (a b : G₀) (h : b ≠ 0) : (a * b) * b⁻¹ = a := calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma mul_inv_cancel_assoc_right (a b : G₀) (h : a ≠ 0) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] lemma inv_ne_zero' {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 := assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel' a h @[simp] lemma inv_mul_cancel' (a : G₀) (h : a ≠ 0) : a⁻¹ * a = 1 := calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero' h] ... = a⁻¹ * a⁻¹⁻¹ : by simp [h] ... = 1 : by simp [inv_ne_zero' h] @[simp] lemma inv_mul_cancel_assoc_left (a b : G₀) (h : b ≠ 0) : (a * b⁻¹) * b = a := calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma inv_mul_cancel_assoc_right (a b : G₀) (h : a ≠ 0) : a⁻¹ * (a * b) = b := calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] @[simp] lemma inv_inv' (a : G₀) : a⁻¹⁻¹ = a := begin classical, by_cases h : a = 0, { simp [h] }, calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h] ... = a : by simp [inv_ne_zero' h] end /-- Multiplying `a` by itself and then by its inverse results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_assoc, mul_inv_cancel' a h, mul_one] } end /-- Multiplying `a` by its inverse and then by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_inv_cancel' a h, one_mul] } end /-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a` is zero). -/ @[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [inv_mul_cancel' a h, one_mul] } end /-- Multiplying `a` by itself and then dividing by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a := mul_self_mul_inv a /-- Dividing `a` by itself and then multiplying by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a := mul_inv_mul_self a lemma inv_involutive' : function.involutive (has_inv.inv : G₀ → G₀) := inv_inv' lemma ne_zero_of_mul_right_eq_one' (a b : G₀) (h : a * b = 1) : a ≠ 0 := assume a_eq_0, zero_ne_one (by simpa [a_eq_0] using h : (0:G₀) = 1) lemma ne_zero_of_mul_left_eq_one' (a b : G₀) (h : a * b = 1) : b ≠ 0 := assume b_eq_0, zero_ne_one (by simpa [b_eq_0] using h : (0:G₀) = 1) lemma eq_inv_of_mul_right_eq_one' (a b : G₀) (h : a * b = 1) : b = a⁻¹ := calc b = a⁻¹ * (a * b) : (inv_mul_cancel_assoc_right _ _ $ ne_zero_of_mul_right_eq_one' a b h).symm ... = a⁻¹ : by simp [h] lemma eq_inv_of_mul_left_eq_one' (a b : G₀) (h : a * b = 1) : a = b⁻¹ := calc a = (a * b) * b⁻¹ : (mul_inv_cancel_assoc_left _ _ (ne_zero_of_mul_left_eq_one' a b h)).symm ... = b⁻¹ : by simp [h] @[simp] lemma inv_one' : (1 : G₀)⁻¹ = 1 := eq.symm $ eq_inv_of_mul_right_eq_one' _ _ (mul_one 1) lemma inv_injective' : function.injective (@has_inv.inv G₀ _) := inv_involutive'.injective @[simp] lemma inv_inj'' (g h : G₀) : g⁻¹ = h⁻¹ ↔ g = h := ⟨assume H, inv_injective' H, congr_arg _⟩ lemma inv_eq_iff {g h : G₀} : g⁻¹ = h ↔ h⁻¹ = g := by rw [← inv_inj'', eq_comm, inv_inv'] @[simp] lemma coe_unit_mul_inv' (a : units G₀) : (a : G₀) * a⁻¹ = 1 := mul_inv_cancel' _ $ ne_zero_of_mul_right_eq_one' _ (a⁻¹ : units G₀) $ by simp @[simp] lemma coe_unit_inv_mul' (a : units G₀) : (a⁻¹ : G₀) * a = 1 := inv_mul_cancel' _ $ ne_zero_of_mul_right_eq_one' _ (a⁻¹ : units G₀) $ by simp @[simp] lemma unit_ne_zero (a : units G₀) : (a : G₀) ≠ 0 := assume a_eq_0, zero_ne_one $ calc 0 = (a : G₀) * a⁻¹ : by simp [a_eq_0] ... = 1 : by simp end group_with_zero namespace units variables {G₀ : Type*} [group_with_zero G₀] variables {a b : G₀} /-- Embed a non-zero element of a `group_with_zero` into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ := ⟨a, a⁻¹, mul_inv_cancel' _ ha, inv_mul_cancel' _ ha⟩ @[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl @[simp] theorem inv_eq_inv (u : units G₀) : (↑u⁻¹ : G₀) = u⁻¹ := (mul_right_inj u).1 $ by { rw [units.mul_inv, mul_inv_cancel'], apply unit_ne_zero } @[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u := units.ext rfl @[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, λ h, units.ext h⟩ @[simp] lemma exists_iff_ne_zero (x : G₀) : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 := ⟨λ ⟨u, hu⟩, by { rw ← hu, exact unit_ne_zero u }, assume hx, ⟨mk0 x hx, rfl⟩⟩ end units section group_with_zero variables {G₀ : Type*} [group_with_zero G₀] lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx) lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 := ⟨λ ⟨u, hu⟩, hu ▸ λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3, is_unit.mk0 x⟩ lemma mul_eq_zero' (a b : G₀) (h : a * b = 0) : a = 0 ∨ b = 0 := begin classical, contrapose! h, exact unit_ne_zero ((units.mk0 a h.1) * (units.mk0 b h.2)) end section prio set_option default_priority 10 -- see Note [default priority] instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ := { eq_zero_or_eq_zero_of_mul_eq_zero := mul_eq_zero', .. (‹_› : group_with_zero G₀) } end prio @[simp] lemma mul_eq_zero_iff' {a b : G₀} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨mul_eq_zero' a b, by rintro (H|H); simp [H]⟩ lemma mul_ne_zero'' {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := begin assume ab0, rw mul_eq_zero_iff' at ab0, cases ab0; contradiction end lemma mul_ne_zero_iff {a b : G₀} : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := by { classical, rw ← not_iff_not, push_neg, exact mul_eq_zero_iff' } lemma mul_left_cancel' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : x * y = x * z) : y = z := calc y = x⁻¹ * (x * y) : by rw inv_mul_cancel_assoc_right _ _ hx ... = x⁻¹ * (x * z) : by rw h ... = z : by rw inv_mul_cancel_assoc_right _ _ hx lemma mul_right_cancel' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y * x = z * x) : y = z := calc y = (y * x) * x⁻¹ : by rw mul_inv_cancel_assoc_left _ _ hx ... = (z * x) * x⁻¹ : by rw h ... = z : by rw mul_inv_cancel_assoc_left _ _ hx lemma mul_inv_eq_of_eq_mul' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y * x⁻¹ = z := h.symm ▸ (mul_inv_cancel_assoc_left z x hx) lemma eq_mul_inv_of_mul_eq' {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y * x⁻¹ := eq.symm $ mul_inv_eq_of_eq_mul' hx h.symm lemma mul_inv_rev' (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ := begin classical, by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, symmetry, apply eq_inv_of_mul_left_eq_one', simp [mul_assoc, hx, hy] end theorem inv_comm_of_comm' {a b : G₀} (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:G₀, a⁻¹ * x * a⁻¹) H.symm, classical, by_cases h : a = 0, { rw [h, inv_zero, zero_mul, mul_zero] }, rwa [inv_mul_cancel_assoc_right _ _ h, mul_assoc, mul_inv_cancel_assoc_left _ _ h] at this, end @[simp] lemma div_self' {a : G₀} (h : a ≠ 0) : a / a = 1 := mul_inv_cancel' _ h @[simp] lemma div_one' (a : G₀) : a / 1 = a := show a * 1⁻¹ = a, by rw [inv_one', mul_one] lemma one_div (a : G₀) : 1 / a = a⁻¹ := one_mul _ @[simp] lemma zero_div' (a : G₀) : 0 / a = 0 := zero_mul _ @[simp] lemma div_zero (a : G₀) : a / 0 = 0 := show a * 0⁻¹ = 0, by rw [inv_zero, mul_zero] @[simp] lemma div_mul_cancel' (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a := inv_mul_cancel_assoc_left a b h @[simp] lemma mul_div_cancel'' (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a := mul_inv_cancel_assoc_left a b h lemma mul_div_assoc'' {a b c : G₀} : a * b / c = a * (b / c) := mul_assoc _ _ _ local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm lemma div_eq_mul_one_div' (a b : G₀) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel' {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel' {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] lemma one_div_one' : 1 / 1 = (1:G₀) := div_self' (ne.symm zero_ne_one) lemma one_div_ne_zero' {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 := assume : 1 / a = 0, have 0 = (1:G₀), from eq.symm (by rw [← mul_one_div_cancel' h, this, mul_zero]), absurd this zero_ne_one lemma mul_ne_zero_comm'' {a b : G₀} (h : a * b ≠ 0) : b * a ≠ 0 := by { rw mul_ne_zero_iff at h ⊢, rwa and_comm } lemma eq_one_div_of_mul_eq_one' {a b : G₀} (h : a * b = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:G₀), by rwa [this, zero_mul] at h, absurd this zero_ne_one, have b = (1 / a) * a * b, by rw [one_div_mul_cancel' this, one_mul], show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this lemma eq_one_div_of_mul_eq_one_left' {a b : G₀} (h : b * a = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:G₀), by rwa [this, mul_zero] at h, absurd this zero_ne_one, by rw [← h, mul_div_assoc'', div_self' this, mul_one] @[simp] lemma one_div_div' (a b : G₀) : 1 / (a / b) = b / a := by rw [one_div, div_eq_mul_inv, mul_inv_rev', inv_inv', div_eq_mul_inv] @[simp] lemma one_div_one_div' (a : G₀) : 1 / (1 / a) = a := by simp lemma eq_of_one_div_eq_one_div' {a b : G₀} (h : 1 / a = 1 / b) : a = b := by rw [← one_div_one_div' a, h, one_div_one_div'] end group_with_zero section group_with_zero variables {G₀ : Type*} [group_with_zero G₀] variables {a b c : G₀} @[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 := by rw [inv_eq_iff, inv_zero, eq_comm] lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) := by simp only [div_eq_mul_inv, one_mul, mul_inv_rev'] theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u := congr_arg _ $ units.inv_eq_inv _ @[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div : (a / b)⁻¹ = b / a := (mul_inv_rev' _ _).trans (by rw inv_inv'; refl) lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ := (mul_inv_rev' _ _).symm lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := mul_ne_zero'' ha (inv_ne_zero' hb) lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 := ⟨mt (λ h, by rw [h, zero_div']), λ ha, div_ne_zero ha hb⟩ lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 := by haveI := classical.prop_decidable; exact not_iff_not.1 (div_ne_zero_iff hb) lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj] lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := by rw [← inv_inv' c, ← div_eq_mul_inv, ← div_eq_mul_inv, div_left_inj' (inv_ne_zero' hc)] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel' _ hb], λ h, by rw [← h, mul_div_cancel'' _ hb]⟩ end group_with_zero section comm_group_with_zero -- comm variables {G₀ : Type*} [comm_group_with_zero G₀] {a b c : G₀} lemma mul_inv'' : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev', mul_comm] lemma one_div_mul_one_div' (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [one_div_mul_one_div_rev, mul_comm b] lemma div_mul_right' {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b := eq.symm (calc 1 / b = a * ((1 / a) * (1 / b)) : by rw [← mul_assoc, one_div a, mul_inv_cancel' a ha, one_mul] ... = a * (1 / (b * a)) : by rw one_div_mul_one_div_rev ... = a * (a * b)⁻¹ : by rw [← one_div, mul_comm a b]) lemma div_mul_left' {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a := by rw [mul_comm a, div_mul_right' _ hb] lemma mul_div_cancel_left' {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b := by rw [mul_comm a, (mul_div_cancel'' _ ha)] lemma mul_div_cancel''' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel' _ hb)] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_mul_div' (a b c d : G₀) : (a / b) * (c / d) = (a * c) / (b * d) := by { simp [div_eq_mul_inv], rw [mul_inv_rev', mul_comm d⁻¹] } lemma mul_div_mul_left' (a b : G₀) {c : G₀} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [← div_mul_div', div_self' hc, one_mul] lemma mul_div_mul_right' (a b : G₀) {c : G₀} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, mul_div_mul_left' _ _ hc] lemma div_mul_eq_mul_div' (a b c : G₀) : (b / c) * a = (b * a) / c := by simp [div_eq_mul_inv] lemma div_mul_eq_mul_div_comm' (a b c : G₀) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div', ← one_mul c, ← div_mul_div', div_one', one_mul] lemma mul_eq_mul_of_div_eq_div' (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self' hb, ← div_mul_eq_mul_div_comm', h, div_mul_eq_mul_div', div_mul_cancel' _ hd] lemma div_div_eq_mul_div' (a b c : G₀) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div', one_div_div', ← mul_div_assoc''] lemma div_div_eq_div_mul' (a b c : G₀) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div', div_mul_div', mul_one] lemma div_div_div_div_eq' (a : G₀) {b c d : G₀} : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div', div_mul_eq_mul_div', div_div_eq_div_mul'] lemma div_mul_eq_div_mul_one_div' (a b c : G₀) : a / (b * c) = (a / b) * (1 / c) := by rw [← div_div_eq_div_mul', ← div_eq_mul_one_div'] /-- Dividing `a` by the result of dividing `a` by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_div_self (a : G₀) : a / (a / a) = a := begin rw div_div_eq_mul_div', exact mul_self_div_self a end lemma eq_of_mul_eq_mul_of_nonzero_left' {a b c : G₀} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c := by rw [← one_mul b, ← div_self' h, div_mul_eq_mul_div', h₂, mul_div_cancel_left' _ h] lemma eq_of_mul_eq_mul_of_nonzero_right' {a b c : G₀} (h : c ≠ 0) (h2 : a * c = b * c) : a = b := by rw [← mul_one a, ← div_self' h, ← mul_div_assoc'', h2, mul_div_cancel'' _ h] lemma ne_zero_of_one_div_ne_zero' {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero' {a : G₀} (h : 1 / a = 0) : a = 0 := classical.by_cases (assume ha, ha) (assume ha, false.elim ((one_div_ne_zero' ha) h)) lemma div_helper' {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rw [div_mul_eq_mul_div', one_mul, div_mul_right' _ h] end comm_group_with_zero section comm_group_with_zero variables {G₀ : Type*} [comm_group_with_zero G₀] {a b c d : G₀} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b := by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc]; refl lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc'', mul_div_right_comm] lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div', mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc'', mul_comm, mul_div_assoc''] lemma div_right_comm' (a : G₀) : (a / b) / c = (a / c) / b := by rw [div_div_eq_div_mul', div_div_eq_div_mul', mul_comm] lemma div_div_div_cancel_right' (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [div_div_eq_mul_div', div_mul_cancel' _ hc] lemma div_mul_div_cancel' (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc'', div_mul_cancel' _ hc] @[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) : by rw [mul_left_inj' (mul_ne_zero'' hb hd)] ... ↔ a * d = c * b : by rw [← mul_assoc, div_mul_cancel' _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel' _ hd] @[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div, mul_div_cancel''' _ ha] end comm_group_with_zero
add0836cf563fe6785540bdb0befb9757fb8594b
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/field_theory/galois.lean
f1460cb6a20461a59ab38a7b411a8b1b2e39cd65
[ "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
18,783
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.normal import field_theory.primitive_element import field_theory.fixed import ring_theory.power_basis /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `is_galois F E` where `E` is an extension of `F` - `fixed_field H` where `H : subgroup (E ≃ₐ[F] E)` - `fixing_subgroup K` where `K : intermediate_field F E` - `galois_correspondence` where `E/F` is finite dimensional and Galois ## Main results - `fixing_subgroup_of_fixed_field` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixing_subgroup (fixed_field H) = H` - `fixed_field_of_fixing_subgroup`: If `E/F` is finite dimensional and Galois then `fixed_field (fixing_subgroup K) = K` Together, these two result prove the Galois correspondence - `is_galois.tfae` : Equivalent characterizations of a Galois extension of finite degree -/ noncomputable theory open_locale classical open finite_dimensional alg_equiv section variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-- A field extension E/F is galois if it is both separable and normal -/ class is_galois : Prop := (separable' : is_separable F E) (normal' : normal F E) variables {F E} theorem is_galois_iff : is_galois F E ↔ is_separable F E ∧ normal F E := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ protected theorem is_galois.is_separable (h : is_galois F E) : is_separable F E := h.1 protected theorem is_galois.normal (h : is_galois F E) : normal F E := h.2 @[priority 100] -- see Note [lower instance priority] instance is_galois.normal'' [h : is_galois F E] : normal F E := h.2 variables (F E) namespace is_galois instance self : is_galois F F := ⟨is_separable_self F, normal_self F⟩ @[priority 100] -- see Note [lower instance priority] instance to_is_separable [h : is_galois F E] : is_separable F E := h.1 @[priority 100] -- see Note [lower instance priority] instance to_normal [h : is_galois F E] : normal F E := h.2 variables (F) {E} lemma integral [is_galois F E] (x : E) : is_integral F x := normal.is_integral' x lemma separable [h : is_galois F E] (x : E) : (minpoly F x).separable := h.is_separable.separable x lemma splits [is_galois F E] (x : E) : (minpoly F x).splits (algebra_map F E) := normal.splits' x variables (F E) instance of_fixed_field (G : Type*) [group G] [fintype G] [mul_semiring_action G E] : is_galois (mul_action.fixed_points G E) E := ⟨fixed_points.separable G E, fixed_points.normal G E⟩ lemma intermediate_field.adjoin_simple.card_aut_eq_findim [finite_dimensional F E] {α : E} (hα : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F F⟮α⟯)) : fintype.card (F⟮α⟯ ≃ₐ[F] F⟮α⟯) = findim F F⟮α⟯ := begin letI : fintype (F⟮α⟯ →ₐ[F] F⟮α⟯) := intermediate_field.fintype_of_alg_hom_adjoin_integral F hα, rw intermediate_field.adjoin.findim hα, rw ← intermediate_field.card_alg_hom_adjoin_integral F hα h_sep h_splits, exact fintype.card_congr (alg_equiv_equiv_alg_hom F F⟮α⟯) end lemma card_aut_eq_findim [finite_dimensional F E] [h : is_galois F E] : fintype.card (E ≃ₐ[F] E) = findim F E := begin cases field.exists_primitive_element h.1 with α hα, let iso : F⟮α⟯ ≃ₐ[F] E := { to_fun := λ e, e.val, inv_fun := λ e, ⟨e, by { rw hα, exact intermediate_field.mem_top }⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, rfl, map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, commutes' := λ _, rfl }, have H : is_integral F α := is_galois.integral F α, have h_sep : (minpoly F α).separable := is_galois.separable F α, have h_splits : (minpoly F α).splits (algebra_map F E) := is_galois.splits F α, replace h_splits : polynomial.splits (algebra_map F F⟮α⟯) (minpoly F α), { convert polynomial.splits_comp_of_splits (algebra_map F E) iso.symm.to_alg_hom.to_ring_hom h_splits }, rw ← linear_equiv.findim_eq iso.to_linear_equiv, rw ← intermediate_field.adjoin_simple.card_aut_eq_findim F E H h_sep h_splits, apply fintype.card_congr, apply equiv.mk (λ ϕ, iso.trans (trans ϕ iso.symm)) (λ ϕ, iso.symm.trans (trans ϕ iso)), { intro ϕ, ext1, simp only [trans_apply, apply_symm_apply] }, { intro ϕ, ext1, simp only [trans_apply, symm_apply_apply] }, end end is_galois end section is_galois_tower variables (F K E : Type*) [field F] [field K] [field E] {E' : Type*} [field E'] [algebra F E'] variables [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_galois.tower_top_of_is_galois [is_galois F E] : is_galois K E := ⟨is_separable_tower_top_of_is_separable F K E, normal.tower_top_of_normal F K E⟩ variables {F E} @[priority 100] -- see Note [lower instance priority] instance is_galois.tower_top_intermediate_field (K : intermediate_field F E) [h : is_galois F E] : is_galois K E := is_galois.tower_top_of_is_galois F K E lemma is_galois_iff_is_galois_bot : is_galois (⊥ : intermediate_field F E) E ↔ is_galois F E := begin split, { introI h, exact is_galois.tower_top_of_is_galois (⊥ : intermediate_field F E) F E }, { introI h, apply_instance }, end lemma is_galois.of_alg_equiv [h : is_galois F E] (f : E ≃ₐ[F] E') : is_galois F E' := ⟨is_separable.of_alg_hom F E f.symm, normal.of_alg_equiv f⟩ lemma alg_equiv.transfer_galois (f : E ≃ₐ[F] E') : is_galois F E ↔ is_galois F E' := ⟨λ h, by exactI is_galois.of_alg_equiv f, λ h, by exactI is_galois.of_alg_equiv f.symm⟩ lemma is_galois_iff_is_galois_top : is_galois F (⊤ : intermediate_field F E) ↔ is_galois F E := (intermediate_field.top_equiv).transfer_galois instance is_galois_bot : is_galois F (⊥ : intermediate_field F E) := intermediate_field.bot_equiv.transfer_galois.mpr (is_galois.self F) end is_galois_tower section galois_correspondence variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] variables (H : subgroup (E ≃ₐ[F] E)) (K : intermediate_field F E) namespace intermediate_field instance subgroup_action : faithful_mul_semiring_action H E := { smul := λ h x, h x, smul_zero := λ _, map_zero _, smul_add := λ _, map_add _, one_smul := λ _, rfl, smul_one := λ _, map_one _, mul_smul := λ _ _ _, rfl, smul_mul := λ _, map_mul _, eq_of_smul_eq_smul' := λ x y z, subtype.ext (alg_equiv.ext z) } /-- The intermediate_field fixed by a subgroup -/ def fixed_field : intermediate_field F E := { carrier := mul_action.fixed_points H E, zero_mem' := λ g, smul_zero g, add_mem' := λ a b hx hy g, by rw [smul_add g a b, hx, hy], neg_mem' := λ a hx g, by rw [smul_neg g a, hx], one_mem' := λ g, smul_one g, mul_mem' := λ a b hx hy g, by rw [smul_mul' g a b, hx, hy], inv_mem' := λ a hx g, by rw [smul_inv _ g a, hx], algebra_map_mem' := λ a g, commutes g a } lemma findim_fixed_field_eq_card [finite_dimensional F E] : findim (fixed_field H) E = fintype.card H := fixed_points.findim_eq_card H E /-- The subgroup fixing an intermediate_field -/ def fixing_subgroup : subgroup (E ≃ₐ[F] E) := { carrier := λ ϕ, ∀ x : K, ϕ x = x, one_mem' := λ _, rfl, mul_mem' := λ _ _ hx hy _, (congr_arg _ (hy _)).trans (hx _), inv_mem' := λ _ hx _, (equiv.symm_apply_eq (to_equiv _)).mpr (hx _).symm } lemma le_iff_le : K ≤ fixed_field H ↔ H ≤ fixing_subgroup K := ⟨λ h g hg x, h (subtype.mem x) ⟨g, hg⟩, λ h x hx g, h (subtype.mem g) ⟨x, hx⟩⟩ /-- The fixing_subgroup of `K : intermediate_field F E` is isomorphic to `E ≃ₐ[K] E` -/ def fixing_subgroup_equiv : fixing_subgroup K ≃* (E ≃ₐ[K] E) := { to_fun := λ ϕ, of_bijective (alg_hom.mk ϕ (map_one ϕ) (map_mul ϕ) (map_zero ϕ) (map_add ϕ) (ϕ.mem)) (bijective ϕ), inv_fun := λ ϕ, ⟨of_bijective (alg_hom.mk ϕ (ϕ.map_one) (ϕ.map_mul) (ϕ.map_zero) (ϕ.map_add) (λ r, ϕ.commutes (algebra_map F K r))) (ϕ.bijective), ϕ.commutes⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl }, map_mul' := λ _ _, by { ext, refl } } theorem fixing_subgroup_fixed_field [finite_dimensional F E] : fixing_subgroup (fixed_field H) = H := begin have H_le : H ≤ (fixing_subgroup (fixed_field H)) := (le_iff_le _ _).mp (le_refl _), suffices : fintype.card H = fintype.card (fixing_subgroup (fixed_field H)), { exact set_like.coe_injective (set.eq_of_inclusion_surjective ((fintype.bijective_iff_injective_and_card (set.inclusion H_le)).mpr ⟨set.inclusion_injective H_le, this⟩).2).symm }, apply fintype.card_congr, refine (fixed_points.to_alg_hom_equiv H E).trans _, refine (alg_equiv_equiv_alg_hom (fixed_field H) E).symm.trans _, exact (fixing_subgroup_equiv (fixed_field H)).to_equiv.symm end instance fixed_field.algebra : algebra K (fixed_field (fixing_subgroup K)) := { smul := λ x y, ⟨x*y, λ ϕ, by rw [smul_mul', (show ϕ • ↑x = ↑x, by exact subtype.mem ϕ x), (show ϕ • ↑y = ↑y, by exact subtype.mem y ϕ)]⟩, to_fun := λ x, ⟨x, λ ϕ, subtype.mem ϕ x⟩, map_zero' := rfl, map_add' := λ _ _, rfl, map_one' := rfl, map_mul' := λ _ _, rfl, commutes' := λ _ _, mul_comm _ _, smul_def' := λ _ _, rfl } instance fixed_field.is_scalar_tower : is_scalar_tower K (fixed_field (fixing_subgroup K)) E := ⟨λ _ _ _, mul_assoc _ _ _⟩ end intermediate_field namespace is_galois theorem fixed_field_fixing_subgroup [finite_dimensional F E] [h : is_galois F E] : intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) = K := begin have K_le : K ≤ intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) := (intermediate_field.le_iff_le _ _).mpr (le_refl _), suffices : findim K E = findim (intermediate_field.fixed_field (intermediate_field.fixing_subgroup K)) E, { exact (intermediate_field.eq_of_le_of_findim_eq' K_le this).symm }, rw [intermediate_field.findim_fixed_field_eq_card, fintype.card_congr (intermediate_field.fixing_subgroup_equiv K).to_equiv], exact (card_aut_eq_findim K E).symm, end lemma card_fixing_subgroup_eq_findim [finite_dimensional F E] [is_galois F E] : fintype.card (intermediate_field.fixing_subgroup K) = findim K E := by conv { to_rhs, rw [←fixed_field_fixing_subgroup K, intermediate_field.findim_fixed_field_eq_card] } /-- The Galois correspondence from intermediate fields to subgroups -/ def intermediate_field_equiv_subgroup [finite_dimensional F E] [is_galois F E] : intermediate_field F E ≃o order_dual (subgroup (E ≃ₐ[F] E)) := { to_fun := intermediate_field.fixing_subgroup, inv_fun := intermediate_field.fixed_field, left_inv := λ K, fixed_field_fixing_subgroup K, right_inv := λ H, intermediate_field.fixing_subgroup_fixed_field H, map_rel_iff' := λ K L, by { rw [←fixed_field_fixing_subgroup L, intermediate_field.le_iff_le, fixed_field_fixing_subgroup L, ←order_dual.dual_le], refl } } /-- The Galois correspondence as a galois_insertion -/ def galois_insertion_intermediate_field_subgroup [finite_dimensional F E] : galois_insertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ K _, intermediate_field.fixing_subgroup K, gc := λ K H, (intermediate_field.le_iff_le H K).symm, le_l_u := λ H, le_of_eq (intermediate_field.fixing_subgroup_fixed_field H).symm, choice_eq := λ K _, rfl } /-- The Galois correspondence as a galois_coinsertion -/ def galois_coinsertion_intermediate_field_subgroup [finite_dimensional F E] [is_galois F E] : galois_coinsertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ H _, intermediate_field.fixed_field H, gc := λ K H, (intermediate_field.le_iff_le H K).symm, u_l_le := λ K, le_of_eq (fixed_field_fixing_subgroup K), choice_eq := λ H _, rfl } end is_galois end galois_correspondence section galois_equivalent_definitions variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] namespace is_galois lemma is_separable_splitting_field [finite_dimensional F E] [h : is_galois F E] : ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E := begin cases field.exists_primitive_element h.1 with α h1, use [minpoly F α, separable F α, is_galois.splits F α], rw [eq_top_iff, ←intermediate_field.top_to_subalgebra, ←h1], rw intermediate_field.adjoin_simple_to_subalgebra_of_integral F α (integral F α), apply algebra.adjoin_mono, rw [set.singleton_subset_iff, finset.mem_coe, multiset.mem_to_finset, polynomial.mem_roots], { dsimp only [polynomial.is_root], rw [polynomial.eval_map, ←polynomial.aeval_def], exact minpoly.aeval _ _ }, { exact polynomial.map_ne_zero (minpoly.ne_zero (integral F α)) } end lemma of_fixed_field_eq_bot [finite_dimensional F E] (h : intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥) : is_galois F E := begin rw [←is_galois_iff_is_galois_bot, ←h], exact is_galois.of_fixed_field E (⊤ : subgroup (E ≃ₐ[F] E)), end lemma of_card_aut_eq_findim [finite_dimensional F E] (h : fintype.card (E ≃ₐ[F] E) = findim F E) : is_galois F E := begin apply of_fixed_field_eq_bot, have p : 0 < findim (intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E))) E := findim_pos, rw [←intermediate_field.findim_eq_one_iff, ←mul_left_inj' (ne_of_lt p).symm, findim_mul_findim, ←h, one_mul, intermediate_field.findim_fixed_field_eq_card], apply fintype.card_congr, exact { to_fun := λ g, ⟨g, subgroup.mem_top g⟩, inv_fun := coe, left_inv := λ g, rfl, right_inv := λ _, by { ext, refl } }, end variables {F} {E} {p : polynomial F} lemma of_separable_splitting_field_aux [hFE : finite_dimensional F E] [sp : p.is_splitting_field F E] (hp : p.separable) (K : intermediate_field F E) {x : E} (hx : x ∈ (p.map (algebra_map F E)).roots) : fintype.card ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) = fintype.card (K →ₐ[F] E) * findim K K⟮x⟯ := begin have h : is_integral K x := is_integral_of_is_scalar_tower x (is_integral_of_noetherian hFE x), have h1 : p ≠ 0 := λ hp, by rwa [hp, polynomial.map_zero, polynomial.roots_zero] at hx, have h2 : (minpoly K x) ∣ p.map (algebra_map F K), { apply minpoly.dvd, rw [polynomial.aeval_def, polynomial.eval₂_map, ←polynomial.eval_map], exact (polynomial.mem_roots (polynomial.map_ne_zero h1)).mp hx }, let key_equiv : ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) ≃ Σ (f : K →ₐ[F] E), @alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f) := equiv.trans (alg_equiv.arrow_congr (intermediate_field.lift2_alg_equiv K⟮x⟯) (alg_equiv.refl)) alg_hom_equiv_sigma, haveI : Π (f : K →ₐ[F] E), fintype (@alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f)) := λ f, by { apply fintype.of_injective (sigma.mk f) (λ _ _ H, eq_of_heq ((sigma.mk.inj H).2)), exact fintype.of_equiv _ key_equiv }, rw [fintype.card_congr key_equiv, fintype.card_sigma, intermediate_field.adjoin.findim h], apply finset.sum_const_nat, intros f hf, rw ← @intermediate_field.card_alg_hom_adjoin_integral K _ E _ _ x E _ (ring_hom.to_algebra f) h, { apply fintype.card_congr, refl }, { exact polynomial.separable.of_dvd ((polynomial.separable_map (algebra_map F K)).mpr hp) h2 }, { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero h1) _ h2, rw [polynomial.splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact sp.splits }, end lemma of_separable_splitting_field [sp : p.is_splitting_field F E] (hp : p.separable) : is_galois F E := begin haveI hFE : finite_dimensional F E := polynomial.is_splitting_field.finite_dimensional E p, let s := (p.map (algebra_map F E)).roots.to_finset, have adjoin_root : intermediate_field.adjoin F ↑s = ⊤, { apply intermediate_field.to_subalgebra_injective, rw [intermediate_field.top_to_subalgebra, ←top_le_iff, ←sp.adjoin_roots], apply intermediate_field.algebra_adjoin_le_adjoin, }, let P : intermediate_field F E → Prop := λ K, fintype.card (K →ₐ[F] E) = findim F K, suffices : P (intermediate_field.adjoin F ↑s), { rw adjoin_root at this, apply of_card_aut_eq_findim, rw ← eq.trans this (linear_equiv.findim_eq intermediate_field.top_equiv.to_linear_equiv), exact fintype.card_congr (equiv.trans (alg_equiv_equiv_alg_hom F E) (alg_equiv.arrow_congr intermediate_field.top_equiv.symm alg_equiv.refl)) }, apply intermediate_field.induction_on_adjoin_finset s P, { have key := intermediate_field.card_alg_hom_adjoin_integral F (show is_integral F (0 : E), by exact is_integral_zero), rw [minpoly.zero, polynomial.nat_degree_X] at key, specialize key polynomial.separable_X (polynomial.splits_X (algebra_map F E)), rw [←@subalgebra.findim_bot F E _ _ _, ←intermediate_field.bot_to_subalgebra] at key, refine eq.trans _ key, apply fintype.card_congr, rw intermediate_field.adjoin_zero }, intros K x hx hK, simp only [P] at *, rw [of_separable_splitting_field_aux hp K (multiset.mem_to_finset.mp hx), hK, findim_mul_findim], exact (linear_equiv.findim_eq (intermediate_field.lift2_alg_equiv K⟮x⟯).to_linear_equiv).symm, end /--Equivalent characterizations of a Galois extension of finite degree-/ theorem tfae [finite_dimensional F E] : tfae [is_galois F E, intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥, fintype.card (E ≃ₐ[F] E) = findim F E, ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E] := begin tfae_have : 1 → 2, { exact λ h, order_iso.map_bot (@intermediate_field_equiv_subgroup F _ E _ _ _ h).symm }, tfae_have : 1 → 3, { introI _, exact card_aut_eq_findim F E }, tfae_have : 1 → 4, { introI _, exact is_separable_splitting_field F E }, tfae_have : 2 → 1, { exact of_fixed_field_eq_bot F E }, tfae_have : 3 → 1, { exact of_card_aut_eq_findim F E }, tfae_have : 4 → 1, { rintros ⟨h, hp1, _⟩, exactI of_separable_splitting_field hp1 }, tfae_finish, end end is_galois end galois_equivalent_definitions
555751bd9ac09b64b90197519d18113e224ba3be
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0105/S0105.lean
e6d68d4929d1942392837b278f6be12927da45c2
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,108
lean
inductive zfc : Type | empty : zfc | insert : zfc → zfc → zfc instance : has_emptyc zfc := ⟨zfc.empty⟩ instance : has_insert zfc zfc := ⟨zfc.insert⟩ instance : has_zero zfc := ⟨{}⟩ instance : has_one zfc := ⟨{0}⟩ def succ (a : zfc) : zfc := has_insert.insert a a def zfc_add : zfc → zfc → zfc | m 0 := m | m (zfc.insert n p) := succ (zfc_add m n) instance : has_add zfc := ⟨zfc_add⟩ inductive member : zfc → zfc → Prop | left {a b c : zfc} : member a c → member a (has_insert.insert b c) | right {a b : zfc} : member a (has_insert.insert a b) instance : has_mem zfc zfc := ⟨member⟩ instance : has_subset zfc := ⟨(λ a b:zfc, (∀ z:zfc, z ∈ a → z ∈ b))⟩ axiom member.ext (a b : zfc) : (∀ x, x ∈ a ↔ x ∈ b) ↔ a=b export zfc export member definition A : zfc := {1,2,3,4,5} theorem M1F_Sheet01_Q05a_is_true : (1:zfc) ∈ A := begin left, left, left, left, right end theorem M1F_Sheet01_Q05b_is_false: ({1}:zfc) ∉ A := begin intro h, cases h, cases a_1, cases a_2, cases a_3, cases a_4, cases a_5 end theorem M1F_Sheet01_Q05c_is_true: ({1}:zfc) ⊆ A := begin intro x, intro h, cases h, cases a_1, left, left, left, left, right end theorem M1F_Sheet01_Q05d_is_true: ({1,2}:zfc) ⊆ A := begin intro x, intro h, cases h, cases a_1, cases a_2, left, left, left, left, right, left, left, left, right end theorem M1F_Sheet01_Q05e_is_true: ({1,2,1}:zfc) ⊆ A := begin intro x, intro h, cases h, cases a_1, cases a_2, cases a_3, left, left, left, left, right, left, left, left, right, left, left, left, left, right end theorem M1F_Sheet01_Q05f_is_false: ({1,1}:zfc) ∉ A := begin intro h, cases h, cases a_1, cases a_2, cases a_3, cases a_4, cases a_5 end theorem M1F_Sheet01_Q05g_is_false: A ∉ A := begin intro h, cases h, cases a_1, cases a_2, cases a_3, cases a_4, cases a_5 end theorem M1F_Sheet01_Q05h_is_true: A ⊇ A := begin intro h, exact id end
f7a02e8a5ae798a6666970a539cbeb926affb224
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebraic_geometry/presheafed_space/gluing.lean
94ef63d65c7281454dab1ffe224a854a0517b0c7
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
26,258
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import topology.gluing import algebraic_geometry.open_immersion import algebraic_geometry.locally_ringed_space.has_colimits /-! # Gluing Structured spaces Given a family of gluing data of structured spaces (presheafed spaces, sheafed spaces, or locally ringed spaces), we may glue them together. The construction should be "sealed" and considered as a black box, while only using the API provided. ## Main definitions * `algebraic_geometry.PresheafedSpace.glue_data`: A structure containing the family of gluing data. * `category_theory.glue_data.glued`: The glued presheafed space. This is defined as the multicoequalizer of `∐ V i j ⇉ ∐ U i`, so that the general colimit API can be used. * `category_theory.glue_data.ι`: The immersion `ι i : U i ⟶ glued` for each `i : J`. ## Main results * `algebraic_geometry.PresheafedSpace.glue_data.ι_is_open_immersion`: The map `ι i : U i ⟶ glued` is an open immersion for each `i : J`. * `algebraic_geometry.PresheafedSpace.glue_data.ι_jointly_surjective` : The underlying maps of `ι i : U i ⟶ glued` are jointly surjective. * `algebraic_geometry.PresheafedSpace.glue_data.V_pullback_cone_is_limit` : `V i j` is the pullback (intersection) of `U i` and `U j` over the glued space. Analogous results are also provided for `SheafedSpace` and `LocallyRingedSpace`. ## Implementation details Almost the whole file is dedicated to showing tht `ι i` is an open immersion. The fact that this is an open embedding of topological spaces follows from `topology.gluing.lean`, and it remains to construct `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_X, ι i '' U)` for each `U ⊆ U i`. Since `Γ(𝒪_X, ι i '' U)` is the the limit of `diagram_over_open`, the components of the structure sheafs of the spaces in the gluing diagram, we need to construct a map `ι_inv_app_π_app : Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_V, U_V)` for each `V` in the gluing diagram. We will refer to ![this diagram](https://i.imgur.com/P0phrwr.png) in the following doc strings. The `X` is the glued space, and the dotted arrow is a partial inverse guaranteed by the fact that it is an open immersion. The map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_{U_j}, _)` is given by the composition of the red arrows, and the map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_{V_{jk}}, _)` is given by the composition of the blue arrows. To lift this into a map from `Γ(𝒪_X, ι i '' U)`, we also need to show that these commute with the maps in the diagram (the green arrows), which is just a lengthy diagram-chasing. -/ noncomputable theory open topological_space category_theory opposite open category_theory.limits algebraic_geometry.PresheafedSpace open category_theory.glue_data namespace algebraic_geometry universes v u variables (C : Type u) [category.{v} C] namespace PresheafedSpace /-- A family of gluing data consists of 1. An index type `J` 2. A presheafed space `U i` for each `i : J`. 3. A presheafed space `V i j` for each `i j : J`. (Note that this is `J × J → PresheafedSpace C` rather than `J → J → PresheafedSpace C` to connect to the limits library easier.) 4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data (PresheafedSpace.{v} C) := (f_open : ∀ i j, is_open_immersion (f i j)) attribute [instance] glue_data.f_open namespace glue_data variables {C} (D : glue_data C) local notation `𝖣` := D.to_glue_data local notation `π₁` i `,` j `,` k := @pullback.fst _ _ _ _ _ (D.f i j) (D.f i k) _ local notation `π₂` i `,` j `,` k := @pullback.snd _ _ _ _ _ (D.f i j) (D.f i k) _ local notation `π₁⁻¹` i `,` j `,` k := (PresheafedSpace.is_open_immersion.pullback_fst_of_right (D.f i j) (D.f i k)).inv_app local notation `π₂⁻¹` i `,` j `,` k := (PresheafedSpace.is_open_immersion.pullback_snd_of_left (D.f i j) (D.f i k)).inv_app /-- The glue data of topological spaces associated to a family of glue data of PresheafedSpaces. -/ abbreviation to_Top_glue_data : Top.glue_data := { f_open := λ i j, (D.f_open i j).base_open, to_glue_data := 𝖣 .map_glue_data (forget C) } lemma ι_open_embedding [has_limits C] (i : D.J) : open_embedding (𝖣 .ι i).base := begin rw ← (show _ = (𝖣 .ι i).base, from 𝖣 .ι_glued_iso_inv (PresheafedSpace.forget _) _), exact open_embedding.comp (Top.homeo_of_iso (𝖣 .glued_iso (PresheafedSpace.forget _)).symm).open_embedding (D.to_Top_glue_data.ι_open_embedding i) end lemma pullback_base (i j k : D.J) (S : set (D.V (i, j)).carrier) : (π₂ i, j, k) '' ((π₁ i, j, k) ⁻¹' S) = D.f i k ⁻¹' (D.f i j '' S) := begin have eq₁ : _ = (π₁ i, j, k).base := preserves_pullback.iso_hom_fst (forget C) _ _, have eq₂ : _ = (π₂ i, j, k).base := preserves_pullback.iso_hom_snd (forget C) _ _, rw [coe_to_fun_eq, coe_to_fun_eq, ← eq₁, ← eq₂, coe_comp, set.image_comp, coe_comp, set.preimage_comp, set.image_preimage_eq, Top.pullback_snd_image_fst_preimage], refl, rw ← Top.epi_iff_surjective, apply_instance end /-- The red and the blue arrows in ![this diagram](https://i.imgur.com/0GiBUh6.png) commute. -/ @[simp, reassoc] lemma f_inv_app_f_app (i j k : D.J) (U : (opens (D.V (i, j)).carrier)) : (D.f_open i j).inv_app U ≫ (D.f i k).c.app _ = (π₁ i, j, k).c.app (op U) ≫ (π₂⁻¹ i, j, k) (unop _) ≫ (D.V _).presheaf.map (eq_to_hom (begin delta is_open_immersion.open_functor, dsimp only [functor.op, is_open_map.functor, opens.map, unop_op], congr, apply pullback_base, end)) := begin have := PresheafedSpace.congr_app (@pullback.condition _ _ _ _ _ (D.f i j) (D.f i k) _), dsimp only [comp_c_app] at this, rw [← cancel_epi (inv ((D.f_open i j).inv_app U)), is_iso.inv_hom_id_assoc, is_open_immersion.inv_inv_app], simp_rw category.assoc, erw [(π₁ i, j, k).c.naturality_assoc, reassoc_of this, ← functor.map_comp_assoc, is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app_assoc, ← (D.V (i, k)).presheaf.map_comp, ← (D.V (i, k)).presheaf.map_comp], convert (category.comp_id _).symm, erw (D.V (i, k)).presheaf.map_id, refl end /-- We can prove the `eq` along with the lemma. Thus this is bundled together here, and the lemma itself is separated below. -/ lemma snd_inv_app_t_app' (i j k : D.J) (U : opens (pullback (D.f i j) (D.f i k)).carrier) : ∃ eq, (π₂⁻¹ i, j, k) U ≫ (D.t k i).c.app _ ≫ (D.V (k, i)).presheaf.map (eq_to_hom eq) = (D.t' k i j).c.app _ ≫ (π₁⁻¹ k, j, i) (unop _) := begin split, rw [← is_iso.eq_inv_comp, is_open_immersion.inv_inv_app, category.assoc, (D.t' k i j).c.naturality_assoc], simp_rw ← category.assoc, erw ← comp_c_app, rw [congr_app (D.t_fac k i j), comp_c_app], simp_rw category.assoc, erw [is_open_immersion.inv_naturality, is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app'_assoc], simp_rw [← (𝖣 .V (k, i)).presheaf.map_comp, eq_to_hom_map (functor.op _), eq_to_hom_op, eq_to_hom_trans], rintros x ⟨y, hy, eq⟩, replace eq := concrete_category.congr_arg ((𝖣 .t i k).base) eq, change ((π₂ i, j, k) ≫ D.t i k).base y = (D.t k i ≫ D.t i k).base x at eq, rw [𝖣 .t_inv, id_base, Top.id_app] at eq, subst eq, use (inv (D.t' k i j)).base y, change ((inv (D.t' k i j)) ≫ (π₁ k, i, j)).base y = _, congr' 2, rw [is_iso.inv_comp_eq, 𝖣 .t_fac_assoc, 𝖣 .t_inv, category.comp_id] end /-- The red and the blue arrows in ![this diagram](https://i.imgur.com/q6X1GJ9.png) commute. -/ @[simp, reassoc] lemma snd_inv_app_t_app (i j k : D.J) (U : opens (pullback (D.f i j) (D.f i k)).carrier) : (π₂⁻¹ i, j, k) U ≫ (D.t k i).c.app _ = (D.t' k i j).c.app _ ≫ (π₁⁻¹ k, j, i) (unop _) ≫ (D.V (k, i)).presheaf.map (eq_to_hom (D.snd_inv_app_t_app' i j k U).some.symm) := begin have e := (D.snd_inv_app_t_app' i j k U).some_spec, reassoc! e, rw ← e, simp [eq_to_hom_map], end variable [has_limits C] lemma ι_image_preimage_eq (i j : D.J) (U : opens (D.U i).carrier) : (opens.map (𝖣 .ι j).base).obj ((D.ι_open_embedding i).is_open_map.functor.obj U) = (D.f_open j i).open_functor.obj ((opens.map (𝖣 .t j i).base).obj ((opens.map (𝖣 .f i j).base).obj U)) := begin dsimp only [opens.map, is_open_map.functor], congr' 1, rw [← (show _ = (𝖣 .ι i).base, from 𝖣 .ι_glued_iso_inv (PresheafedSpace.forget _) i), ← (show _ = (𝖣 .ι j).base, from 𝖣 .ι_glued_iso_inv (PresheafedSpace.forget _) j), coe_comp, coe_comp, set.image_comp, set.preimage_comp, set.preimage_image_eq], refine eq.trans (D.to_Top_glue_data.preimage_image_eq_image' _ _ _) _, rw [coe_comp, set.image_comp], congr' 1, erw set.eq_preimage_iff_image_eq, rw ← set.image_comp, change (D.t i j ≫ D.t j i).base '' _ = _, rw 𝖣 .t_inv, { simp }, { change function.bijective (Top.homeo_of_iso (as_iso _)), exact homeomorph.bijective _, apply_instance }, { rw ← Top.mono_iff_injective, apply_instance } end /-- (Implementation). The map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_{U_j}, 𝖣.ι j ⁻¹' (𝖣.ι i '' U))` -/ def opens_image_preimage_map (i j : D.J) (U : opens (D.U i).carrier) : (D.U i).presheaf.obj (op U) ⟶ (D.U j).presheaf.obj _ := (D.f i j).c.app (op U) ≫ (D.t j i).c.app _ ≫ (D.f_open j i).inv_app (unop _) ≫ (𝖣 .U j).presheaf.map (eq_to_hom (D.ι_image_preimage_eq i j U)).op lemma opens_image_preimage_map_app' (i j k : D.J) (U : opens (D.U i).carrier) : ∃ eq, D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ = ((π₁ j, i, k) ≫ D.t j i ≫ D.f i j).c.app (op U) ≫ (π₂⁻¹ j, i, k) (unop _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom eq) := begin split, delta opens_image_preimage_map, simp_rw category.assoc, rw [(D.f j k).c.naturality, f_inv_app_f_app_assoc], erw ← (D.V (j, k)).presheaf.map_comp, simp_rw ← category.assoc, erw [← comp_c_app, ← comp_c_app], simp_rw category.assoc, dsimp only [functor.op, unop_op, quiver.hom.unop_op], rw [eq_to_hom_map (opens.map _), eq_to_hom_op, eq_to_hom_trans], congr end /-- The red and the blue arrows in ![this diagram](https://i.imgur.com/mBzV1Rx.png) commute. -/ lemma opens_image_preimage_map_app (i j k : D.J) (U : opens (D.U i).carrier) : D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ = ((π₁ j, i, k) ≫ D.t j i ≫ D.f i j).c.app (op U) ≫ (π₂⁻¹ j, i, k) (unop _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom ((opens_image_preimage_map_app' D i j k U).some)) := (opens_image_preimage_map_app' D i j k U).some_spec -- This is proved separately since `reassoc` somehow timeouts. lemma opens_image_preimage_map_app_assoc (i j k : D.J) (U : opens (D.U i).carrier) {X' : C} (f' : _ ⟶ X') : D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ ≫ f' = ((π₁ j, i, k) ≫ D.t j i ≫ D.f i j).c.app (op U) ≫ (π₂⁻¹ j, i, k) (unop _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom ((opens_image_preimage_map_app' D i j k U).some)) ≫ f' := by simpa only [category.assoc] using congr_arg (λ g, g ≫ f') (opens_image_preimage_map_app D i j k U) /-- (Implementation) Given an open subset of one of the spaces `U ⊆ Uᵢ`, the sheaf component of the image `ι '' U` in the glued space is the limit of this diagram. -/ abbreviation diagram_over_open {i : D.J} (U : opens (D.U i).carrier) : (walking_multispan _ _)ᵒᵖ ⥤ C := componentwise_diagram 𝖣 .diagram.multispan ((D.ι_open_embedding i).is_open_map.functor.obj U) /-- (Implementation) The projection from the limit of `diagram_over_open` to a component of `D.U j`. -/ abbreviation diagram_over_open_π {i : D.J} (U : opens (D.U i).carrier) (j : D.J) := limit.π (D.diagram_over_open U) (op (walking_multispan.right j)) /-- (Implementation) We construct the map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_V, U_V)` for each `V` in the gluing diagram. We will lift these maps into `ι_inv_app`. -/ def ι_inv_app_π_app {i : D.J} (U : opens (D.U i).carrier) (j) : (𝖣 .U i).presheaf.obj (op U) ⟶ (D.diagram_over_open U).obj (op j) := begin rcases j with (⟨j, k⟩|j), { refine D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ ≫ (D.V (j, k)).presheaf.map (eq_to_hom _), dsimp only [functor.op, opens.map, unop_op], congr' 2, rw set.preimage_preimage, change (D.f j k ≫ 𝖣 .ι j).base ⁻¹' _ = _, congr' 3, exact colimit.w 𝖣 .diagram.multispan (walking_multispan.hom.fst (j, k)) }, { exact D.opens_image_preimage_map i j U } end /-- (Implementation) The natural map `Γ(𝒪_{U_i}, U) ⟶ Γ(𝒪_X, 𝖣.ι i '' U)`. This forms the inverse of `(𝖣.ι i).c.app (op U)`. -/ def ι_inv_app {i : D.J} (U : opens (D.U i).carrier) : (D.U i).presheaf.obj (op U) ⟶ limit (D.diagram_over_open U) := limit.lift (D.diagram_over_open U) { X := (D.U i).presheaf.obj (op U), π := { app := λ j, D.ι_inv_app_π_app U (unop j), naturality' := λ X Y f', begin induction X using opposite.rec, induction Y using opposite.rec, let f : Y ⟶ X := f'.unop, have : f' = f.op := rfl, clear_value f, subst this, rcases f with (_|⟨j,k⟩|⟨j,k⟩), { erw [category.id_comp, category_theory.functor.map_id], rw category.comp_id }, { erw category.id_comp, congr' 1 }, erw category.id_comp, -- It remains to show that the blue is equal to red + green in the original diagram. -- The proof strategy is illustrated in ![this diagram](https://i.imgur.com/mBzV1Rx.png) -- where we prove red = pink = light-blue = green = blue. change D.opens_image_preimage_map i j U ≫ (D.f j k).c.app _ ≫ (D.V (j, k)).presheaf.map (eq_to_hom _) = D.opens_image_preimage_map _ _ _ ≫ ((D.f k j).c.app _ ≫ (D.t j k).c.app _) ≫ (D.V (j, k)).presheaf.map (eq_to_hom _), erw opens_image_preimage_map_app_assoc, simp_rw category.assoc, erw [opens_image_preimage_map_app_assoc, (D.t j k).c.naturality_assoc], rw snd_inv_app_t_app_assoc, erw ← PresheafedSpace.comp_c_app_assoc, -- light-blue = green is relatively easy since the part that differs does not involve -- partial inverses. have : D.t' j k i ≫ (π₁ k, i, j) ≫ D.t k i ≫ 𝖣 .f i k = (pullback_symmetry _ _).hom ≫ (π₁ j, i, k) ≫ D.t j i ≫ D.f i j, { rw [← 𝖣 .t_fac_assoc, 𝖣 .t'_comp_eq_pullback_symmetry_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.condition, 𝖣 .t_fac_assoc] }, rw congr_app this, erw PresheafedSpace.comp_c_app_assoc (pullback_symmetry _ _).hom, simp_rw category.assoc, congr' 1, rw ← is_iso.eq_inv_comp, erw is_open_immersion.inv_inv_app, simp_rw category.assoc, erw [nat_trans.naturality_assoc, ← PresheafedSpace.comp_c_app_assoc, congr_app (pullback_symmetry_hom_comp_snd _ _)], simp_rw category.assoc, erw [is_open_immersion.inv_naturality_assoc, is_open_immersion.inv_naturality_assoc, is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app_assoc], repeat { erw ← (D.V (j, k)).presheaf.map_comp }, congr, end } } /-- `ι_inv_app` is the left inverse of `D.ι i` on `U`. -/ lemma ι_inv_app_π {i : D.J} (U : opens (D.U i).carrier) : ∃ eq, D.ι_inv_app U ≫ D.diagram_over_open_π U i = (D.U i).presheaf.map (eq_to_hom eq) := begin split, delta ι_inv_app, rw limit.lift_π, change D.opens_image_preimage_map i i U = _, dsimp [opens_image_preimage_map], rw [congr_app (D.t_id _), id_c_app, ← functor.map_comp], erw [is_open_immersion.inv_naturality_assoc, is_open_immersion.app_inv_app'_assoc], simp only [eq_to_hom_op, eq_to_hom_trans, eq_to_hom_map (functor.op _), ← functor.map_comp], rw set.range_iff_surjective.mpr _, { simp }, { rw ← Top.epi_iff_surjective, apply_instance } end /-- The `eq_to_hom` given by `ι_inv_app_π`. -/ abbreviation ι_inv_app_π_eq_map {i : D.J} (U : opens (D.U i).carrier) := (D.U i).presheaf.map (eq_to_iso (D.ι_inv_app_π U).some).inv /-- `ι_inv_app` is the right inverse of `D.ι i` on `U`. -/ lemma π_ι_inv_app_π (i j : D.J) (U : opens (D.U i).carrier) : D.diagram_over_open_π U i ≫ D.ι_inv_app_π_eq_map U ≫ D.ι_inv_app U ≫ D.diagram_over_open_π U j = D.diagram_over_open_π U j := begin rw ← cancel_mono ((componentwise_diagram 𝖣 .diagram.multispan _).map (quiver.hom.op (walking_multispan.hom.snd (i, j))) ≫ (𝟙 _)), simp_rw category.assoc, rw limit.w_assoc, erw limit.lift_π_assoc, rw [category.comp_id, category.comp_id], change _ ≫ _ ≫ (_ ≫ _) ≫ _ = _, rw [congr_app (D.t_id _), id_c_app], simp_rw category.assoc, rw [← functor.map_comp_assoc, is_open_immersion.inv_naturality_assoc], erw is_open_immersion.app_inv_app_assoc, iterate 3 { rw ← functor.map_comp_assoc }, rw nat_trans.naturality_assoc, erw ← (D.V (i, j)).presheaf.map_comp, convert limit.w (componentwise_diagram 𝖣 .diagram.multispan _) (quiver.hom.op (walking_multispan.hom.fst (i, j))), { rw category.comp_id, apply_with mono_comp { instances := ff }, change mono ((_ ≫ D.f j i).c.app _), rw comp_c_app, apply_with mono_comp { instances := ff }, erw D.ι_image_preimage_eq i j U, all_goals { apply_instance } }, end /-- `ι_inv_app` is the inverse of `D.ι i` on `U`. -/ lemma π_ι_inv_app_eq_id (i : D.J) (U : opens (D.U i).carrier) : D.diagram_over_open_π U i ≫ D.ι_inv_app_π_eq_map U ≫ D.ι_inv_app U = 𝟙 _ := begin ext j, induction j using opposite.rec, rcases j with (⟨j, k⟩|⟨j⟩), { rw [← limit.w (componentwise_diagram 𝖣 .diagram.multispan _) (quiver.hom.op (walking_multispan.hom.fst (j, k))), ← category.assoc, category.id_comp], congr' 1, simp_rw category.assoc, apply π_ι_inv_app_π }, { simp_rw category.assoc, rw category.id_comp, apply π_ι_inv_app_π } end instance componentwise_diagram_π_is_iso (i : D.J) (U : opens (D.U i).carrier) : is_iso (D.diagram_over_open_π U i) := begin use D.ι_inv_app_π_eq_map U ≫ D.ι_inv_app U, split, { apply π_ι_inv_app_eq_id }, { rw [category.assoc, (D.ι_inv_app_π _).some_spec], exact iso.inv_hom_id ((D.to_glue_data.U i).presheaf.map_iso (eq_to_iso _)) } end instance ι_is_open_immersion (i : D.J) : is_open_immersion (𝖣 .ι i) := { base_open := D.ι_open_embedding i, c_iso := λ U, by { erw ← colimit_presheaf_obj_iso_componentwise_limit_hom_π, apply_instance } } /-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`. Vᵢⱼ ⟶ Uᵢ | | ↓ ↓ Uⱼ ⟶ X -/ def V_pullback_cone_is_limit (i j : D.J) : is_limit (𝖣 .V_pullback_cone i j) := pullback_cone.is_limit_aux' _ $ λ s, begin refine ⟨_, _, _, _⟩, { refine PresheafedSpace.is_open_immersion.lift (D.f i j) s.fst _, erw ← D.to_Top_glue_data.preimage_range j i, have : s.fst.base ≫ D.to_Top_glue_data.to_glue_data.ι i = s.snd.base ≫ D.to_Top_glue_data.to_glue_data.ι j, { rw [← 𝖣 .ι_glued_iso_hom (PresheafedSpace.forget _) _, ← 𝖣 .ι_glued_iso_hom (PresheafedSpace.forget _) _], have := congr_arg PresheafedSpace.hom.base s.condition, rw [comp_base, comp_base] at this, reassoc! this, exact this _ }, rw [← set.image_subset_iff, ← set.image_univ, ← set.image_comp, set.image_univ, ← coe_comp, this, coe_comp, ← set.image_univ, set.image_comp], exact set.image_subset_range _ _ }, { apply is_open_immersion.lift_fac }, { rw [← cancel_mono (𝖣 .ι j), category.assoc, ← (𝖣 .V_pullback_cone i j).condition], conv_rhs { rw ← s.condition }, erw is_open_immersion.lift_fac_assoc }, { intros m e₁ e₂, rw ← cancel_mono (D.f i j), erw e₁, rw is_open_immersion.lift_fac } end lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ (i : D.J) (y : D.U i), (𝖣 .ι i).base y = x := 𝖣 .ι_jointly_surjective (PresheafedSpace.forget _ ⋙ category_theory.forget Top) x end glue_data end PresheafedSpace namespace SheafedSpace variables (C) [has_products.{v} C] /-- A family of gluing data consists of 1. An index type `J` 2. A sheafed space `U i` for each `i : J`. 3. A sheafed space `V i j` for each `i j : J`. (Note that this is `J × J → SheafedSpace C` rather than `J → J → SheafedSpace C` to connect to the limits library easier.) 4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data (SheafedSpace.{v} C) := (f_open : ∀ i j, SheafedSpace.is_open_immersion (f i j)) attribute [instance] glue_data.f_open namespace glue_data variables {C} (D : glue_data C) local notation `𝖣` := D.to_glue_data /-- The glue data of presheafed spaces associated to a family of glue data of sheafed spaces. -/ abbreviation to_PresheafedSpace_glue_data : PresheafedSpace.glue_data C := { f_open := D.f_open, to_glue_data := 𝖣 .map_glue_data forget_to_PresheafedSpace } variable [has_limits C] /-- The gluing as sheafed spaces is isomorphic to the gluing as presheafed spaces. -/ abbreviation iso_PresheafedSpace : 𝖣 .glued.to_PresheafedSpace ≅ D.to_PresheafedSpace_glue_data.to_glue_data.glued := 𝖣 .glued_iso forget_to_PresheafedSpace lemma ι_iso_PresheafedSpace_inv (i : D.J) : D.to_PresheafedSpace_glue_data.to_glue_data.ι i ≫ D.iso_PresheafedSpace.inv = 𝖣 .ι i := 𝖣 .ι_glued_iso_inv _ _ instance ι_is_open_immersion (i : D.J) : is_open_immersion (𝖣 .ι i) := by { rw ← D.ι_iso_PresheafedSpace_inv, apply_instance } lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ (i : D.J) (y : D.U i), (𝖣 .ι i).base y = x := 𝖣 .ι_jointly_surjective (SheafedSpace.forget _ ⋙ category_theory.forget Top) x /-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`. Vᵢⱼ ⟶ Uᵢ | | ↓ ↓ Uⱼ ⟶ X -/ def V_pullback_cone_is_limit (i j : D.J) : is_limit (𝖣 .V_pullback_cone i j) := 𝖣 .V_pullback_cone_is_limit_of_map forget_to_PresheafedSpace i j (D.to_PresheafedSpace_glue_data.V_pullback_cone_is_limit _ _) end glue_data end SheafedSpace namespace LocallyRingedSpace /-- A family of gluing data consists of 1. An index type `J` 2. A locally ringed space `U i` for each `i : J`. 3. A locally ringed space `V i j` for each `i j : J`. (Note that this is `J × J → LocallyRingedSpace` rather than `J → J → LocallyRingedSpace` to connect to the limits library easier.) 4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. We can then glue the spaces `U i` together by identifying `V i j` with `V j i`, such that the `U i`'s are open subspaces of the glued space. -/ @[nolint has_nonempty_instance] structure glue_data extends glue_data LocallyRingedSpace := (f_open : ∀ i j, LocallyRingedSpace.is_open_immersion (f i j)) attribute [instance] glue_data.f_open namespace glue_data variables (D : glue_data) local notation `𝖣` := D.to_glue_data /-- The glue data of ringed spaces associated to a family of glue data of locally ringed spaces. -/ abbreviation to_SheafedSpace_glue_data : SheafedSpace.glue_data CommRing := { f_open := D.f_open, to_glue_data := 𝖣 .map_glue_data forget_to_SheafedSpace } /-- The gluing as locally ringed spaces is isomorphic to the gluing as ringed spaces. -/ abbreviation iso_SheafedSpace : 𝖣 .glued.to_SheafedSpace ≅ D.to_SheafedSpace_glue_data.to_glue_data.glued := 𝖣 .glued_iso forget_to_SheafedSpace lemma ι_iso_SheafedSpace_inv (i : D.J) : D.to_SheafedSpace_glue_data.to_glue_data.ι i ≫ D.iso_SheafedSpace.inv = (𝖣 .ι i).1 := 𝖣 .ι_glued_iso_inv forget_to_SheafedSpace i instance ι_is_open_immersion (i : D.J) : is_open_immersion (𝖣 .ι i) := by { delta is_open_immersion, rw ← D.ι_iso_SheafedSpace_inv, apply PresheafedSpace.is_open_immersion.comp } instance (i j k : D.J) : preserves_limit (cospan (𝖣 .f i j) (𝖣 .f i k)) forget_to_SheafedSpace := infer_instance lemma ι_jointly_surjective (x : 𝖣 .glued) : ∃ (i : D.J) (y : D.U i), (𝖣 .ι i).1.base y = x := 𝖣 .ι_jointly_surjective ((LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget _) ⋙ forget Top) x /-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`. Vᵢⱼ ⟶ Uᵢ | | ↓ ↓ Uⱼ ⟶ X -/ def V_pullback_cone_is_limit (i j : D.J) : is_limit (𝖣 .V_pullback_cone i j) := 𝖣 .V_pullback_cone_is_limit_of_map forget_to_SheafedSpace i j (D.to_SheafedSpace_glue_data.V_pullback_cone_is_limit _ _) end glue_data end LocallyRingedSpace end algebraic_geometry
6eb9f3b1b071dedb2292635dafecca43b293f239
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/well_founded_set.lean
5ae940977844e4c6d77123a73404059ac36e3ebd
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
29,096
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.antichain import order.order_iso_nat import order.well_founded /-! # Well-founded sets A well-founded subset of an ordered type is one on which the relation `<` is well-founded. ## Main Definitions * `set.well_founded_on s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `set.is_wf s` indicates that `<` is well-founded when restricted to `s`. * `set.partially_well_ordered_on s r` indicates that the relation `r` is partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`. * `set.is_pwo s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. Note that this is equivalent to containing only two comparable elements. ## Main Results * Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`, shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially well-ordered on the set of lists of elements of `s`. The result was originally published by Higman, but this proof more closely follows Nash-Williams. * `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded. * `set.is_wf.union` shows that the union of two well-founded subsets is well-founded. * `finset.is_wf` shows that all `finset`s are well-founded. ## TODO Prove that `s` is partial well ordered iff it has no infinite descending chain or antichain. ## References * [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52] * [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63] -/ variables {ι α β : Type*} namespace set /-! ### Relations well-founded on sets -/ /-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/ def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded $ λ a b : s, r a b @[simp] lemma well_founded_on_empty (r : α → α → Prop) : well_founded_on ∅ r := well_founded_of_empty _ section well_founded_on variables {r r' : α → α → Prop} section any_rel variables {s t : set α} {x y : α} lemma well_founded_on_iff : s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := begin have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := ⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩, refine ⟨λ h, _, f.well_founded⟩, rw well_founded.well_founded_iff_has_min, intros t ht, by_cases hst : (s ∩ t).nonempty, { rw ← subtype.preimage_coe_nonempty at hst, rcases h.has_min (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ }, { rcases ht with ⟨m, mt⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ } end namespace well_founded_on protected lemma induction (hs : s.well_founded_on r) (hx : x ∈ s) {P : α → Prop} (hP : ∀ y ∈ s, (∀ z ∈ s, r z y → P z) → P y) : P x := begin let Q : s → Prop := λ y, P y, change Q ⟨x, hx⟩, refine well_founded.induction hs ⟨x, hx⟩ _, simpa only [subtype.forall] end protected lemma mono (h : t.well_founded_on r') (hle : r ≤ r') (hst : s ⊆ t) : s.well_founded_on r := begin rw well_founded_on_iff at *, refine subrelation.wf (λ x y xy, _) h, exact ⟨hle _ _ xy.1, hst xy.2.1, hst xy.2.2⟩ end lemma subset (h : t.well_founded_on r) (hst : s ⊆ t) : s.well_founded_on r := h.mono le_rfl hst end well_founded_on end any_rel section is_strict_order variables [is_strict_order α r] {s t : set α} instance is_strict_order.subset : is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ } lemma well_founded_on_iff_no_descending_seq : s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬∀ n, f n ∈ s := begin simp only [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq, ← not_exists, ← not_nonempty_iff, not_iff_not], split, { rintro ⟨⟨f, hf⟩⟩, have H : ∀ n, f n ∈ s, from λ n, (hf.2 n.lt_succ_self).2.2, refine ⟨⟨f, _⟩, H⟩, simpa only [H, and_true] using @hf }, { rintro ⟨⟨f, hf⟩, hfs : ∀ n, f n ∈ s⟩, refine ⟨⟨f, _⟩⟩, simpa only [hfs, and_true] using @hf } end lemma well_founded_on.union (hs : s.well_founded_on r) (ht : t.well_founded_on r) : (s ∪ t).well_founded_on r := begin rw well_founded_on_iff_no_descending_seq at *, rintro f hf, rcases nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hg|hg⟩, exacts [hs (g.dual.lt_embedding.trans f) hg, ht (g.dual.lt_embedding.trans f) hg] end @[simp] lemma well_founded_on_union : (s ∪ t).well_founded_on r ↔ s.well_founded_on r ∧ t.well_founded_on r := ⟨λ h, ⟨h.subset $ subset_union_left _ _, h.subset $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ end is_strict_order end well_founded_on /-! ### Sets well-founded w.r.t. the strict inequality -/ section has_lt variables [has_lt α] {s t : set α} /-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/ def is_wf (s : set α) : Prop := well_founded_on s (<) @[simp] lemma is_wf_empty : is_wf (∅ : set α) := well_founded_of_empty _ lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) := by simp [is_wf, well_founded_on_iff] theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := h.subset st end has_lt section preorder variables [preorder α] {s t : set α} {a : α} protected lemma is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := hs.union ht @[simp] lemma is_wf_union : is_wf (s ∪ t) ↔ is_wf s ∧ is_wf t := well_founded_on_union end preorder section preorder variables [preorder α] {s t : set α} {a : α} theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ f : ℕ → α, strict_anti f → ¬(∀ n, f (order_dual.to_dual n) ∈ s) := well_founded_on_iff_no_descending_seq.trans ⟨λ H f hf, H ⟨⟨f, hf.injective⟩, λ a b, hf.lt_iff_lt⟩, λ H f, H f (λ _ _, f.map_rel_iff.2)⟩ end preorder /-! ### Partially well-ordered sets A set is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. Equivalently, any antichain (see `is_antichain`) is finite, see `set.partially_well_ordered_on_iff_finite_antichains`. -/ /-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. -/ def partially_well_ordered_on (s : set α) (r : α → α → Prop) : Prop := ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ m n : ℕ, m < n ∧ r (f m) (f n) section partially_well_ordered_on variables {r : α → α → Prop} {r' : β → β → Prop} {f : α → β} {s : set α} {t : set α} {a : α} lemma partially_well_ordered_on.mono (ht : t.partially_well_ordered_on r) (h : s ⊆ t) : s.partially_well_ordered_on r := λ f hf, ht f $ λ n, h $ hf n @[simp] lemma partially_well_ordered_on_empty (r : α → α → Prop) : partially_well_ordered_on ∅ r := λ f hf, (hf 0).elim lemma partially_well_ordered_on.union (hs : s.partially_well_ordered_on r) (ht : t.partially_well_ordered_on r) : (s ∪ t).partially_well_ordered_on r := begin rintro f hf, rcases nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hgs|hgt⟩, { rcases hs _ hgs with ⟨m, n, hlt, hr⟩, exact ⟨g m, g n, g.strict_mono hlt, hr⟩ }, { rcases ht _ hgt with ⟨m, n, hlt, hr⟩, exact ⟨g m, g n, g.strict_mono hlt, hr⟩ } end @[simp] lemma partially_well_ordered_on_union : (s ∪ t).partially_well_ordered_on r ↔ s.partially_well_ordered_on r ∧ t.partially_well_ordered_on r := ⟨λ h, ⟨h.mono $ subset_union_left _ _, h.mono $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ lemma partially_well_ordered_on.image_of_monotone_on (hs : s.partially_well_ordered_on r) (hf : ∀ (a₁ ∈ s) (a₂ ∈ s), r a₁ a₂ → r' (f a₁) (f a₂)) : (f '' s).partially_well_ordered_on r' := begin intros g' hg', choose g hgs heq using hg', obtain rfl : f ∘ g = g', from funext heq, obtain ⟨m, n, hlt, hmn⟩ := hs g hgs, exact ⟨m, n, hlt, hf _ (hgs m) _ (hgs n) hmn⟩ end lemma _root_.is_antichain.finite_of_partially_well_ordered_on (ha : is_antichain r s) (hp : s.partially_well_ordered_on r) : s.finite := begin refine finite_or_infinite.resolve_right (λ hi, _), obtain ⟨m, n, hmn, h⟩ := hp (λ n, hi.nat_embedding _ n) (λ n, (hi.nat_embedding _ n).2), exact hmn.ne ((hi.nat_embedding _).injective $ subtype.val_injective $ ha.eq (hi.nat_embedding _ m).2 (hi.nat_embedding _ n).2 h), end section is_refl variables [is_refl α r] protected lemma finite.partially_well_ordered_on (hs : s.finite) : s.partially_well_ordered_on r := begin intros f hf, obtain ⟨m, n, hmn, h⟩ := hs.exists_lt_map_eq_of_forall_mem hf, exact ⟨m, n, hmn, h.subst $ refl (f m)⟩, end lemma _root_.is_antichain.partially_well_ordered_on_iff (hs : is_antichain r s) : s.partially_well_ordered_on r ↔ s.finite := ⟨hs.finite_of_partially_well_ordered_on, finite.partially_well_ordered_on⟩ @[simp] lemma partially_well_ordered_on_singleton (a : α) : partially_well_ordered_on {a} r := (finite_singleton a).partially_well_ordered_on @[simp] lemma partially_well_ordered_on_insert : partially_well_ordered_on (insert a s) r ↔ partially_well_ordered_on s r := by simp only [← singleton_union, partially_well_ordered_on_union, partially_well_ordered_on_singleton, true_and] protected lemma partially_well_ordered_on.insert (h : partially_well_ordered_on s r) (a : α) : partially_well_ordered_on (insert a s) r := partially_well_ordered_on_insert.2 h lemma partially_well_ordered_on_iff_finite_antichains [is_symm α r] : s.partially_well_ordered_on r ↔ ∀ t ⊆ s, is_antichain r t → t.finite := begin refine ⟨λ h t ht hrt, hrt.finite_of_partially_well_ordered_on (h.mono ht), _⟩, rintro hs f hf, by_contra' H, refine infinite_range_of_injective (λ m n hmn, _) (hs _ (range_subset_iff.2 hf) _), { obtain h | h | h := lt_trichotomy m n, { refine (H _ _ h _).elim, rw hmn, exact refl _ }, { exact h }, { refine (H _ _ h _).elim, rw hmn, exact refl _ } }, rintro _ ⟨m, hm, rfl⟩ _ ⟨n, hn, rfl⟩ hmn, obtain h | h := (ne_of_apply_ne _ hmn).lt_or_lt, { exact H _ _ h }, { exact mt symm (H _ _ h) } end variables [is_trans α r] lemma partially_well_ordered_on.exists_monotone_subseq (h : s.partially_well_ordered_on r) (f : ℕ → α) (hf : ∀ n, f n ∈ s) : ∃ g : ℕ ↪o ℕ, ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f, { refine ⟨g, λ m n hle, _⟩, obtain hlt | rfl := hle.lt_or_eq, exacts [h1 m n hlt, refl_of r _] }, { exfalso, obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (λ n, hf _), exact h2 m n hlt hle } end lemma partially_well_ordered_on_iff_exists_monotone_subseq : s.partially_well_ordered_on r ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin classical, split; intros h f hf, { exact h.exists_monotone_subseq f hf }, { obtain ⟨g, gmon⟩ := h f hf, exact ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩ } end protected lemma partially_well_ordered_on.prod {t : set β} (hs : partially_well_ordered_on s r) (ht : partially_well_ordered_on t r') : partially_well_ordered_on (s ×ˢ t) (λ x y : α × β, r x.1 y.1 ∧ r' x.2 y.2) := begin intros f hf, obtain ⟨g₁, h₁⟩ := hs.exists_monotone_subseq (prod.fst ∘ f) (λ n, (hf n).1), obtain ⟨m, n, hlt, hle⟩ := ht (prod.snd ∘ f ∘ g₁) (λ n, (hf _).2), exact ⟨g₁ m, g₁ n, g₁.strict_mono hlt, h₁ _ _ hlt.le, hle⟩ end end is_refl lemma partially_well_ordered_on.well_founded_on [is_preorder α r] (h : s.partially_well_ordered_on r) : s.well_founded_on (λ a b, r a b ∧ ¬r b a) := begin letI : preorder α := { le := r, le_refl := refl_of r, le_trans := λ _ _ _, trans_of r }, change s.well_founded_on (<), change s.partially_well_ordered_on (≤) at h, rw well_founded_on_iff_no_descending_seq, intros f hf, obtain ⟨m, n, hlt, hle⟩ := h f hf, exact (f.map_rel_iff.2 hlt).not_le hle, end end partially_well_ordered_on section is_pwo variables [preorder α] [preorder β] {s t : set α} /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def is_pwo (s : set α) : Prop := partially_well_ordered_on s (≤) lemma is_pwo.mono (ht : t.is_pwo) : s ⊆ t → s.is_pwo := ht.mono theorem is_pwo.exists_monotone_subseq (h : s.is_pwo) (f : ℕ → α) (hf : ∀ n, f n ∈ s) : ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := h.exists_monotone_subseq f hf theorem is_pwo_iff_exists_monotone_subseq : s.is_pwo ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := partially_well_ordered_on_iff_exists_monotone_subseq protected lemma is_pwo.is_wf (h : s.is_pwo) : s.is_wf := by simpa only [← lt_iff_le_not_le] using h.well_founded_on lemma is_pwo.prod {t : set β} (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s ×ˢ t) := hs.prod ht lemma is_pwo.image_of_monotone_on (hs : s.is_pwo) {f : α → β} (hf : monotone_on f s) : is_pwo (f '' s) := hs.image_of_monotone_on hf lemma is_pwo.image_of_monotone (hs : s.is_pwo) {f : α → β} (hf : monotone f) : is_pwo (f '' s) := hs.image_of_monotone_on (hf.monotone_on _) protected lemma is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) := hs.union ht @[simp] lemma is_pwo_union : is_pwo (s ∪ t) ↔ is_pwo s ∧ is_pwo t := partially_well_ordered_on_union protected lemma finite.is_pwo (hs : s.finite) : is_pwo s := hs.partially_well_ordered_on @[simp] lemma is_pwo_of_finite [finite α] : s.is_pwo := s.to_finite.is_pwo @[simp] lemma is_pwo_singleton (a : α) : is_pwo ({a} : set α) := (finite_singleton a).is_pwo @[simp] lemma is_pwo_empty : is_pwo (∅ : set α) := finite_empty.is_pwo protected lemma subsingleton.is_pwo (hs : s.subsingleton) : is_pwo s := hs.finite.is_pwo @[simp] lemma is_pwo_insert {a} : is_pwo (insert a s) ↔ is_pwo s := by simp only [←singleton_union, is_pwo_union, is_pwo_singleton, true_and] protected lemma is_pwo.insert (h : is_pwo s) (a : α) : is_pwo (insert a s) := is_pwo_insert.2 h protected lemma finite.is_wf (hs : s.finite) : is_wf s := hs.is_pwo.is_wf @[simp] lemma is_wf_singleton {a : α} : is_wf ({a} : set α) := (finite_singleton a).is_wf protected lemma subsingleton.is_wf (hs : s.subsingleton) : is_wf s := hs.is_pwo.is_wf @[simp] lemma is_wf_insert {a} : is_wf (insert a s) ↔ is_wf s := by simp only [←singleton_union, is_wf_union, is_wf_singleton, true_and] lemma is_wf.insert (h : is_wf s) (a : α) : is_wf (insert a s) := is_wf_insert.2 h end is_pwo section well_founded_on variables {r : α → α → Prop} [is_strict_order α r] {s : set α} {a : α} protected lemma finite.well_founded_on (hs : s.finite) : s.well_founded_on r := by { letI := partial_order_of_SO r, exact hs.is_wf } @[simp] lemma well_founded_on_singleton : well_founded_on ({a} : set α) r := (finite_singleton a).well_founded_on protected lemma subsingleton.well_founded_on (hs : s.subsingleton) : s.well_founded_on r := hs.finite.well_founded_on @[simp] lemma well_founded_on_insert : well_founded_on (insert a s) r ↔ well_founded_on s r := by simp only [←singleton_union, well_founded_on_union, well_founded_on_singleton, true_and] lemma well_founded_on.insert (h : well_founded_on s r) (a : α) : well_founded_on (insert a s) r := well_founded_on_insert.2 h end well_founded_on section linear_order variables [linear_order α] {s : set α} protected lemma is_wf.is_pwo (hs : s.is_wf) : s.is_pwo := begin intros f hf, lift f to ℕ → s using hf, have hrange : (range f).nonempty := range_nonempty _, rcases hs.has_min (range f) (range_nonempty _) with ⟨_, ⟨m, rfl⟩, hm⟩, simp only [forall_range_iff, not_lt] at hm, exact ⟨m, m + 1, lt_add_one m, hm _⟩, end /-- In a linear order, the predicates `set.is_wf` and `set.is_pwo` are equivalent. -/ lemma is_wf_iff_is_pwo : s.is_wf ↔ s.is_pwo := ⟨is_wf.is_pwo, is_pwo.is_wf⟩ end linear_order end set namespace finset variables {r : α → α → Prop} @[simp] protected lemma partially_well_ordered_on [is_refl α r] (s : finset α) : (s : set α).partially_well_ordered_on r := s.finite_to_set.partially_well_ordered_on @[simp] protected lemma is_pwo [preorder α] (s : finset α) : set.is_pwo (↑s : set α) := s.partially_well_ordered_on @[simp] protected lemma is_wf [preorder α] (s : finset α) : set.is_wf (↑s : set α) := s.finite_to_set.is_wf @[simp] protected lemma well_founded_on [is_strict_order α r] (s : finset α) : set.well_founded_on (↑s : set α) r := by { letI := partial_order_of_SO r, exact s.is_wf } lemma well_founded_on_sup [is_strict_order α r] (s : finset ι) {f : ι → set α} : (s.sup f).well_founded_on r ↔ ∀ i ∈ s, (f i).well_founded_on r := finset.cons_induction_on s (by simp) $ λ a s ha hs, by simp [-sup_set_eq_bUnion, hs] lemma partially_well_ordered_on_sup (s : finset ι) {f : ι → set α} : (s.sup f).partially_well_ordered_on r ↔ ∀ i ∈ s, (f i).partially_well_ordered_on r := finset.cons_induction_on s (by simp) $ λ a s ha hs, by simp [-sup_set_eq_bUnion, hs] lemma is_wf_sup [preorder α] (s : finset ι) {f : ι → set α} : (s.sup f).is_wf ↔ ∀ i ∈ s, (f i).is_wf := s.well_founded_on_sup lemma is_pwo_sup [preorder α] (s : finset ι) {f : ι → set α} : (s.sup f).is_pwo ↔ ∀ i ∈ s, (f i).is_pwo := s.partially_well_ordered_on_sup @[simp] lemma well_founded_on_bUnion [is_strict_order α r] (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).well_founded_on r ↔ ∀ i ∈ s, (f i).well_founded_on r := by simpa only [finset.sup_eq_supr] using s.well_founded_on_sup @[simp] lemma partially_well_ordered_on_bUnion (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).partially_well_ordered_on r ↔ ∀ i ∈ s, (f i).partially_well_ordered_on r := by simpa only [finset.sup_eq_supr] using s.partially_well_ordered_on_sup @[simp] lemma is_wf_bUnion [preorder α] (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).is_wf ↔ ∀ i ∈ s, (f i).is_wf := s.well_founded_on_bUnion @[simp] lemma is_pwo_bUnion [preorder α] (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).is_pwo ↔ ∀ i ∈ s, (f i).is_pwo := s.partially_well_ordered_on_bUnion end finset namespace set section preorder variables [preorder α] {s : set α} {a : α} /-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s := (well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) @[simp] lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} : hs.min hn = a := eq_of_mem_singleton (is_wf.min_mem hs hn) end preorder section linear_order variables [linear_order α] {s t : set α} {a : α} lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_lt (hs.not_lt_min hn ha) lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩ lemma is_wf.min_le_min_of_subset {hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb)) lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) : (hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) := begin refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _)) (is_wf.min_le_min_of_subset (subset_union_right _ _))) _, rw min_le_iff, exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _), end end linear_order end set open set namespace set.partially_well_ordered_on variables {r : α → α → Prop} /-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence whose range is contained in a particular set `s`. One exists if and only if `s` is not partially well-ordered. -/ def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop := (∀ n, f n ∈ s) ∧ ∀ m n : ℕ, m < n → ¬ r (f m) (f n) lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) : s.partially_well_ordered_on r ↔ ∀ f, ¬ is_bad_seq r s f := forall_congr $ λ f, by simp [is_bad_seq] /-- This indicates that every bad sequence `g` that agrees with `f` on the first `n` terms has `rk (f n) ≤ rk (g n)`. -/ def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop := ∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g /-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n` terms and is minimal at `n`. -/ noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) : { g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } := begin classical, have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g ∧ rk (g n) = k := ⟨_, f, λ _ _, rfl, hf, rfl⟩, obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h), refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩, refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩, rwa ← h3, end lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) : (∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩, let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f }, { refine nat.rec _ _, { exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1, (min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, }, { exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1, (min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } }, have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m, { intros m n mn, obtain ⟨k, rfl⟩ := exists_add_of_le mn, clear mn, induction k with k ih, { refl }, rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m (nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))], refl }, refine ⟨λ n, (fs n).1 n, ⟨(λ n, ((fs n).2).1.1 n), λ m n mn, _⟩, λ n g hg1 hg2, _⟩, { dsimp, rw [← subtype.val_eq_coe, h m n (le_of_lt mn)], convert (fs n).2.1.2 m n mn }, { convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 le_rfl), rw ← h m n (le_of_lt mn) }, end lemma iff_not_exists_is_min_bad_seq (rk : α → ℕ) {s : set α} : s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr], split, { apply exists_min_bad_of_exists_bad }, rintro ⟨f, hf1, hf2⟩, exact ⟨f, hf1⟩, end /-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially well-ordered on the set of lists of elements of `s`. That relation is defined so that `list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/ lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r] {s : set α} (h : s.partially_well_ordered_on r) : { l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) := begin rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩, { apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}), { intros l hl, rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem], exact hl, }, apply_instance }, haveI : inhabited α := ⟨as⟩, rw [iff_not_exists_is_min_bad_seq (list.length)], rintro ⟨f, hf1, hf2⟩, have hnil : ∀ n, f n ≠ list.nil := λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil), obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _, swap, { simp only [set.range_subset_iff, function.comp_apply], exact λ n, hf1.1 n _ (list.head_mem_self (hnil n)) }, have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0)))) (λ m hm, (if_pos hm).symm) _, swap, { simp only [if_neg (lt_irrefl (g 0)), tsub_self], rw [list.length_tail, ← nat.pred_eq_sub_one], exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) }, rw [is_bad_seq] at hf', push_neg at hf', obtain ⟨m, n, mn, hmn⟩ := hf' _, swap, { rintro n x hx, split_ifs at hx with hn hn, { exact hf1.1 _ _ hx }, { refine hf1.1 _ _ (list.tail_subset _ hx), } }, by_cases hn : n < g 0, { apply hf1.2 m n mn, rwa [if_pos hn, if_pos (mn.trans hn)] at hmn }, { obtain ⟨n', rfl⟩ := exists_add_of_le (not_lt.1 hn), rw [if_neg hn, add_comm (g 0) n', add_tsub_cancel_right] at hmn, split_ifs at hmn with hm hm, { apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)), exact trans hmn (list.tail_sublist_forall₂_self _) }, { rw [← (tsub_lt_iff_left (le_of_not_lt hm))] at mn, apply hf1.2 _ _ (g.lt_iff_lt.2 mn), rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))], exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } } end end set.partially_well_ordered_on lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf := (set.is_wf_univ_iff.2 h).mono s.subset_univ /-- A version of **Dickson's lemma** any subset of functions `Π s : σ, α s` is partially well ordered, when `σ` is a `fintype` and each `α s` is a linear well order. This includes the classical case of Dickson's lemma that `ℕ ^ n` is a well partial order. Some generalizations would be possible based on this proof, to include cases where the target is partially well ordered, and also to consider the case of `set.partially_well_ordered_on` instead of `set.is_pwo`. -/ lemma pi.is_pwo {α : ι → Type*} [Π i, linear_order (α i)] [∀ i, is_well_order (α i) (<)] [finite ι] (s : set (Π i, α i)) : s.is_pwo := begin classical, casesI nonempty_fintype ι, refine is_pwo.mono _ (subset_univ _), rw is_pwo_iff_exists_monotone_subseq, simp only [mem_univ, forall_const, function.comp_app], suffices : ∀ s : finset ι, ∀ (f : ℕ → Π s, α s), ∃ g : ℕ ↪o ℕ, ∀ ⦃a b : ℕ⦄, a ≤ b → ∀ (x : ι) (hs : x ∈ s), (f ∘ g) a x ≤ (f ∘ g) b x, { simpa only [forall_true_left, finset.mem_univ] using this finset.univ }, apply' finset.induction, { intros f, existsi rel_embedding.refl (≤), simp only [is_empty.forall_iff, implies_true_iff, forall_const, finset.not_mem_empty], }, { intros x s hx ih f, obtain ⟨g, hg⟩ := (is_well_founded.wf.is_wf univ).is_pwo.exists_monotone_subseq (λ n, f n x) mem_univ, obtain ⟨g', hg'⟩ := ih (f ∘ g), refine ⟨g'.trans g, λ a b hab, _⟩, simp only [finset.mem_insert, rel_embedding.coe_trans, function.comp_app, forall_eq_or_imp], exact ⟨hg (order_hom_class.mono g' hab), hg' hab⟩ } end
2315f5f5312e78dffe7cc4cf8ebee75ba9cde63f
618003631150032a5676f229d13a079ac875ff77
/src/algebra/continued_fractions/computation/basic.lean
de055bf3deaaec4d8c0d294adc31ac414406943f
[ "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
7,892
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.basic import algebra.ordered_field import algebra.archimedean /-! # Computable Continued Fractions ## Summary We formalise the standard computation of (regular) continued fractions for linear ordered floor fields. The algorithm is rather simple. Here is an outline of the procedure adapted from Wikipedia: Take a value `v`. We call `⌊v⌋` the *integer part* of `v` and `v − ⌊v⌋` the *fractional part* of `v`. A continued fraction representation of `v` can then be given by `[⌊v⌋; b₀, b₁, b₂,...]`, where `[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v − ⌊v⌋)`. This process stops when the fractional part hits 0. In other words: to calculate a continued fraction representation of a number `v`, write down the integer part (i.e. the floor) of `v`. Subtract this integer part from `v`. If the difference is 0, stop; otherwise find the reciprocal of the difference and repeat. The procedure will terminate if and only if `v` is rational. For an example, refer to `int_fract_pair.stream`. ## Main definitions - `generalized_continued_fraction.int_fract_pair.stream`: computes the stream of integer and fractional parts of a given value as described in the summary. - `generalized_continued_fraction.of`: computes the generalised continued fraction of a value `v`. In fact, it computes a regular continued fraction that terminates if and only if `v` is rational (those proofs will be added in a future commit). ## Implementation Notes There is an intermediate definition `generalized_continued_fraction.int_fract_pair.seq1` between `generalized_continued_fraction.int_fract_pair.stream` and `generalized_continued_fraction.of` to wire up things. User should not (need to) directly interact with it. The computation of the integer and fractional pairs of a value can elegantly be captured by a recursive computation of a stream of option pairs. This is done in `int_fract_pair.stream`. However, the type then does not guarantee the first pair to always be `some` value, as expected by a continued fraction. To separate concerns, we first compute a single head term that always exists in `generalized_continued_fraction.int_fract_pair.seq1` followed by the remaining stream of option pairs. This sequence with a head term (`seq1`) is then transformed to a generalized continued fraction in `generalized_continued_fraction.of` by extracting the wanted integer parts of the head term and the stream. ## References - https://en.wikipedia.org/wiki/Continued_fraction ## Tags numerics, number theory, approximations, fractions -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf -- Fix a carrier `K`. variable (K : Type*) /-- We collect an integer part `b = ⌊v⌋` and fractional part `fr = v - ⌊v⌋` of a value `v` in a pair `⟨b, fr⟩`. -/ structure int_fract_pair := (b : ℤ) (fr : K) /-! Interlude: define some expected coercions and instances. -/ namespace int_fract_pair /-- Make an `int_fract_pair` printable. -/ instance [has_repr K] : has_repr (int_fract_pair K) := ⟨λ p, "(b : " ++ (repr p.b) ++ ", fract : " ++ (repr p.fr) ++ ")"⟩ instance inhabited [inhabited K] : inhabited (int_fract_pair K) := ⟨⟨0, (default _)⟩⟩ variable {K} section coe /-! Interlude: define some expected coercions. -/ /- Fix another type `β` and assume `K` can be converted to `β`. -/ variables {β : Type*} [has_coe K β] /-- Coerce a pair by coercing the fractional component. -/ instance has_coe_to_int_fract_pair : has_coe (int_fract_pair K) (int_fract_pair β) := ⟨λ ⟨b, fr⟩, ⟨b, (fr : β)⟩⟩ @[simp, norm_cast] lemma coe_to_int_fract_pair {b : ℤ} {fr : K} : (↑(int_fract_pair.mk b fr) : int_fract_pair β) = int_fract_pair.mk b (↑fr : β) := rfl end coe -- Note: this could be relaxed to something like `discrete_linear_ordered_division_ring` in the -- future. /- Fix a discrete linear ordered field with `floor` function. -/ variables [discrete_linear_ordered_field K] [floor_ring K] /-- Creates the integer and fractional part of a value `v`, i.e. `⟨⌊v⌋, v - ⌊v⌋⟩`. -/ protected def of (v : K) : int_fract_pair K := ⟨⌊v⌋, fract v⟩ /-- Creates the stream of integer and fractional parts of a value `v` needed to obtain the continued fraction representation of `v` in `generalized_continued_fraction.of`. More precisely, given a value `v : K`, it recursively computes a stream of option `ℤ × K` pairs as follows: `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩`, `stream v (n + 1) = some ⟨⌊frₙ⁻¹⌋, frₙ⁻¹ - ⌊frₙ⁻¹⌋⟩`, if `stream v n = some ⟨_, frₙ⟩` and `frₙ ≠ 0`. `stream v (n + 1) = none`, otherwise. For example, let `(v : ℚ) := 3.4`. The process goes as follows: `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩ = some ⟨3, 0.4⟩`, `stream v 1 = some ⟨⌊0.4⁻¹⌋, 0.4⁻¹ - ⌊0.4⁻¹⌋⟩ = some ⟨⌊2.5⌋, 2.5 - ⌊2.5⌋⟩ = some ⟨2, 0.5⟩`, `stream v 2 = some ⟨⌊0.5⁻¹⌋, 0.5⁻¹ - ⌊0.5⁻¹⌋⟩ = some ⟨⌊2⌋, 2 - ⌊2⌋⟩ = some ⟨2, 0⟩` `stream v n = none`, for `n ≥ 3`. -/ protected def stream (v : K) : stream $ option (int_fract_pair K) | 0 := some (int_fract_pair.of v) | (n + 1) := do ap_n ← stream n, if ap_n.fr = 0 then none else int_fract_pair.of ap_n.fr⁻¹ /-- Shows that `int_fract_pair.stream` has the sequence property, that is once we return `none` at position `n`, we also return `none` at `n + 1`. -/ lemma stream_is_seq (v : K) : (int_fract_pair.stream v).is_seq := by { assume _ hyp, simp [int_fract_pair.stream, hyp] } /-- Uses `int_fract_pair.stream` to create a sequence with head (i.e. `seq1`) of integer and fractional parts of a value `v`. The first value of `int_fract_pair.stream` is never `none`, so we can safely extract it and put the tail of the stream in the sequence part. This is just an intermediate representation and users should not (need to) directly interact with it. The setup of rewriting/simplification lemmas that make the definitions easy to use is done in `algebra.continued_fractions.computation.translations`. -/ protected def seq1 (v : K) : seq1 $ int_fract_pair K := ⟨ int_fract_pair.of v,--the head seq.tail -- take the tail of `int_fract_pair.stream` since the first element is already in the head -- create a sequence from `int_fract_pair.stream` ⟨ int_fract_pair.stream v, -- the underlying stream @stream_is_seq _ _ _ v ⟩ ⟩ -- the proof that the stream is a sequence end int_fract_pair variable {K} /-- Returns the `generalized_continued_fraction` of a value. In fact, the returned gcf is also a `continued_fraction` that terminates if and only if `v` is rational (those proofs will be added in a future commit). The continued fraction representation of `v` is given by `[⌊v⌋; b₀, b₁, b₂,...]`, where `[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v − ⌊v⌋)`. This process stops when the fractional part `v- ⌊v⌋` hits 0 at some step. The implementation uses `int_fract_pair.stream` to obtain the partial denominators of the continued fraction. Refer to said function for more details about the computation process. -/ protected def of [discrete_linear_ordered_field K] [floor_ring K] (v : K) : gcf K := let ⟨h, s⟩ := int_fract_pair.seq1 v in -- get the sequence of integer and fractional parts. ⟨ h.b, -- the head is just the first integer part s.map (λ p, ⟨1, p.b⟩) ⟩ -- the sequence consists of the remaining integer parts as the partial -- denominators; all partial numerators are simply 1 end generalized_continued_fraction
3991a3a30b142a709c756a9423df63b27d987b08
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/fintype/intervals.lean
e546306acdca29a48c25e96707ae4e543eab27aa
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,501
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.intervals.default import Mathlib.data.set.finite import Mathlib.data.pnat.intervals import Mathlib.PostPort namespace Mathlib /-! # fintype instances for intervals We provide `fintype` instances for `Ico l u`, for `l u : ℕ`, and for `l u : ℤ`. -/ namespace set protected instance Ico_ℕ_fintype (l : ℕ) (u : ℕ) : fintype ↥(Ico l u) := fintype.of_finset (finset.Ico l u) sorry @[simp] theorem Ico_ℕ_card (l : ℕ) (u : ℕ) : fintype.card ↥(Ico l u) = u - l := Eq.trans (fintype.card_of_finset (finset.Ico l u) (Ico_ℕ_fintype._proof_1 l u)) (finset.Ico.card l u) protected instance Ico_pnat_fintype (l : ℕ+) (u : ℕ+) : fintype ↥(Ico l u) := fintype.of_finset (pnat.Ico l u) sorry @[simp] theorem Ico_pnat_card (l : ℕ+) (u : ℕ+) : fintype.card ↥(Ico l u) = ↑u - ↑l := Eq.trans (fintype.card_of_finset (pnat.Ico l u) (Ico_pnat_fintype._proof_1 l u)) (pnat.Ico.card l u) protected instance Ico_ℤ_fintype (l : ℤ) (u : ℤ) : fintype ↥(Ico l u) := fintype.of_finset (finset.Ico_ℤ l u) sorry @[simp] theorem Ico_ℤ_card (l : ℤ) (u : ℤ) : fintype.card ↥(Ico l u) = int.to_nat (u - l) := Eq.trans (fintype.card_of_finset (finset.Ico_ℤ l u) (Ico_ℤ_fintype._proof_1 l u)) (finset.Ico_ℤ.card l u)
0182ffcbb6a75c9194d60ed7636c3514ea1c94d5
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Do.lean
35da6b130c1e31891be04df667f42f76da825e6a
[ "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
69,541
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Elab.PatternVar import Lean.Elab.Quotation.Util import Lean.Parser.Do -- HACK: avoid code explosion until heuristics are improved set_option compiler.reuse false namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Lean.Parser.Term.do || k == ``Lean.Parser.Term.doSeqIndent || k == ``Lean.Parser.Term.doSeqBracketed || k == ``Lean.Parser.Term.termReturn || k == ``Lean.Parser.Term.termUnless || k == ``Lean.Parser.Term.termTry || k == ``Lean.Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Lean.Parser.Term.letPatDecl then false else if k == ``Lean.Parser.Term.letEqnsDecl then true else if k == ``Lean.Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts || k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Lean.Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Lean.Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Lean.Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node _ k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == ``Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr expectedType : Expr private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do match type with | Expr.app m α _ => try let bindInstType ← mkAppM ``Bind #[m] let _ ← Meta.synthInstance bindInstType return some { m := m, α := α, expectedType := expectedType } catch _ => return none | _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => throwError "invalid 'do' notation, expected type is not a monad application{indentExpr expectedType}\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad." namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensure_expected_type% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref g ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == ``Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == ``Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == ``Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == ``Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => ``(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == ``Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == ``Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == ``Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == ``Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == ``Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == ``Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == ``Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType id arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == ``Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == ``Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensure_type_of% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(if $cond then $thenBranch else $elseBranch) else let h := optIdent[0] ``(if $h:ident : $cond then $thenBranch else $elseBranch) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref genParam discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x def checkNotShadowingMutable (xs : Array Name) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x then throwInvalidShadowing x def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax | stx@(Syntax.node i k args) => if liftMethodDelimiter k then return stx else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1] let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node i k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == ``Lean.Parser.Term.doLetArrow || kind == ``Lean.Parser.Term.doLet || kind == ``Lean.Parser.Term.doLetRec || kind == ``Lean.Parser.Term.doHave || kind == ``Lean.Parser.Term.doReassign || kind == ``Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == ``Lean.Parser.Term.doIdDecl then let y := decl[0].getId checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == ``Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == ``Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == ``Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys ``(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(for_in% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit) | some a => return ensure_expected_type% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let discrs := doMatch[2] let optType := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == ``Lean.Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x.getId] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular ``(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← expandLiftMethod doElem if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == ``Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doHave then let var := getDoHaveVar doElem checkNotShadowingMutable #[var] mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == ``Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == ``Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == ``Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == ``Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == ``Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == ``Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == ``Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == ``Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == ``Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == ``Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == ``Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn end Lean.Elab.Term
c5d076f71d6bdbbc13434e2854da94787df9fd4d
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/algebra/groupoid.hlean
ab7e0ef0eeb76f2ddd509995b84e4c22e602b92d
[ "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
2,829
hlean
-- Copyright (c) 2014 Jakob von Raumer. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jakob von Raumer -- Ported from Coq HoTT import .precategory.basic .precategory.morphism .group open eq function prod sigma truncation morphism nat path_algebra unit structure foo (A : Type) := (bsp : A) structure groupoid [class] (ob : Type) extends precategory ob := (all_iso : Π ⦃a b : ob⦄ (f : hom a b), @is_iso ob (precategory.mk hom _ _ _ assoc id_left id_right) a b f) namespace groupoid attribute all_iso [instance] --set_option pp.universes true --set_option pp.implicit true universe variable l open precategory definition path_groupoid (A : Type.{l}) (H : is_trunc (nat.zero .+1) A) : groupoid.{l l} A := groupoid.mk (λ (a b : A), a = b) (λ (a b : A), have ish : is_hset (a = b), from succ_is_trunc nat.zero a b, ish) (λ (a b c : A) (p : b = c) (q : a = b), q ⬝ p) (λ (a : A), refl a) (λ (a b c d : A) (p : c = d) (q : b = c) (r : a = b), concat_pp_p r q p) (λ (a b : A) (p : a = b), concat_p1 p) (λ (a b : A) (p : a = b), concat_1p p) (λ (a b : A) (p : a = b), @is_iso.mk A _ a b p (p⁻¹) !concat_pV !concat_Vp) -- A groupoid with a contractible carrier is a group definition group_of_contr {ob : Type} (H : is_contr ob) (G : groupoid ob) : group (hom (center ob) (center ob)) := begin fapply group.mk, intros (f, g), apply (comp f g), apply homH, intros (f, g, h), apply ((assoc f g h)⁻¹), apply (ID (center ob)), intro f, apply id_left, intro f, apply id_right, intro f, exact (morphism.inverse f), intro f, exact (morphism.inverse_compose f), end definition group_of_unit (G : groupoid unit) : group (hom ⋆ ⋆) := begin fapply group.mk, intros (f, g), apply (comp f g), apply homH, intros (f, g, h), apply ((assoc f g h)⁻¹), apply (ID ⋆), intro f, apply id_left, intro f, apply id_right, intro f, exact (morphism.inverse f), intro f, exact (morphism.inverse_compose f), end -- Conversely we can turn each group into a groupoid on the unit type definition of_group (A : Type.{l}) [G : group A] : groupoid.{l l} unit := begin fapply groupoid.mk, intros, exact A, intros, apply (@group.carrier_hset A G), intros (a, b, c, g, h), exact (@group.mul A G g h), intro a, exact (@group.one A G), intros, exact ((@group.mul_assoc A G h g f)⁻¹), intros, exact (@group.mul_left_id A G f), intros, exact (@group.mul_right_id A G f), intros, apply is_iso.mk, apply mul_left_inv, apply mul_right_inv, end -- TODO: This is probably wrong open equiv is_equiv definition group_equiv {A : Type.{l}} [fx : funext] : group A ≃ Σ (G : groupoid.{l l} unit), @hom unit G ⋆ ⋆ = A := sorry end groupoid
d02cfb692f968668c32a31f22bb351dd49145661
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/match4.lean
6768547a429821ea5217f8e938bb2786fad04e65
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
527
lean
open nat bool inhabited prod definition diag (a b c : bool) : nat := match (a, b, c) with | (b, tt, ff) := 1 | (ff, b, tt) := 2 | (tt, ff, b) := 3 | (b1, b2, b3) := arbitrary nat end theorem diag1 (a : bool) : diag a tt ff = 1 := bool.cases_on a rfl rfl theorem diag2 (a : bool) : diag ff a tt = 2 := bool.cases_on a rfl rfl theorem diag3 (a : bool) : diag tt ff a = 3 := bool.cases_on a rfl rfl theorem diag4_1 : diag ff ff ff = arbitrary nat := rfl theorem diag4_2 : diag tt tt tt = arbitrary nat := rfl
a71c25b615df2085179171ad7c4150b660724ba9
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Meta/Tactic/Rewrite.lean
83bfe3fb1c6f0a68864e9b4b037e6f21eebaa252
[ "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
2,732
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.KAbstract import Lean.Meta.Check import Lean.Meta.Tactic.Apply namespace Lean.Meta structure RewriteResult := (eNew : Expr) (eqProof : Expr) (mvarIds : List MVarId) -- new goals def rewrite (mvarId : MVarId) (e : Expr) (heq : Expr) (symm : Bool := false) (occs : Occurrences := Occurrences.all) (mode := TransparencyMode.reducible) : MetaM RewriteResult := withMVarContext mvarId do checkNotAssigned mvarId `rewrite let heqType ← inferType heq let (newMVars, binderInfos, heqType) ← forallMetaTelescopeReducing heqType let heq := mkAppN heq newMVars let cont (heq heqType : Expr) : MetaM RewriteResult := do match (← matchEq? heqType) with | none => throwTacticEx `rewrite mvarId m!"equality or iff proof expected{indentExpr heqType}" | some (α, lhs, rhs) => let cont (heq heqType lhs rhs : Expr) : MetaM RewriteResult := do if lhs.getAppFn.isMVar then throwTacticEx `rewrite mvarId m!"pattern is a metavariable{indentExpr lhs}\nfrom equation{indentExpr heqType}" let e ← instantiateMVars e let eAbst ← withTransparency mode <| kabstract e lhs occs unless eAbst.hasLooseBVars do throwTacticEx `rewrite mvarId m!"did not find instance of the pattern in the target expression{indentExpr lhs}" -- construct rewrite proof let eNew := eAbst.instantiate1 rhs let eNew ← instantiateMVars eNew let eEqE ← mkEq e e let eEqEAbst := mkApp eEqE.appFn! eAbst let motive := Lean.mkLambda `_a BinderInfo.default α eEqEAbst unless (← isTypeCorrect motive) do throwTacticEx `rewrite mvarId "motive is not type correct" let eqRefl ← mkEqRefl e let eqPrf ← mkEqNDRec motive eqRefl heq postprocessAppMVars `rewrite mvarId newMVars binderInfos let newMVars ← newMVars.filterM fun mvar => not <$> isExprMVarAssigned mvar.mvarId! pure { eNew := eNew, eqProof := eqPrf, mvarIds := newMVars.toList.map Expr.mvarId! } match symm with | false => cont heq heqType lhs rhs | true => do let heq ← mkEqSymm heq let heqType ← mkEq rhs lhs cont heq heqType rhs lhs match heqType.iff? with | some (lhs, rhs) => let heqType ← mkEq lhs rhs let heq := mkApp3 (mkConst `propext) lhs rhs heq cont heq heqType | none => cont heq heqType end Lean.Meta
dd8a50a01b6e1f68ada7730c82edcf14f5041f8c
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Logic_and_Proof/Chapter9/9.10.lean
3cbc043184621e0376acb27a05da42145deecdf4
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,006
lean
-- 9.1 Functions, Predicates, and Relations -- In these specific examples, |constant| can be replaced with |variable|. -- This interchangeability is not always the case though, as |constant|s are a -- little more powerful than |variable|s, since they add a new object to Lean -- essentially, they can be referenced elsewhere. constant U: Type constant c: U -- Constant symbol. constant f: U -> U -- Unary function symbol. constant g: U -> U -> U -- Binary function symbol. constant P: U -> Prop -- Unary relation symbol. constant R: U -> U -> Prop -- Binary relation symbol. -- Define variables to actually use with the above symbols. variables x y : U -- These all resolve to type `U`; as such, they can be considered "terms" in -- FOL. #check c #check f c #check g x c #check g x (f c) #check g c (f x) -- These all resolve to type `Prop`; as such, they can be considered "formulas".s -- Example: even(), odd(), etc. #check P x #check P (g x y) #check R x c #check R x y
a0372ffc66aa33330d5be74c21c0370d4be223e1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/continued_fractions/continuants_recurrence_auto.lean
631c027a84232e42d25ace8a3a1ababa3ac60fdc
[]
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,530
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.continued_fractions.translations import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Recurrence Lemmas for the `continuants` Function of Continued Fractions. ## Summary Given a generalized continued fraction `g`, for all `n ≥ 1`, we prove that the `continuants` function indeed satisfies the following recurrences: - `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂`, and - `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ namespace generalized_continued_fraction theorem continuants_aux_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppred : pair K} {pred : pair K} (nth_s_eq : seq.nth (s g) n = some gp) (nth_conts_aux_eq : continuants_aux g n = ppred) (succ_nth_conts_aux_eq : continuants_aux g (n + 1) = pred) : continuants_aux g (n + bit0 1) = pair.mk (pair.b gp * pair.a pred + pair.a gp * pair.a ppred) (pair.b gp * pair.b pred + pair.a gp * pair.b ppred) := sorry theorem continuants_recurrence_aux {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppred : pair K} {pred : pair K} (nth_s_eq : seq.nth (s g) n = some gp) (nth_conts_aux_eq : continuants_aux g n = ppred) (succ_nth_conts_aux_eq : continuants_aux g (n + 1) = pred) : continuants g (n + 1) = pair.mk (pair.b gp * pair.a pred + pair.a gp * pair.a ppred) (pair.b gp * pair.b pred + pair.a gp * pair.b ppred) := sorry /-- Shows that `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂` and `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ theorem continuants_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppred : pair K} {pred : pair K} (succ_nth_s_eq : seq.nth (s g) (n + 1) = some gp) (nth_conts_eq : continuants g n = ppred) (succ_nth_conts_eq : continuants g (n + 1) = pred) : continuants g (n + bit0 1) = pair.mk (pair.b gp * pair.a pred + pair.a gp * pair.a ppred) (pair.b gp * pair.b pred + pair.a gp * pair.b ppred) := continuants_recurrence_aux succ_nth_s_eq (eq.mp (Eq._oldrec (Eq.refl (continuants g n = ppred)) nth_cont_eq_succ_nth_cont_aux) nth_conts_eq) (eq.mp (Eq._oldrec (Eq.refl (continuants g (n + 1) = pred)) nth_cont_eq_succ_nth_cont_aux) succ_nth_conts_eq) /-- Shows that `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂`. -/ theorem numerators_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppredA : K} {predA : K} (succ_nth_s_eq : seq.nth (s g) (n + 1) = some gp) (nth_num_eq : numerators g n = ppredA) (succ_nth_num_eq : numerators g (n + 1) = predA) : numerators g (n + bit0 1) = pair.b gp * predA + pair.a gp * ppredA := sorry /-- Shows that `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ theorem denominators_recurrence {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {gp : pair K} {ppredB : K} {predB : K} (succ_nth_s_eq : seq.nth (s g) (n + 1) = some gp) (nth_denom_eq : denominators g n = ppredB) (succ_nth_denom_eq : denominators g (n + 1) = predB) : denominators g (n + bit0 1) = pair.b gp * predB + pair.a gp * ppredB := sorry end Mathlib
038be899cfb3a399168ee0167176792ba1905be3
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/thm95/constants/spectral_constants.lean
90a23d74dca46f9c27a56c02022d2a97b9e2f8f0
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,106
lean
import polyhedral_lattice.cosimplicial /-! # Explicit formulas for the constants in theorem 9.5 -/ noncomputable theory open_locale nnreal namespace system_of_double_complexes namespace normed_spectral noncomputable def ε : Π (m : ℕ) (K : ℝ≥0), ℝ≥0 | 0 K := (2 * K)⁻¹ | (m+1) K := ε m (K * (K * K + 1)) lemma ε_pos : ∀ m K [fact (1 ≤ K)], 0 < ε m K | 0 K hK := nnreal.inv_pos.mpr (mul_pos zero_lt_two (lt_of_lt_of_le zero_lt_one hK.out)) | (m+1) K hK := by { dsimp [ε], exactI ε_pos m _ } --noncomputable def k₀ : Π (m : ℕ) (k : ℝ≥0), ℝ≥0 | 0 k := k | (m+1) k := k₀ m (k * k * k) instance one_le_k₀ : ∀ m k [fact (1 ≤ k)], fact (1 ≤ k₀ m k) | 0 k hk := hk | (m+1) k hk := by { dsimp [k₀], exactI one_le_k₀ m _ } noncomputable def K₀ : Π (m : ℕ) (K : ℝ≥0), ℝ≥0 | 0 K := K | (m+1) K := K₀ m (K * (K * K + 1)) instance one_le_K₀ : ∀ m K [fact (1 ≤ K)], fact (1 ≤ K₀ m K) | 0 K hK := hK | (m+1) K hK := by { dsimp [K₀], exactI one_le_K₀ m _ } end normed_spectral end system_of_double_complexes