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
300de3d1679e246ebaa857ca9f5a21fb90cee3b1
439bc6c3e74a118aa51df633b8e1f24415804d86
/covering_family.lean
238992005a1ff0eb73d249b85c4bcd949c78f79e
[]
no_license
jcommelin/lt2019_slides
4ca498db02b5187c5778c21b985126d52d260696
3234cd92920d3d4321cc2cef78b48e5fa55be413
refs/heads/master
1,586,718,101,957
1,546,930,855,000
1,546,930,855,000
162,697,592
1
0
null
null
null
null
UTF-8
Lean
false
false
57
lean
def covering_family (U : X) : Type u := set (over.{u} U)
666196d24018e271b685132488077e713895543f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/454.lean
f0ce488b56876a158709261894f1168955d61ee8
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
148
lean
constants (A : Type₁) (P : A → Type₁) (H : Π{a b : A}, P a → P b) (a b : A) (K : P a) theorem foo : P b := begin apply H, {apply K} end
744ad6b559d7684d9e10cebdde8e5a37c98b1425
7b4371534ac437ca8cfb325dd5c6638ff111d31a
/main.lean
200e65ad6bc5a40d9ef8f30b8dcc676fa723b734
[]
no_license
Shamrock-Frost/boolean_rings
6d78294568b6b9ad7b9c67b5de5e9545227826da
5da11beeaa37ec186c1deff946f2dbf7594fceb4
refs/heads/master
1,588,394,857,485
1,553,973,949,000
1,553,973,949,000
177,757,941
0
0
null
null
null
null
UTF-8
Lean
false
false
673
lean
import .algebra_util .boolean_rings @[reducible] def ring_of_subsets (A) := set A theorem classification_of_finite_boolean_rings {R : Type} [boolean_ring R] : finite R → ∃ A : Type, R ≅ ring_of_subsets A := begin intros is_fin, existsi min_nonzero.type, apply ring.isomorphic_symm, existsi min_nonzero.pset_embed is_fin, apply classical.ring.bijective_homomorphism_is_isomorphism, { constructor, { exact pset_embed_inj is_fin }, { exact pset_embed_surj is_fin } }, { constructor, exact pset_embed_preserves_add is_fin, constructor, { exact pset_embed_preserves_mul is_fin }, { exact pset_embed_preserves_one is_fin } } end
ffc6902670d42f98ee10fc06b79fb69831ea7d83
3aad12fe82645d2d3173fbedc2e5c2ba945a4d75
/src/data/serial/derive.lean
776c8774c339b68c6173228ba16bc4d27d846e1d
[]
no_license
seanpm2001/LeanProver-Community_MathLIB-Nursery
4f88d539cb18d73a94af983092896b851e6640b5
0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec
refs/heads/master
1,688,730,786,645
1,572,070,026,000
1,572,070,026,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,059
lean
import tactic.monotonicity import data.serial.basic import data.nat.nursery import tactic.nursery import tactic.norm_num import tactic.basic import category.basic namespace tactic open serial open tactic open tactic.interactive (unfold norm_num trivial simp ac_mono) open interactive meta def mk_up (u : level) (e : expr) : tactic expr := do t ← infer_type e, u' ← mk_meta_univ, (t,e) ← mcond (succeeds $ infer_type t >>= unify (expr.sort (level.succ u'))) (pure (t,e)) (prod.mk <$> mk_app ``plift [t] <*> mk_app ``plift.up [e]), let up : expr := expr.const ``ulift.up [u,u'], pure $ up t e meta def mk_down (u : level) (e t : expr) : tactic expr := do u' ← mk_meta_univ, e ← mk_app ``ulift.down [e], mcond (succeeds $ infer_type t >>= unify (expr.sort (level.succ u'))) (pure (e)) (mk_app ``plift.down [e]) meta def mk_ulift (u : level) (t : expr) : tactic expr := do u' ← mk_meta_univ, t ← mcond (succeeds $ infer_type t >>= unify (expr.sort (level.succ u'))) (pure t) (mk_app ``plift [t] <|> do { t ← pp t, fail format!"plift {t}" }), let ulift_t : expr := expr.const ``ulift [u,u'], pure $ ulift_t t meta def induction_state := (list (name × list ((expr × option expr) × expr))) meta def mk_encode (n : name) (u : level) : tactic $ bool × induction_state := do x ← intro1, b ← is_recursive_type n, when b $ do { size ← to_expr ``(sizeof %%x) >>= mk_up u, refine ``(encode %%size >> _) }, vs ← better_induction x, gs ← get_goals, prod.mk b <$> mzip_with (λ (g : ℕ × expr) (c : name × list (expr × option expr) × list (name × expr)), do let ⟨i,g⟩ := g, set_goals [g], when (gs.length ≠ 1) $ refine ``(write_word (fin.of_nat %%(reflect i)) >> _), let ⟨c,vs,_⟩ := c, vs' ← vs.mmap $ infer_type ∘ prod.fst, vs.mmap' (λ v, do t ← infer_type v.1, match v.2 with | none := do v ← mk_up u v.1, refine ``(encode %%v >> _) | (some rec_call) := do refine ``(%%rec_call >> _) end ), refine ``(pure punit.star), (c,vs.zip vs') <$ done) gs.enum vs meta def mk_parser (u : level) : expr → list ((expr × option expr) × expr) → list (name × expr) → option expr → tactic unit | e [] _ rec_call := refine ``(pure %%e) | e (((v,rec),t) :: vs) σ rec_call := do let t := t.instantiate_locals σ, ulift_t ← mk_ulift u t, v' ← match rec_call <* rec with | none := do refine ``(decode %%ulift_t >>= _), v' ← intro1, mk_down u v' t | (some rec_call) := refine ``(%%rec_call >>= _) >> intro1 end, mk_parser (e v') vs ( (v.local_uniq_name,v') :: σ ) rec_call meta def mk_decode (is_rec : bool) (args : list expr) (u : level) (n : name) (pat : induction_state) : tactic unit := do if pat.length = 1 then do let ⟨c,vs⟩ := pat.head, c ← mk_const c, mk_parser u (c.mk_app args) vs [] none else do rec_call ← if is_rec then do nat_t ← mk_ulift u `(nat), refine ``(decode %%nat_t >>= _), n ← intro1, refine ``(recursive_parser (ulift.down %%n) _), some <$> intro `rec_call else pure none, refine ``(select_tag _), pat.enum.mmap' $ λ ⟨i,c,vs⟩, do { v₀ ← mk_mvar, v₁ ← mk_mvar, refine ``((fin.of_nat %%(reflect i),%%v₀) :: %%v₁), set_goals [v₀], c ← mk_const c, mk_parser u (c.mk_app args) vs [] rec_call, done, set_goals [v₁] }, refine ``([]) meta def reduce_select_tag (tag : expr) : expr → tactic unit | `( list.cons (fin.of_nat %%n, %%br) %%brs ) := if n =ₐ tag then do v ← mk_mvar, to_expr ``(read_write_tag_hit %%v) >>= rewrite_target <|> (to_expr ``(read_write_tag_hit' %%v) >>= rewrite_target), gs ← get_goals, set_goals [v], tactic.interactive.norm_num [] (loc.ns [none]), done, set_goals gs else do v ← mk_mvar, to_expr ``(read_write_tag_miss %%v) >>= rewrite_target, gs ← get_goals, set_goals [v], do { applyc ``fin.ne_of_vne, let rs := list.map simp_arg_type.expr [``(fin.of_nat),``(fin.val),``(nat.succ_eq_add_one)], tactic.interactive.norm_num rs (loc.ns [none]), done }, set_goals gs, reduce_select_tag brs | e := failed meta def match_sum_branch : tactic unit := do brs ← mk_mvar, tag ← mk_mvar, tgt ← target, mcond (succeeds $ to_expr ``(select_tag %%brs -<< (write_word (fin.of_nat %%tag) >> _) = _) >>= change <|> (to_expr ``(select_tag %%brs -<< (write_word (fin.of_nat %%tag)) = _) >>= change)) (do brs ← instantiate_mvars brs, tag ← instantiate_mvars tag, reduce_select_tag tag brs) skip meta def prove_bound (n : name) : tactic unit := solve1 $ do h ← get_local `h, transitivity; [skip, () <$ apply h], dunfold_target [``sizeof], dunfold_target [``sizeof,``has_sizeof.sizeof,n <.> "sizeof"], try $ to_expr ``(1 + 0 ≤ _) >>= change, (`[ac_mono*]; try ( applyc ``nat.zero_le) ) <|> reflexivity, done <|> do { repeat $ applyc ``nat.le_add_right <|> applyc ``nat.le_add_of_le_left, try $ reflexivity }, return () meta def mk_serial_correctness (is_rec : bool) (n encode_n decode_n : name) : tactic unit := do let rules := [``has_bind.and_then, ``encode_decode_bind,``encode_decode_bind', ``encode_decode_pure], rules ← rules.mmap ((<$>) simp_arg_type.expr ∘ resolve_name), w ← intro1, dunfold_target [decode_n], dunfold_target [encode_n], simp none ff rules [] (loc.ns [none]), hs ← if is_rec then do { tactic.interactive.generalize `h () (``(sizeof %%w),`k), k ← get_local `k, h ← get_local `h, replace `h ``(le_of_eq %%h), revert k, better_induction w <* all_goals (() <$ intro_lst [`k,`h]) } else better_induction w, gs ← get_goals, mzip_with' (λ g (h : name × list (expr × option expr) × list (name × expr)), do { set_goals [g], let ⟨_,ih,_⟩ := h, let ih := ih.filter_map prod.snd, when is_rec $ `[rw recursive_parser_unfold], solve1 $ do { match_sum_branch, ih.mmap' $ λ hh, do { try $ simp none ff rules [] (loc.ns [none]), bound ← mk_mvar, mcond (succeeds $ to_expr ``((_ >>= _) -<< (_ >> _) = _) >>= change) (do dunfold_target [``has_bind.and_then], to_expr ``(read_write_mono $ %%hh _ %%bound) >>= rewrite_target) (do to_expr ``((_ >>= _) -<< _ = _) >>= change, to_expr ``(read_write_mono_left $ %%hh _ %%bound) >>= rewrite_target), gs ← get_goals, set_goals [bound], h ← get_local `h, applyc ``nat.le_sub_right_of_add_le, prove_bound n, set_goals gs }, simp none ff rules [] (loc.ns [none]) <|> reflexivity }, when is_rec $ prove_bound n, done, pure () }) gs hs meta def mk_serial_instance : tactic unit := expand_untrusted $ do tgt ← target, let t := tgt.app_arg, let args := t.get_app_args, (expr.sort (level.succ u)) ← infer_type t, let n := t.get_app_fn.const_name, d ← get_decl n, let t := d.is_trusted, enc ← mk_mvar, dec ← mk_mvar, correct ← mk_mvar, reset_instance_cache, refine ``( { encode := %%enc, decode := %%dec, correctness := %%correct } ), let decode_n := n <.> "decode", let encode_n := n <.> "encode", set_goals [enc], (is_rec,vs) ← extract_def' encode_n t (mk_encode n u), set_goals [dec], extract_def' decode_n t (mk_decode is_rec args u n vs), set_goals [correct], mk_serial_correctness is_rec n encode_n decode_n @[derive_handler] meta def serial_derive_handler : derive_handler := instance_derive_handler ``serial mk_serial_instance end tactic
587df682d03ec6cadb455766261409116141d22e
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/topology/constructions.lean
364c38d99dce7c20b4f8411c5e27b6d03eb96ec5
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
38,683
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down /-- The image of a dense set under `quotient.mk` is a dense set. -/ lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) := (surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H /-- The composition of `quotient.mk` and a function with dense range has dense range. -/ lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) := (surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := (hf.comp continuous_fst).prod_mk (hg.comp continuous_snd) lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma continuous_uncurry_left {f : α → β → γ} (a : α) (h : continuous (function.uncurry f)) : continuous (f a) := show continuous (function.uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity) lemma continuous_uncurry_right {f : α → β → γ} (b : β) (h : continuous (function.uncurry f)) : continuous (λ a, f a b) := show continuous (function.uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity) lemma continuous_curry {g : α × β → γ} (a : α) (h : continuous g) : continuous (function.curry g a) := show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity) lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (hs.preimage continuous_fst) (ht.preimage continuous_snd) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), set.prod u v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { rw nhds_prod_eq, exact ha.prod hb } lemma filter.has_basis.prod_nhds' {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {ab : α × β} (ha : (𝓝 ab.1).has_basis pa sa) (hb : (𝓝 ab.2).has_basis pb sb) : (𝓝 ab).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { cases ab, exact ha.prod_nhds hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_iff {s : set α} {t : set β} {a : α} {b : β} : s.prod t ∈ 𝓝 (a, b) ↔ s ∈ 𝓝 a ∧ t ∈ 𝓝 b := by rw [nhds_prod_eq, prod_mem_prod_iff] lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := prod_mem_nhds_iff.2 ⟨ha, hb⟩ lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := (hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at) lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := have hf : continuous_at f (x, y).fst, from hf, have hg : continuous_at g (x, y).snd, from hg, hf.prod_map hg lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α] {f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (function.uncurry f) := continuous_iff_continuous_at.2 $ λ ⟨a, b⟩, by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘), function.uncurry, (h a).tendsto] /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- `prod.fst` maps neighborhood of `x : α × β` within the section `prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ lemma map_fst_nhds_within (x : α × β) : map prod.fst (𝓝[prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := begin refine le_antisymm (continuous_at_fst.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_sets_of_superset hu (λ z hz, H _ hz _ (mem_of_nhds hv) rfl) end @[simp] lemma map_fst_nhds (x : α × β) : map prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuous_at_fst $ (map_fst_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_fst_nhds x).ge /-- `prod.snd` maps neighborhood of `x : α × β` within the section `prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ lemma map_snd_nhds_within (x : α × β) : map prod.snd (𝓝[prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := begin refine le_antisymm (continuous_at_snd.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_sets_of_superset hv (λ z hz, H _ (mem_of_nhds hu) _ hz rfl) end @[simp] lemma map_snd_nhds (x : α × β) : map prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuous_at_snd $ (map_snd_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma interior_prod_eq (s : set α) (t : set β) : interior (s.prod t) = (interior s).prod (interior t) := set.ext $ λ ⟨a, b⟩, by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] lemma frontier_prod_eq (s : set α) (t : set β) : frontier (s.prod t) = (closure s).prod (frontier t) ∪ (frontier s).prod (closure t) := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] lemma frontier_prod_univ_eq (s : set α) : frontier (s.prod (univ : set β)) = (frontier s).prod univ := by simp [frontier_prod_eq] @[simp] lemma frontier_univ_prod_eq (s : set β) : frontier ((univ : set α).prod s) = (univ : set α).prod (frontier s) := by simp [frontier_prod_eq] lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (s.prod t) := λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ } /-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/ lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := by simpa only [dense_range, prod_range_range_eq] using hf.prod hg lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := begin apply continuous_sup_dom; rw continuous_def at hf hg ⊢; assumption end lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, have : inl ⁻¹' (@inl α β '' u) = u := preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this, have : inr ⁻¹' (@inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, have : inl ⁻¹' (@inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this, have : inr ⁻¹' (@inr α β '' u) = u := preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := is_open_range_inl, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := is_open_range_inr, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ lemma closed_embedding_subtype_coe (h : is_closed {a | p a}) : closed_embedding (coe : subtype p → α) := ⟨embedding_subtype_coe, by rwa [subtype.range_coe_subtype]⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_of_mem $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, (closed_embedding_subtype_coe (h_is_closed _)).is_closed_map _ (hs.preimage (f_cont i)), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from locally_finite.is_closed_Union (h_lf.subset $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom /-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is continuous. -/ @[continuity] lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} : continuous (λ x : π i, function.update f i x) := begin refine continuous_pi (λj, _), by_cases h : j = i, { rw h, simpa using continuous_id }, { simpa [h] using continuous_const } end lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by simp [nhds_pi, filter.tendsto_comap_iff] lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _)) lemma is_closed_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hs : ∀a∈i, is_closed (s a)) : is_closed (pi i s) := by rw [pi_def]; exact (is_closed_Inter $ λ a, is_closed_Inter $ λ ha, (hs _ ha).preimage (continuous_apply _)) lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)} {x : Π a, π a} (hi : finite i) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by { rw [pi_def, bInter_mem_sets hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) } lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end variables [fintype ι] [∀ i, topological_space (π i)] [∀ i, discrete_topology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discrete_topology : discrete_topology (Π i, π i) := singletons_open_iff_discrete.mp (λ x, begin rw show {x} = ⋂ i, {y : Π i, π i | y i = x i}, { ext, simp only [function.funext_iff, set.mem_singleton_iff, set.mem_Inter, set.mem_set_of_eq] }, exact is_open_Inter (λ i, (continuous_apply i).is_open_preimage {x i} (is_open_discrete {x i})) end) end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
6149ff763f87f21fa1d840cfa8d53ba86ca534b6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/mul_add_auto.lean
940504f8e5d4eecc0815ac8db91fd3b920ded9c7
[]
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
19,046
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, Callum Sutton, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.hom import Mathlib.algebra.group.type_tags import Mathlib.algebra.group.units_hom import Mathlib.PostPort universes u_8 u_9 l u_3 u_4 u_1 u_5 u_2 u_6 u_7 namespace Mathlib /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (A : Type u_8) (B : Type u_9) [Add A] [Add B] extends add_hom A B, A ≃ B where /-- The `equiv` underlying an `add_equiv`. -/ /-- The `add_hom` underlying a `add_equiv`. -/ /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ structure mul_equiv (M : Type u_8) (N : Type u_9) [Mul M] [Mul N] extends mul_hom M N, M ≃ N where infixl:25 " ≃* " => Mathlib.mul_equiv infixl:25 " ≃+ " => Mathlib.add_equiv /-- The `equiv` underlying a `mul_equiv`. -/ /-- The `mul_hom` underlying a `mul_equiv`. -/ namespace mul_equiv protected instance has_coe_to_fun {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] : has_coe_to_fun (M ≃* N) := has_coe_to_fun.mk (fun (x : M ≃* N) => M → N) to_fun @[simp] theorem Mathlib.add_equiv.to_fun_apply {M : Type u_3} {N : Type u_4} [Add M] [Add N] {f : M ≃+ N} {m : M} : add_equiv.to_fun f m = coe_fn f m := rfl @[simp] theorem Mathlib.add_equiv.to_equiv_apply {M : Type u_3} {N : Type u_4} [Add M] [Add N] {f : M ≃+ N} {m : M} : coe_fn (add_equiv.to_equiv f) m = coe_fn f m := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp] theorem map_mul {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] (f : M ≃* N) (x : M) (y : M) : coe_fn f (x * y) = coe_fn f x * coe_fn f y := map_mul' f /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ def mk' {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] (f : M ≃ N) (h : ∀ (x y : M), coe_fn f (x * y) = coe_fn f x * coe_fn f y) : M ≃* N := mk (equiv.to_fun f) (equiv.inv_fun f) (equiv.left_inv f) (equiv.right_inv f) h protected theorem Mathlib.add_equiv.bijective {M : Type u_3} {N : Type u_4} [Add M] [Add N] (e : M ≃+ N) : function.bijective ⇑e := equiv.bijective (add_equiv.to_equiv e) protected theorem Mathlib.add_equiv.injective {M : Type u_3} {N : Type u_4} [Add M] [Add N] (e : M ≃+ N) : function.injective ⇑e := equiv.injective (add_equiv.to_equiv e) protected theorem Mathlib.add_equiv.surjective {M : Type u_3} {N : Type u_4} [Add M] [Add N] (e : M ≃+ N) : function.surjective ⇑e := equiv.surjective (add_equiv.to_equiv e) /-- The identity map is a multiplicative isomorphism. -/ def refl (M : Type u_1) [Mul M] : M ≃* M := mk (equiv.to_fun (equiv.refl M)) (equiv.inv_fun (equiv.refl M)) sorry sorry sorry protected instance inhabited {M : Type u_3} [Mul M] : Inhabited (M ≃* M) := { default := refl M } /-- The inverse of an isomorphism is an isomorphism. -/ def Mathlib.add_equiv.symm {M : Type u_3} {N : Type u_4} [Add M] [Add N] (h : M ≃+ N) : N ≃+ M := add_equiv.mk (equiv.to_fun (equiv.symm (add_equiv.to_equiv h))) (equiv.inv_fun (equiv.symm (add_equiv.to_equiv h))) sorry sorry sorry /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. def simps.inv_fun {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] (e : M ≃* N) : N → M := ⇑(symm e) @[simp] theorem Mathlib.add_equiv.to_equiv_symm {M : Type u_3} {N : Type u_4} [Add M] [Add N] (f : M ≃+ N) : add_equiv.to_equiv (add_equiv.symm f) = equiv.symm (add_equiv.to_equiv f) := rfl @[simp] theorem Mathlib.add_equiv.coe_mk {M : Type u_3} {N : Type u_4} [Add M] [Add N] (f : M → N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) (h₃ : ∀ (x y : M), f (x + y) = f x + f y) : ⇑(add_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp] theorem Mathlib.add_equiv.coe_symm_mk {M : Type u_3} {N : Type u_4} [Add M] [Add N] (f : M → N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) (h₃ : ∀ (x y : M), f (x + y) = f x + f y) : ⇑(add_equiv.symm (add_equiv.mk f g h₁ h₂ h₃)) = g := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ def Mathlib.add_equiv.trans {M : Type u_3} {N : Type u_4} {P : Type u_5} [Add M] [Add N] [Add P] (h1 : M ≃+ N) (h2 : N ≃+ P) : M ≃+ P := add_equiv.mk (equiv.to_fun (equiv.trans (add_equiv.to_equiv h1) (add_equiv.to_equiv h2))) (equiv.inv_fun (equiv.trans (add_equiv.to_equiv h1) (add_equiv.to_equiv h2))) sorry sorry sorry /-- e.right_inv in canonical form -/ @[simp] theorem apply_symm_apply {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] (e : M ≃* N) (y : N) : coe_fn e (coe_fn (symm e) y) = y := equiv.apply_symm_apply (to_equiv e) /-- e.left_inv in canonical form -/ @[simp] theorem Mathlib.add_equiv.symm_apply_apply {M : Type u_3} {N : Type u_4} [Add M] [Add N] (e : M ≃+ N) (x : M) : coe_fn (add_equiv.symm e) (coe_fn e x) = x := equiv.symm_apply_apply (add_equiv.to_equiv e) @[simp] theorem Mathlib.add_equiv.refl_apply {M : Type u_3} [Add M] (m : M) : coe_fn (add_equiv.refl M) m = m := rfl @[simp] theorem Mathlib.add_equiv.trans_apply {M : Type u_3} {N : Type u_4} {P : Type u_5} [Add M] [Add N] [Add P] (e₁ : M ≃+ N) (e₂ : N ≃+ P) (m : M) : coe_fn (add_equiv.trans e₁ e₂) m = coe_fn e₂ (coe_fn e₁ m) := rfl @[simp] theorem Mathlib.add_equiv.apply_eq_iff_eq {M : Type u_3} {N : Type u_4} [Add M] [Add N] (e : M ≃+ N) {x : M} {y : M} : coe_fn e x = coe_fn e y ↔ x = y := function.injective.eq_iff (add_equiv.injective e) theorem Mathlib.add_equiv.apply_eq_iff_symm_apply {M : Type u_3} {N : Type u_4} [Add M] [Add N] (e : M ≃+ N) {x : M} {y : N} : coe_fn e x = y ↔ x = coe_fn (add_equiv.symm e) y := equiv.apply_eq_iff_eq_symm_apply (add_equiv.to_equiv e) theorem symm_apply_eq {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] (e : M ≃* N) {x : N} {y : M} : coe_fn (symm e) x = y ↔ x = coe_fn e y := equiv.symm_apply_eq (to_equiv e) theorem eq_symm_apply {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] (e : M ≃* N) {x : N} {y : M} : y = coe_fn (symm e) x ↔ coe_fn e y = x := equiv.eq_symm_apply (to_equiv e) /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp] theorem Mathlib.add_equiv.map_zero {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (h : M ≃+ N) : coe_fn h 0 = 0 := sorry @[simp] theorem Mathlib.add_equiv.map_eq_zero_iff {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (h : M ≃+ N) {x : M} : coe_fn h x = 0 ↔ x = 0 := add_equiv.map_zero h ▸ equiv.apply_eq_iff_eq (add_equiv.to_equiv h) theorem map_ne_one_iff {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (h : M ≃* N) {x : M} : coe_fn h x ≠ 1 ↔ x ≠ 1 := { mp := mt (iff.mpr (map_eq_one_iff h)), mpr := mt (iff.mp (map_eq_one_iff h)) } /-- A bijective `monoid` homomorphism is an isomorphism -/ def Mathlib.add_equiv.of_bijective {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) (hf : function.bijective ⇑f) : M ≃+ N := add_equiv.mk (equiv.to_fun (equiv.of_bijective (⇑f) hf)) (equiv.inv_fun (equiv.of_bijective (⇑f) hf)) sorry sorry (add_monoid_hom.map_add' f) /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ def Mathlib.add_equiv.to_add_monoid_hom {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (h : M ≃+ N) : M →+ N := add_monoid_hom.mk (add_equiv.to_fun h) (add_equiv.map_zero h) sorry @[simp] theorem coe_to_monoid_hom {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (e : M ≃* N) : ⇑(to_monoid_hom e) = ⇑e := rfl theorem Mathlib.add_equiv.to_add_monoid_hom_apply {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (e : M ≃+ N) (x : M) : coe_fn (add_equiv.to_add_monoid_hom e) x = coe_fn e x := rfl /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp] theorem map_inv {G : Type u_6} {H : Type u_7} [group G] [group H] (h : G ≃* H) (x : G) : coe_fn h (x⁻¹) = (coe_fn h x⁻¹) := monoid_hom.map_inv (to_monoid_hom h) x /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ theorem ext {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] {f : M ≃* N} {g : M ≃* N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g := sorry protected theorem congr_arg {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] {f : M ≃* N} {x : M} {x' : M} : x = x' → coe_fn f x = coe_fn f x' := sorry protected theorem congr_fun {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] {f : M ≃* N} {g : M ≃* N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x := h ▸ rfl theorem ext_iff {M : Type u_3} {N : Type u_4} [Mul M] [Mul N] {f : M ≃* N} {g : M ≃* N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := ext } theorem Mathlib.add_equiv.to_add_monoid_hom_injective {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] : function.injective add_equiv.to_add_monoid_hom := fun (f g : M ≃+ N) (h : add_equiv.to_add_monoid_hom f = add_equiv.to_add_monoid_hom g) => add_equiv.ext (iff.mp add_monoid_hom.ext_iff h) end mul_equiv -- We don't use `to_additive` to generate definition because it fails to tell Lean about -- equational lemmas /-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms. -/ def add_monoid_hom.to_add_equiv {M : Type u_3} {N : Type u_4} [add_monoid M] [add_monoid N] (f : M →+ N) (g : N →+ M) (h₁ : add_monoid_hom.comp g f = add_monoid_hom.id M) (h₂ : add_monoid_hom.comp f g = add_monoid_hom.id N) : M ≃+ N := add_equiv.mk ⇑f ⇑g sorry sorry (add_monoid_hom.map_add f) /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ def monoid_hom.to_mul_equiv {M : Type u_3} {N : Type u_4} [monoid M] [monoid N] (f : M →* N) (g : N →* M) (h₁ : monoid_hom.comp g f = monoid_hom.id M) (h₂ : monoid_hom.comp f g = monoid_hom.id N) : M ≃* N := mul_equiv.mk ⇑f ⇑g sorry sorry (monoid_hom.map_mul f) @[simp] theorem monoid_hom.coe_to_mul_equiv {M : Type u_3} {N : Type u_4} [monoid M] [monoid N] (f : M →* N) (g : N →* M) (h₁ : monoid_hom.comp g f = monoid_hom.id M) (h₂ : monoid_hom.comp f g = monoid_hom.id N) : ⇑(monoid_hom.to_mul_equiv f g h₁ h₂) = ⇑f := rfl /-- An additive equivalence of additive groups preserves subtraction. -/ theorem add_equiv.map_sub {A : Type u_1} {B : Type u_2} [add_group A] [add_group B] (h : A ≃+ B) (x : A) (y : A) : coe_fn h (x - y) = coe_fn h x - coe_fn h y := add_monoid_hom.map_sub (add_equiv.to_add_monoid_hom h) x y protected instance add_equiv.inhabited {M : Type u_1} [Add M] : Inhabited (M ≃+ M) := { default := add_equiv.refl M } /-- A group is isomorphic to its group of units. -/ def to_add_units {G : Type u_1} [add_group G] : G ≃+ add_units G := add_equiv.mk (fun (x : G) => add_units.mk x (-x) (add_neg_self x) (neg_add_self x)) coe sorry sorry sorry namespace units /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv {M : Type u_3} {N : Type u_4} [monoid M] [monoid N] (h : M ≃* N) : units M ≃* units N := mul_equiv.mk (monoid_hom.to_fun (map (mul_equiv.to_monoid_hom h))) ⇑(map (mul_equiv.to_monoid_hom (mul_equiv.symm h))) sorry sorry sorry /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ def mul_left {M : Type u_3} [monoid M] (u : units M) : equiv.perm M := equiv.mk (fun (x : M) => ↑u * x) (fun (x : M) => ↑(u⁻¹) * x) (inv_mul_cancel_left u) (mul_inv_cancel_left u) @[simp] theorem coe_mul_left {M : Type u_3} [monoid M] (u : units M) : ⇑(mul_left u) = Mul.mul ↑u := rfl @[simp] theorem Mathlib.add_units.add_left_symm {M : Type u_3} [add_monoid M] (u : add_units M) : equiv.symm (add_units.add_left u) = add_units.add_left (-u) := equiv.ext fun (x : M) => rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ def mul_right {M : Type u_3} [monoid M] (u : units M) : equiv.perm M := equiv.mk (fun (x : M) => x * ↑u) (fun (x : M) => x * ↑(u⁻¹)) sorry sorry @[simp] theorem Mathlib.add_units.coe_add_right {M : Type u_3} [add_monoid M] (u : add_units M) : ⇑(add_units.add_right u) = fun (x : M) => x + ↑u := rfl @[simp] theorem Mathlib.add_units.add_right_symm {M : Type u_3} [add_monoid M] (u : add_units M) : equiv.symm (add_units.add_right u) = add_units.add_right (-u) := equiv.ext fun (x : M) => rfl end units namespace equiv /-- Left multiplication in a `group` is a permutation of the underlying type. -/ protected def add_left {G : Type u_6} [add_group G] (a : G) : perm G := add_units.add_left (coe_fn to_add_units a) @[simp] theorem coe_add_left {G : Type u_6} [add_group G] (a : G) : ⇑(equiv.add_left a) = Add.add a := rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp] theorem add_left_symm_apply {G : Type u_6} [add_group G] (a : G) : ⇑(equiv.symm (equiv.add_left a)) = Add.add (-a) := rfl @[simp] theorem mul_left_symm {G : Type u_6} [group G] (a : G) : equiv.symm (equiv.mul_left a) = equiv.mul_left (a⁻¹) := ext fun (x : G) => rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ protected def add_right {G : Type u_6} [add_group G] (a : G) : perm G := add_units.add_right (coe_fn to_add_units a) @[simp] theorem coe_mul_right {G : Type u_6} [group G] (a : G) : ⇑(equiv.mul_right a) = fun (x : G) => x * a := rfl @[simp] theorem mul_right_symm {G : Type u_6} [group G] (a : G) : equiv.symm (equiv.mul_right a) = equiv.mul_right (a⁻¹) := ext fun (x : G) => rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp] theorem add_right_symm_apply {G : Type u_6} [add_group G] (a : G) : ⇑(equiv.symm (equiv.add_right a)) = fun (x : G) => x + -a := rfl /-- Inversion on a `group` is a permutation of the underlying type. -/ protected def neg (G : Type u_6) [add_group G] : perm G := mk (fun (a : G) => -a) (fun (a : G) => -a) sorry sorry @[simp] theorem coe_inv {G : Type u_6} [group G] : ⇑(equiv.inv G) = has_inv.inv := rfl @[simp] theorem neg_symm {G : Type u_6} [add_group G] : equiv.symm (equiv.neg G) = equiv.neg G := rfl end equiv /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative {G : Type u_6} {H : Type u_7} [add_monoid G] [add_monoid H] : G ≃+ H ≃ (multiplicative G ≃* multiplicative H) := equiv.mk (fun (f : G ≃+ H) => mul_equiv.mk ⇑(coe_fn add_monoid_hom.to_multiplicative (add_equiv.to_add_monoid_hom f)) ⇑(coe_fn add_monoid_hom.to_multiplicative (add_equiv.to_add_monoid_hom (add_equiv.symm f))) sorry sorry sorry) (fun (f : multiplicative G ≃* multiplicative H) => add_equiv.mk ⇑(mul_equiv.to_monoid_hom f) ⇑(mul_equiv.to_monoid_hom (mul_equiv.symm f)) sorry sorry sorry) sorry sorry /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive {G : Type u_6} {H : Type u_7} [monoid G] [monoid H] : G ≃* H ≃ (additive G ≃+ additive H) := equiv.mk (fun (f : G ≃* H) => add_equiv.mk ⇑(coe_fn monoid_hom.to_additive (mul_equiv.to_monoid_hom f)) ⇑(coe_fn monoid_hom.to_additive (mul_equiv.to_monoid_hom (mul_equiv.symm f))) sorry sorry sorry) (fun (f : additive G ≃+ additive H) => mul_equiv.mk ⇑(add_equiv.to_add_monoid_hom f) ⇑(add_equiv.to_add_monoid_hom (add_equiv.symm f)) sorry sorry sorry) sorry sorry /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' {G : Type u_6} {H : Type u_7} [monoid G] [add_monoid H] : additive G ≃+ H ≃ (G ≃* multiplicative H) := equiv.mk (fun (f : additive G ≃+ H) => mul_equiv.mk ⇑(coe_fn add_monoid_hom.to_multiplicative' (add_equiv.to_add_monoid_hom f)) ⇑(coe_fn add_monoid_hom.to_multiplicative'' (add_equiv.to_add_monoid_hom (add_equiv.symm f))) sorry sorry sorry) (fun (f : G ≃* multiplicative H) => add_equiv.mk ⇑(mul_equiv.to_monoid_hom f) ⇑(mul_equiv.to_monoid_hom (mul_equiv.symm f)) sorry sorry sorry) sorry sorry /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' {G : Type u_6} {H : Type u_7} [monoid G] [add_monoid H] : G ≃* multiplicative H ≃ (additive G ≃+ H) := equiv.symm add_equiv.to_multiplicative' /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' {G : Type u_6} {H : Type u_7} [add_monoid G] [monoid H] : G ≃+ additive H ≃ (multiplicative G ≃* H) := equiv.mk (fun (f : G ≃+ additive H) => mul_equiv.mk ⇑(coe_fn add_monoid_hom.to_multiplicative'' (add_equiv.to_add_monoid_hom f)) ⇑(coe_fn add_monoid_hom.to_multiplicative' (add_equiv.to_add_monoid_hom (add_equiv.symm f))) sorry sorry sorry) (fun (f : multiplicative G ≃* H) => add_equiv.mk ⇑(mul_equiv.to_monoid_hom f) ⇑(mul_equiv.to_monoid_hom (mul_equiv.symm f)) sorry sorry sorry) sorry sorry /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' {G : Type u_6} {H : Type u_7} [add_monoid G] [monoid H] : multiplicative G ≃* H ≃ (G ≃+ additive H) := equiv.symm add_equiv.to_multiplicative'' end Mathlib
c9d8a5d57579544b9a41251c00344aace10ba529
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/normed_space/finite_dimension.lean
601d123000db6b5f761f79af773a88f26d219368
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,577
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.normed_space.affine_isometry import analysis.normed_space.operator_norm import analysis.asymptotics.asymptotic_equivalent import linear_algebra.finite_dimensional /-! # Finite dimensional normed spaces over complete fields Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a complete field is continuous. * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w x open set finite_dimensional topological_space filter asymptotics open_locale classical big_operators filter topological_space asymptotics noncomputable theory /-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/ lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜] {E : Type v} [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_smul 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f := begin -- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous -- function. have : (f : (ι → 𝕜) → E) = (λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))), by { ext x, exact f.pi_apply_eq_sum_univ x }, rw this, refine continuous_finset_sum _ (λi hi, _), exact (continuous_apply i).smul continuous_const end section complete_field variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {F : Type w} [normed_group F] [normed_space 𝕜 F] {F' : Type x} [add_comm_group F'] [module 𝕜 F'] [topological_space F'] [topological_add_group F'] [has_continuous_smul 𝕜 F'] [complete_space 𝕜] /-- In finite dimension over a complete field, the canonical identification (in terms of a basis) with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that all norms are equivalent in finite dimension. This statement is superceded by the fact that every linear map on a finite-dimensional space is continuous, in `linear_map.continuous_of_finite_dimensional`. -/ lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : basis ι 𝕜 E) : continuous ξ.equiv_fun := begin unfreezingI { induction hn : fintype.card ι with n IH generalizing ι E }, { apply linear_map.continuous_of_bound _ 0 (λx, _), have : ξ.equiv_fun x = 0, by { ext i, exact (fintype.card_eq_zero_iff.1 hn).elim i }, change ∥ξ.equiv_fun x∥ ≤ 0 * ∥x∥, rw this, simp [norm_nonneg] }, { haveI : finite_dimensional 𝕜 E := of_fintype_basis ξ, -- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent -- to a standard space of dimension n, hence it is complete and therefore closed. have H₁ : ∀s : submodule 𝕜 E, finrank 𝕜 s = n → is_closed (s : set E), { assume s s_dim, let b := basis.of_vector_space 𝕜 s, have U : uniform_embedding b.equiv_fun.symm.to_equiv, { have : fintype.card (basis.of_vector_space_index 𝕜 s) = n, by { rw ← s_dim, exact (finrank_eq_card_basis b).symm }, have : continuous b.equiv_fun := IH b this, exact b.equiv_fun.symm.uniform_embedding (linear_map.continuous_on_pi _) this }, have : is_complete (s : set E), from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)), exact this.is_closed }, -- second step: any linear form is continuous, as its kernel is closed by the first step have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f, { assume f, have : finrank 𝕜 f.ker = n ∨ finrank 𝕜 f.ker = n.succ, { have Z := f.finrank_range_add_finrank_ker, rw [finrank_eq_card_basis ξ, hn] at Z, by_cases H : finrank 𝕜 f.range = 0, { right, rw H at Z, simpa using Z }, { left, have : finrank 𝕜 f.range = 1, { refine le_antisymm _ (zero_lt_iff.mpr H), simpa [finrank_self] using f.range.finrank_le }, rw [this, add_comm, nat.add_one] at Z, exact nat.succ.inj Z } }, have : is_closed (f.ker : set E), { cases this, { exact H₁ _ this }, { have : f.ker = ⊤, by { apply eq_top_of_finrank_eq, rw [finrank_eq_card_basis ξ, hn, this] }, simp [this] } }, exact linear_map.continuous_iff_is_closed_ker.2 this }, -- third step: applying the continuity to the linear form corresponding to a coefficient in the -- basis decomposition, deduce that all such coefficients are controlled in terms of the norm have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥ξ.equiv_fun x i∥ ≤ C * ∥x∥, { assume i, let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i) ∘ₗ ↑ξ.equiv_fun, let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f }, exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ }, -- fourth step: combine the bound on each coefficient to get a global bound and the continuity choose C0 hC0 using this, let C := ∑ i, C0 i, have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1), have C0_le : ∀i, C0 i ≤ C := λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _), apply linear_map.continuous_of_bound _ C (λx, _), rw pi_semi_norm_le_iff, { exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) }, { exact mul_nonneg C_nonneg (norm_nonneg _) } } end /-- Any linear map on a finite dimensional space over a complete field is continuous. -/ theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : continuous f := begin -- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and -- argue that all linear maps there are continuous. let b := basis.of_vector_space 𝕜 E, have A : continuous b.equiv_fun := continuous_equiv_fun_basis b, have B : continuous (f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) := linear_map.continuous_on_pi _, have : continuous ((f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) ∘ b.equiv_fun) := B.comp A, convert this, ext x, dsimp, rw [basis.equiv_fun_symm_apply, basis.sum_repr] end theorem affine_map.continuous_of_finite_dimensional {PE PF : Type*} [metric_space PE] [normed_add_torsor E PE] [metric_space PF] [normed_add_torsor F PF] [finite_dimensional 𝕜 E] (f : PE →ᵃ[𝕜] PF) : continuous f := affine_map.continuous_linear_iff.1 f.linear.continuous_of_finite_dimensional namespace linear_map variables [finite_dimensional 𝕜 E] /-- The continuous linear map induced by a linear map on a finite dimensional space -/ def to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F' := { to_fun := λ f, ⟨f, f.continuous_of_finite_dimensional⟩, inv_fun := coe, map_add' := λ f g, rfl, map_smul' := λ c f, rfl, left_inv := λ f, rfl, right_inv := λ f, continuous_linear_map.coe_injective rfl } @[simp] lemma coe_to_continuous_linear_map' (f : E →ₗ[𝕜] F') : ⇑f.to_continuous_linear_map = f := rfl @[simp] lemma coe_to_continuous_linear_map (f : E →ₗ[𝕜] F') : (f.to_continuous_linear_map : E →ₗ[𝕜] F') = f := rfl @[simp] lemma coe_to_continuous_linear_map_symm : ⇑(to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F').symm = coe := rfl end linear_map /-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/ def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F := { continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F := e.finite_dimensional, exact e.symm.to_linear_map.continuous_of_finite_dimensional end, ..e } lemma linear_map.exists_antilipschitz_with [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F) (hf : f.ker = ⊥) : ∃ K > 0, antilipschitz_with K f := begin cases subsingleton_or_nontrivial E; resetI, { exact ⟨1, zero_lt_one, antilipschitz_with.of_subsingleton⟩ }, { let e : E ≃L[𝕜] f.range := (linear_equiv.of_injective f hf).to_continuous_linear_equiv, exact ⟨_, e.nnnorm_symm_pos, e.antilipschitz⟩ } end protected lemma linear_independent.eventually {ι} [fintype ι] {f : ι → E} (hf : linear_independent 𝕜 f) : ∀ᶠ g in 𝓝 f, linear_independent 𝕜 g := begin simp only [fintype.linear_independent_iff'] at hf ⊢, rcases linear_map.exists_antilipschitz_with _ hf with ⟨K, K0, hK⟩, have : tendsto (λ g : ι → E, ∑ i, ∥g i - f i∥) (𝓝 f) (𝓝 $ ∑ i, ∥f i - f i∥), from tendsto_finset_sum _ (λ i hi, tendsto.norm $ ((continuous_apply i).tendsto _).sub tendsto_const_nhds), simp only [sub_self, norm_zero, finset.sum_const_zero] at this, refine (this.eventually (gt_mem_nhds $ inv_pos.2 K0)).mono (λ g hg, _), replace hg : ∑ i, nnnorm (g i - f i) < K⁻¹, by { rw ← nnreal.coe_lt_coe, push_cast, exact hg }, rw linear_map.ker_eq_bot, refine (hK.add_sub_lipschitz_with (lipschitz_with.of_dist_le_mul $ λ v u, _) hg).injective, simp only [dist_eq_norm, linear_map.lsum_apply, pi.sub_apply, linear_map.sum_apply, linear_map.comp_apply, linear_map.proj_apply, linear_map.smul_right_apply, linear_map.id_apply, ← finset.sum_sub_distrib, ← smul_sub, ← sub_smul, nnreal.coe_sum, coe_nnnorm, finset.sum_mul], refine norm_sum_le_of_le _ (λ i _, _), rw [norm_smul, mul_comm], exact mul_le_mul_of_nonneg_left (norm_le_pi_norm (v - u) i) (norm_nonneg _) end lemma is_open_set_of_linear_independent {ι : Type*} [fintype ι] : is_open {f : ι → E | linear_independent 𝕜 f} := is_open_iff_mem_nhds.2 $ λ f, linear_independent.eventually lemma is_open_set_of_nat_le_rank (n : ℕ) : is_open {f : E →L[𝕜] F | ↑n ≤ rank (f : E →ₗ[𝕜] F)} := begin simp only [le_rank_iff_exists_linear_independent_finset, set_of_exists, ← exists_prop], refine is_open_bUnion (λ t ht, _), have : continuous (λ f : E →L[𝕜] F, (λ x : (t : set E), f x)), from continuous_pi (λ x, (continuous_linear_map.apply 𝕜 F (x : E)).continuous), exact is_open_set_of_linear_independent.preimage this end /-- Two finite-dimensional normed spaces are continuously linearly equivalent if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : nonempty (E ≃L[𝕜] F) := (nonempty_linear_equiv_of_finrank_eq cond).map linear_equiv.to_continuous_linear_equiv /-- Two finite-dimensional normed spaces are continuously linearly equivalent if and only if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_iff_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] : nonempty (E ≃L[𝕜] F) ↔ finrank 𝕜 E = finrank 𝕜 F := ⟨ λ ⟨h⟩, h.to_linear_equiv.finrank_eq, λ h, finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq h ⟩ /-- A continuous linear equivalence between two finite-dimensional normed spaces of the same (finite) dimension. -/ def continuous_linear_equiv.of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : E ≃L[𝕜] F := (linear_equiv.of_finrank_eq E F cond).to_continuous_linear_equiv variables {ι : Type*} [fintype ι] /-- Construct a continuous linear map given the value at a finite basis. -/ def basis.constrL (v : basis ι 𝕜 E) (f : ι → F) : E →L[𝕜] F := by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v; exact (v.constr 𝕜 f).to_continuous_linear_map @[simp, norm_cast] lemma basis.coe_constrL (v : basis ι 𝕜 E) (f : ι → F) : (v.constrL f : E →ₗ[𝕜] F) = v.constr 𝕜 f := rfl /-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and functions from its basis indexing type to `𝕜`. -/ def basis.equiv_funL (v : basis ι 𝕜 E) : E ≃L[𝕜] (ι → 𝕜) := { continuous_to_fun := begin haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v, apply linear_map.continuous_of_finite_dimensional, end, continuous_inv_fun := begin change continuous v.equiv_fun.symm.to_fun, apply linear_map.continuous_of_finite_dimensional, end, ..v.equiv_fun } @[simp] lemma basis.constrL_apply (v : basis ι 𝕜 E) (f : ι → F) (e : E) : (v.constrL f) e = ∑ i, (v.equiv_fun e i) • f i := v.constr_apply_fintype 𝕜 _ _ @[simp] lemma basis.constrL_basis (v : basis ι 𝕜 E) (f : ι → F) (i : ι) : (v.constrL f) (v i) = f i := v.constr_basis 𝕜 _ _ lemma basis.sup_norm_le_norm (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ), ∀ e : E, ∑ i, ∥v.equiv_fun e i∥ ≤ C * ∥e∥ := begin set φ := v.equiv_funL.to_continuous_linear_map, set C := ∥φ∥ * (fintype.card ι), use [max C 1, lt_of_lt_of_le (zero_lt_one) (le_max_right C 1)], intros e, calc ∑ i, ∥φ e i∥ ≤ ∑ i : ι, ∥φ e∥ : by { apply finset.sum_le_sum, exact λ i hi, norm_le_pi_norm (φ e) i } ... = ∥φ e∥*(fintype.card ι) : by simpa only [mul_comm, finset.sum_const, nsmul_eq_mul] ... ≤ ∥φ∥ * ∥e∥ * (fintype.card ι) : mul_le_mul_of_nonneg_right (φ.le_op_norm e) (fintype.card ι).cast_nonneg ... = ∥φ∥ * (fintype.card ι) * ∥e∥ : by ring ... ≤ max C 1 * ∥e∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) end lemma basis.op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M := begin obtain ⟨C, C_pos, hC⟩ : ∃ C > (0 : ℝ), ∀ (e : E), ∑ i, ∥v.equiv_fun e i∥ ≤ C * ∥e∥, from v.sup_norm_le_norm, use [C, C_pos], intros u M hM hu, apply u.op_norm_le_bound (mul_nonneg (le_of_lt C_pos) hM), intros e, calc ∥u e∥ = ∥u (∑ i, v.equiv_fun e i • v i)∥ : by rw [v.sum_equiv_fun] ... = ∥∑ i, (v.equiv_fun e i) • (u $ v i)∥ : by simp [u.map_sum, linear_map.map_smul] ... ≤ ∑ i, ∥(v.equiv_fun e i) • (u $ v i)∥ : norm_sum_le _ _ ... = ∑ i, ∥v.equiv_fun e i∥ * ∥u (v i)∥ : by simp only [norm_smul] ... ≤ ∑ i, ∥v.equiv_fun e i∥ * M : finset.sum_le_sum (λ i hi, mul_le_mul_of_nonneg_left (hu i) (norm_nonneg _)) ... = (∑ i, ∥v.equiv_fun e i∥) * M : finset.sum_mul.symm ... ≤ C * ∥e∥ * M : mul_le_mul_of_nonneg_right (hC e) hM ... = C * M * ∥e∥ : by ring end instance [finite_dimensional 𝕜 E] [second_countable_topology F] : second_countable_topology (E →L[𝕜] F) := begin set d := finite_dimensional.finrank 𝕜 E, suffices : ∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε, from metric.second_countable_of_countable_discretization (λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩), intros ε ε_pos, obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F, let v := finite_dimensional.fin_basis 𝕜 E, obtain ⟨C : ℝ, C_pos : 0 < C, hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ := v.op_norm_le, have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos, have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C, have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (v.constrL $ u ∘ n)∥ ≤ ε/2, { intros φ, have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C), { simp only [norm_sub_rev], intro i, have : φ (v i) ∈ closure (range u) := hu _, obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C), { rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this, specialize this (ε/(2*C)) hε2C, simpa [dist_eq_norm] }, exact ⟨n, le_of_lt hn⟩ }, choose n hn using this, use n, replace hn : ∀ i : fin d, ∥(φ - (v.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn], have : C * (ε / (2 * C)) = ε/2, { rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc, mul_div_cancel' _ (ne_of_gt h_2C)] }, specialize hC (le_of_lt hε2C) hn, rwa this at hC }, choose n hn using this, set Φ := λ φ : E →L[𝕜] F, (v.constrL $ u ∘ (n φ)), change ∀ z, dist z (Φ z) ≤ ε/2 at hn, use n, intros x y hxy, calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _ ... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm] ... ≤ ε : by linarith [hn x, hn y] end /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, have : uniform_embedding e.to_linear_equiv.to_equiv.symm := e.symm.uniform_embedding, exact (complete_space_congr this).1 (by apply_instance) end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s) /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := s.complete_of_finite_dimensional.is_closed lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F] (f : E →L[𝕜] F) (hf : f.range = ⊤) : ∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F := let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in ⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩ lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) := begin haveI : finite_dimensional 𝕜 (submodule.span 𝕜 {c}) := finite_dimensional.span_of_finite 𝕜 (finite_singleton c), have m1 : closed_embedding (coe : submodule.span 𝕜 {c} → E) := (submodule.span 𝕜 {c}).closed_of_finite_dimensional.closed_embedding_subtype_coe, have m2 : closed_embedding (linear_equiv.to_span_nonzero_singleton 𝕜 E c hc : 𝕜 → submodule.span 𝕜 {c}) := (continuous_linear_equiv.to_span_nonzero_singleton 𝕜 c hc).to_homeomorph.closed_embedding, exact m1.comp m2 end /- `smul` is a closed map in the first argument. -/ lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) := begin by_cases hc : c = 0, { simp_rw [hc, smul_zero], exact is_closed_map_const }, { exact (closed_embedding_smul_left hc).is_closed_map } end end complete_field section proper_field variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜] (E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, exact e.symm.antilipschitz.proper_space e.symm.continuous e.symm.surjective end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ instance finite_dimensional.proper_real (E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E attribute [instance, priority 900] finite_dimensional.proper_real /-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in any complete normed space, while the other holds only in finite dimensional spaces. -/ lemma summable_norm_iff {α E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : α → E} : summable (λ x, ∥f x∥) ↔ summable f := begin refine ⟨summable_of_summable_norm, λ hf, _⟩, -- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ` suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥), { obtain v := fin_basis ℝ E, set e := v.equiv_funL, have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf), refine summable_of_norm_bounded _ (this.mul_left ↑(nnnorm (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E))) (λ i, _), simpa using (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) }, unfreezingI { clear_dependent E }, -- Now we deal with `g : α → fin N → ℝ` intros N g hg, have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs, refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _), rw [norm_norm, pi_norm_le_iff], { refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i), exact norm_nonneg (g x i) }, { exact finset.sum_nonneg (λ _ _, norm_nonneg _) } end lemma summable_of_is_O' {ι E F : Type*} [normed_group E] [complete_space E] [normed_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ι → E} {g : ι → F} (hg : summable g) (h : is_O f g cofinite) : summable f := summable_of_is_O (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_O_nat' {E F : Type*} [normed_group E] [complete_space E] [normed_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ℕ → E} {g : ℕ → F} (hg : summable g) (h : is_O f g at_top) : summable f := summable_of_is_O_nat (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_equivalent {ι E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (hg : summable g) (h : f ~[cofinite] g) : summable f := hg.trans_sub (summable_of_is_O' hg h.is_o.is_O) lemma summable_of_is_equivalent_nat {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (hg : summable g) (h : f ~[at_top] g) : summable f := hg.trans_sub (summable_of_is_O_nat' hg h.is_o.is_O) lemma is_equivalent.summable_iff {ι E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (h : f ~[cofinite] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent hf h.symm, λ hg, summable_of_is_equivalent hg h⟩ lemma is_equivalent.summable_iff_nat {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (h : f ~[at_top] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent_nat hf h.symm, λ hg, summable_of_is_equivalent_nat hg h⟩
3cc290ceb6b60ef4c05ec9743ed4c7c8518b8bc1
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p1_categories/c3_wtypes/s2_exp.lean
adc1cf316f1d496d22a889410ba20449fc64082c
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
13,598
lean
/- ----------------------------------------------------------------------- Exponential obejcts. ----------------------------------------------------------------------- -/ import ..c1_basic import ..c2_limits namespace qp open stdaux universe variables ℓobjx ℓhomx ℓobj ℓhom /-! #brief An exponential object. -/ class HasExp (C : Cat.{ℓobj ℓhom}) (X Y : C^.obj) := (exp : C^.obj) (ev : ∀ [exp_Y_HasFinProduct : HasFinProduct C [exp, Y]] , C^.hom (finproduct C [exp, Y]) X) (univ : ∀ (Z : C^.obj) [Z_Y_HasFinProduct : HasFinProduct C [Z, Y]] (e : C^.hom (finproduct C [Z, Y]) X) , C^.hom Z exp) (factor : ∀ [exp_Y_HasFinProduct : HasFinProduct C [exp, Y]] (Z : C^.obj) [Z_Y_HasFinProduct : HasFinProduct C [Z, Y]] (e : C^.hom (finproduct C [Z, Y]) X) , e = ev ∘∘ finproduct.hom (univ Z e ↗ C^.id Y ↗↗)) (uniq : ∀ [exp_Y_HasFinProduct : HasFinProduct C [exp, Y]] (Z : C^.obj) [Z_Y_HasFinProduct : HasFinProduct C [Z, Y]] (e : C^.hom (finproduct C [Z, Y]) X) (u : C^.hom Z exp) (ωu : e = ev ∘∘ finproduct.hom (u ↗ C^.id Y ↗↗)) , u = univ Z e) /-! #brief A category with all exponential obejcts. -/ class HasAllExp (C : Cat.{ℓobj ℓhom}) := (has_exp : ∀ (X Y : C^.obj), HasExp C X Y) instance HasAllExp.HasExp {C : Cat.{ℓobj ℓhom}} [C_HasAllExp : HasAllExp C] (X Y : C^.obj) : HasExp C X Y := HasAllExp.has_exp X Y /-! #brief A category which locally has all exponential obejcts. -/ class HasAllLocalExp (C : Cat.{ℓobj ℓhom}) := (has_exp : ∀ (A : C^.obj) (X Y : (OverCat C A)^.obj) , HasExp (OverCat C A) X Y) instance HasAllLocalExp.HasAllExp (C : Cat.{ℓobj ℓhom}) [C_HasAllLocalExp : HasAllLocalExp C] (A : C^.obj) : HasAllExp (OverCat C A) := { has_exp := HasAllLocalExp.has_exp A } /-! #brief An exponential object. -/ definition expon (C : Cat.{ℓobj ℓhom}) (X Y : C^.obj) [X_Y_HasExp : HasExp C X Y] : C^.obj := HasExp.exp X Y /-! #brief An evaluation map. -/ definition expon.eval (C : Cat.{ℓobj ℓhom}) (X Y : C^.obj) [X_Y_HasExp : HasExp C X Y] [exp_Y_HasFinProduct : HasFinProduct C [expon C X Y, Y]] : C^.hom (finproduct C [expon C X Y, Y]) X := HasExp.ev X Y /-! #brief A universal map. -/ definition expon.univ (C : Cat.{ℓobj ℓhom}) {X Y : C^.obj} [X_Y_HasExp : HasExp C X Y] {Z : C^.obj} [Z_Y_HasFinProduct : HasFinProduct C [Z, Y]] (e : C^.hom (finproduct C [Z, Y]) X) : C^.hom Z (expon C X Y) := HasExp.univ Z e /-! #brief The universal map factors. -/ theorem expon.univ.factor {C : Cat.{ℓobj ℓhom}} {X Y : C^.obj} [X_Y_HasExp : HasExp C X Y] [exp_Y_HasFinProduct : HasFinProduct C [expon C X Y, Y]] {Z : C^.obj} [Z_Y_HasFinProduct : HasFinProduct C [Z, Y]] {e : C^.hom (finproduct C [Z, Y]) X} : e = expon.eval C X Y ∘∘ finproduct.hom (expon.univ C e ↗ C^.id Y ↗↗) := HasExp.factor Z e /-! #brief The universal map is unique. -/ theorem expon.univ.uniq {C : Cat.{ℓobj ℓhom}} {X Y : C^.obj} [X_Y_HasExp : HasExp C X Y] [exp_Y_HasFinProduct : HasFinProduct C [expon C X Y, Y]] {Z : C^.obj} [Z_Y_HasFinProduct : HasFinProduct C [Z, Y]] (e : C^.hom (finproduct C [Z, Y]) X) (u : C^.hom Z (expon C X Y)) (ωu : e = expon.eval C X Y ∘∘ finproduct.hom (u ↗ C^.id Y ↗↗)) : u = expon.univ C e := @HasExp.uniq C X Y X_Y_HasExp exp_Y_HasFinProduct Z Z_Y_HasFinProduct e u ωu /-! #brief The universal map induced by eval is the identity. -/ theorem expon.univ_eval {C : Cat.{ℓobj ℓhom}} {X Y : C^.obj} [X_Y_HasExp : HasExp C X Y] [exp_Y_HasFinProduct : HasFinProduct C [expon C X Y, Y]] : expon.univ C (expon.eval C X Y) = C^.id (expon C X Y) := eq.symm (expon.univ.uniq _ _ (eq.trans (eq.symm C^.circ_id_right) (Cat.circ.congr_right (eq.symm finproduct.hom₂.id)))) /- ----------------------------------------------------------------------- Homs induce maps between exponentials. ----------------------------------------------------------------------- -/ /-! #brief Hom induced by composition on the right. -/ definition expon.circ_right {C : Cat.{ℓobj ℓhom}} {Z X Y : C^.obj} [Z_X_HasExp : HasExp C Z X] [Z_Y_HasExp : HasExp C Z Y] [exp_Y_HasFinProduct : HasFinProduct C [expon C Z Y, Y]] [exp_X_HasFinProduct : HasFinProduct C [expon C Z Y, X]] (f : C^.hom X Y) : C^.hom (expon C Z Y) (expon C Z X) := expon.univ C (C^.circ (expon.eval C Z Y) (finproduct.hom (C^.id (expon C Z Y) ↗ f ↗↗))) /-! #brief Hom induced by composition on the left. -/ definition expon.circ_left {C : Cat.{ℓobj ℓhom}} {X Y Z : C^.obj} [X_Z_HasExp : HasExp C X Z] [Y_Z_HasExp : HasExp C Y Z] [exp_Z_HasFinProduct : HasFinProduct C [expon C X Z, Z]] (g : C^.hom X Y) : C^.hom (expon C X Z) (expon C Y Z) := expon.univ C (C^.circ g (expon.eval C X Z)) /-! #brief Exponential objects are unique up-to unique isomorphism. -/ definition expon.iso {C : Cat.{ℓobj ℓhom}} {X Y : C^.obj} (X_Y_HasExp₁ X_Y_HasExp₂ : HasExp C X Y) [exp_Y_HasFinProduct₁ : HasFinProduct C [@expon C X Y X_Y_HasExp₁, Y]] : C^.hom (@expon C X Y X_Y_HasExp₁) (@expon C X Y X_Y_HasExp₂) := @expon.circ_left C X X Y X_Y_HasExp₁ X_Y_HasExp₂ exp_Y_HasFinProduct₁ (C^.id X) theorem expon.iso.eq {C : Cat.{ℓobj ℓhom}} {X Y : C^.obj} (X_Y_HasExp₁ X_Y_HasExp₂ : HasExp C X Y) [exp_Y_HasFinProduct₁ : HasFinProduct C [@expon C X Y X_Y_HasExp₁, Y]] [exp_Y_HasFinProduct₂ : HasFinProduct C [@expon C X Y X_Y_HasExp₂, Y]] : expon.iso X_Y_HasExp₂ X_Y_HasExp₁ ∘∘ expon.iso X_Y_HasExp₁ X_Y_HasExp₂ = C^.id (@expon C X Y X_Y_HasExp₁) := begin unfold expon.iso expon.circ_left, repeat { rw C^.circ_id_left }, rw -expon.univ_eval, refine @expon.univ.uniq C X Y X_Y_HasExp₁ exp_Y_HasFinProduct₁ _ exp_Y_HasFinProduct₁ _ _ _, refine eq.trans _ (Cat.circ.congr_right (eq.trans (eq.symm (finproduct.hom₂.circ (@expon.univ C _ _ X_Y_HasExp₁ _ exp_Y_HasFinProduct₂ (@expon.eval C X Y X_Y_HasExp₂ exp_Y_HasFinProduct₂)) ⟨⟨Y⟩⟩ (@expon.univ C _ _ X_Y_HasExp₂ _ exp_Y_HasFinProduct₁ (@expon.eval C X Y X_Y_HasExp₁ exp_Y_HasFinProduct₁)) ⟨⟨Y⟩⟩)) (by rw C^.circ_id_right))), refine eq.trans _ (eq.symm C^.circ_assoc), refine eq.trans _ (Cat.circ.congr_left (@expon.univ.factor C X Y X_Y_HasExp₁ _ _ exp_Y_HasFinProduct₂ _)), apply expon.univ.factor end /-! #brief Exponential objects are unique up-to unique isomorphism. -/ definition expon.Iso {C : Cat.{ℓobj ℓhom}} {X Y : C^.obj} (X_Y_HasExp₁ X_Y_HasExp₂ : HasExp C X Y) [exp_Y_HasFinProduct₁ : HasFinProduct C [@expon C X Y X_Y_HasExp₁, Y]] [exp_Y_HasFinProduct₂ : HasFinProduct C [@expon C X Y X_Y_HasExp₂, Y]] : Iso (expon.iso X_Y_HasExp₁ X_Y_HasExp₂) (expon.iso X_Y_HasExp₂ X_Y_HasExp₁) := { id₁ := expon.iso.eq X_Y_HasExp₁ X_Y_HasExp₂ , id₂ := expon.iso.eq X_Y_HasExp₂ X_Y_HasExp₁ } /- ----------------------------------------------------------------------- The exponential functor. ----------------------------------------------------------------------- -/ /-! #brief The exponential functor. -/ definition ExpFun (C : Cat.{ℓobj ℓhom}) [C_HasAllExp : HasAllExp C] [C_HasAllFinProducts : HasAllFinProducts C] (W : C^.obj) : Fun C C := { obj := λ X, expon C X W , hom := λ X Y f, expon.circ_left f , hom_id := λ X , begin dsimp [expon.circ_left], rw C^.circ_id_left, apply expon.univ_eval end , hom_circ := λ X Y Z g f , begin dsimp [expon.circ_left], refine eq.symm (expon.univ.uniq _ _ _), refine eq.trans _ (Cat.circ.congr_right (eq.trans (eq.symm (finproduct.hom₂.circ (expon.univ C (g ∘∘ expon.eval C Y W)) ⟨⟨W⟩⟩ (expon.univ C (f ∘∘ expon.eval C X W)) ⟨⟨W⟩⟩)) (by rw C^.circ_id_right))), refine eq.trans _ (eq.symm C^.circ_assoc), refine eq.trans _ (Cat.circ.congr_left expon.univ.factor), refine eq.trans (eq.symm C^.circ_assoc) (eq.trans (Cat.circ.congr_right expon.univ.factor) C^.circ_assoc), end } -- /- ----------------------------------------------------------------------- -- The dependent product functor. -- ----------------------------------------------------------------------- -/ -- /-! #brief The fiber functor. -- -/ -- definition FiberFun {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllExp : HasAllExp (OverCat C A)] -- [C_HasAllFinProducts : HasAllFinProducts (OverCat C A)] -- : Fun (OverCat C A) (OverCat C A) -- := ExpFun (OverCat C A) { obj := B, hom := f } -- /-! #brief The dependent product functor. -- -/ -- definition DepProdFun {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllExp : HasAllExp (OverCat C A)] -- [C_HasAllFinProducts : HasAllFinProducts (OverCat C A)] -- : Fun (OverCat C B) (OverCat C A) -- := FiberFun f □□ DepSumFun f -- /-! #brief Preservation of co-limits by DepProdFun. -- -/ -- instance DepProdFun.PresCoLimit {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllExp : HasAllExp (OverCat C A)] -- [C_HasAllFinProducts : HasAllFinProducts (OverCat C A)] -- [f_HasPullbacksAlong : HasPullbacksAlong C f] -- {X : Cat.{ℓobjx ℓhomx}} -- (L : Fun X (OverCat C B)) -- [f_PresCoLimitsFrom : PresCoLimitsFrom (FiberFun f) X] -- : PresCoLimit L (DepProdFun f) -- := @PresCoLimit.comp _ _ _ _ -- L (DepSumFun f) -- (Adj.left.PresCoLimit (DepSum_BaseChange.Adj f) L) -- (FiberFun f) -- (PresCoLimitsFrom.pres_colimit (FiberFun f) _) -- /-! #brief Counit of the adjunction between base change and dependent product. -- -/ -- definition BaseChange_DepProd.Adj.counit.com {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllLocalExp : HasAllLocalExp C] -- [C_HasAllPullbacks : HasAllPullbacks C] -- : ∀ (Q : OverObj C B) -- , OverHom C B -- ((BaseChangeFun f □□ DepProdFun f)^.obj Q) -- Q -- | (OverObj.mk Q h) -- := { hom := (expon.eval (OverCat C A) (OverObj.mk Q (f ∘∘ h)) (OverObj.mk B f))^.hom -- ∘∘ sorry -- -- begin -- -- dsimp [Fun.comp, BaseChangeFun, HasAllExp.DepProdFun, ExpFun, BaseChangeFun.obj, OverObj.dom], -- -- end -- , triangle := sorry -- } -- /-! #brief Counit of the adjunction between base change and dependent product. -- -/ -- definition BaseChange_DepProd.Adj.counit {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllLocalExp : HasAllLocalExp C] -- [C_HasAllPullbacks : HasAllPullbacks C] -- : NatTrans (BaseChangeFun f □□ DepProdFun f) -- (Fun.id (OverCat C B)) -- := { com := BaseChange_DepProd.Adj.counit.com f -- , natural -- := λ X Y h -- , sorry -- } -- /-! #brief Unit of the adjunction between base change and dependent product. -- -/ -- definition BaseChange_DepProd.Adj.unit.com {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllLocalExp : HasAllLocalExp C] -- [C_HasAllPullbacks : HasAllPullbacks C] -- (Q : OverObj C A) -- : OverHom C A -- Q -- ((DepProdFun f □□ BaseChangeFun f)^.obj Q) -- := { hom := -- (expon.univ (OverCat C A) -- begin -- dsimp [Fun.comp, DepSumFun, BaseChangeFun, DepProdFun, ExpFun, BaseChangeFun.obj, OverObj.dom], -- exact sorry -- end -- )^.hom -- , triangle := sorry -- } -- /-! #brief Unit of the adjunction between base change and dependent product. -- -/ -- definition BaseChange_DepProd.Adj.unit {C : Cat.{ℓobj ℓhom}} -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllLocalExp : HasAllLocalExp C] -- [C_HasAllPullbacks : HasAllPullbacks C] -- : NatTrans (Fun.id (OverCat C A)) -- (DepProdFun f □□ BaseChangeFun f) -- := { com := BaseChange_DepProd.Adj.unit.com f -- , natural -- := λ X Y h -- , sorry -- } -- /-! #brief Base change is adjoint to dependent product. -- -/ -- definition BaseChange_DepProd.Adj (C : Cat.{ℓobj ℓhom}) -- {B A : C^.obj} (f : C^.hom B A) -- [C_HasAllLocalExp : HasAllLocalExp C] -- [C_HasAllPullbacks : HasAllPullbacks C] -- : Adj (BaseChangeFun f) (DepProdFun f) -- := { counit := BaseChange_DepProd.Adj.counit f -- , unit := BaseChange_DepProd.Adj.unit f -- , id_left := sorry -- , id_right := sorry -- } -- /-! #brief Locally cartesian closed categories have dependent product. -- -/ -- instance HasAllExp.HasDepProdFun (C : Cat.{ℓobj ℓhom}) -- [C_HasAllLocalExp : HasAllLocalExp C] -- [C_HasAllPullbacks : HasAllPullbacks C] -- : HasDepProdFun C -- := { depprod := λ x y f, HasAllExp.DepProdFun C f -- , adj := λ x y f f_HasPullbacksAlong, begin end -- HasAllExp.BaseChange_DepProd.Adj C f -- } end qp
3d95fee54ec80d15e41d12fee91cd706022fe341
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/squeeze.lean
d735221df3ce730f20e05c93e4e9cc2a9fa9afd3
[]
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,640
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.traversable.basic import Mathlib.tactic.simpa import Mathlib.PostPort namespace Mathlib /-- pretty print a `loc` -/ /-- shift `pos` `n` columns to the left -/ namespace tactic /-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/ /-- pretty print structure instance -/ /-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/ /-- dummy declaration used as target of `squeeze_loc` attribute -/ def squeeze_loc_attr_carrier : Unit := Unit.unit /-- Format a list of arguments for use with `simp` and friends. This omits the list entirely if it is empty. -/ /-- Emit a suggestion to the user. If inside a `squeeze_scope` block, the suggestions emitted through `mk_suggestion` will be aggregated so that every tactic that makes a suggestion can consider multiple execution of the same invocation. If `at_pos` is true, make the suggestion at `p` instead of the current position. -/ /-- translate a `pexpr` into a `simp` configuration -/ /-- translate a `pexpr` into a `dsimp` configuration -/ /-- `same_result proof tac` runs tactic `tac` and checks if the proof produced by `tac` is equivalent to `proof`. -/ /-- `filter_simp_set g call_simp user_args simp_args` returns `args'` such that, when calling `call_simp tt /- only -/ args'` on the goal `g` (`g` is a meta var) we end up in the same state as if we had called `call_simp ff (user_args ++ simp_args)` and removing any one element of `args'` changes the resulting proof. -/ /-- make a `simp_arg_type` that references the name given as an argument -/ /-- tactic combinator to create a `simp`-like tactic that minimizes its argument list. * `slow`: adds all rfl-lemmas from the environment to the initial list (this is a slower but more accurate strategy) * `no_dflt`: did the user use the `only` keyword? * `args`: list of `simp` arguments * `tac`: how to invoke the underlying `simp` tactic -/ namespace interactive /-- Turn a `simp_arg_type` into a string. -/ /-- combinator meant to aggregate the suggestions issued by multiple calls of `squeeze_simp` (due, for instance, to `;`). Can be used as: ```lean example {α β} (xs ys : list α) (f : α → β) : (xs ++ ys.tail).map f = xs.map f ∧ (xs.tail.map f).length = xs.length := begin have : xs = ys, admit, squeeze_scope { split; squeeze_simp, -- `squeeze_simp` is run twice, the first one requires -- `list.map_append` and the second one `[list.length_map, list.length_tail]` -- prints only one message and combine the suggestions: -- > Try this: simp only [list.length_map, list.length_tail, list.map_append] squeeze_simp [this] -- `squeeze_simp` is run only once -- prints: -- > Try this: simp only [this] }, end ``` -/ /-- `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp` perform the same task with the difference that `squeeze_simp` relates to `simp` while `squeeze_simpa` relates to `simpa` and `squeeze_dsimp` relates to `dsimp`. The following applies to `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp`. `squeeze_simp` behaves like `simp` (including all its arguments) and prints a `simp only` invocation to skip the search through the `simp` lemma list. For instance, the following is easily solved with `simp`: ```lean example : 0 + 1 = 1 + 0 := by simp ``` To guide the proof search and speed it up, we may replace `simp` with `squeeze_simp`: ```lean example : 0 + 1 = 1 + 0 := by squeeze_simp -- prints: -- prints: -- Try this: simp only [add_zero, eq_self_iff_true, zero_add] -- Try this: simp only [add_zero, eq_self_iff_true, zero_add] ``` `squeeze_simp` suggests a replacement which we can use instead of `squeeze_simp`. ```lean example : 0 + 1 = 1 + 0 := by simp only [add_zero, eq_self_iff_true, zero_add] ``` `squeeze_simp only` prints nothing as it already skips the `simp` list. This tactic is useful for speeding up the compilation of a complete file. Steps: 1. search and replace ` simp` with ` squeeze_simp` (the space helps avoid the replacement of `simp` in `@[simp]`) throughout the file. 2. Starting at the beginning of the file, go to each printout in turn, copy the suggestion in place of `squeeze_simp`. 3. after all the suggestions were applied, search and replace `squeeze_simp` with `simp` to remove the occurrences of `squeeze_simp` that did not produce a suggestion. Known limitation(s): * in cases where `squeeze_simp` is used after a `;` (e.g. `cases x; squeeze_simp`), `squeeze_simp` will produce as many suggestions as the number of goals it is applied to. It is likely that none of the suggestion is a good replacement but they can all be combined by concatenating their list of lemmas. `squeeze_scope` can be used to combine the suggestions: `by squeeze_scope { cases x; squeeze_simp }` * sometimes, `simp` lemmas are also `_refl_lemma` and they can be used without appearing in the resulting proof. `squeeze_simp` won't know to try that lemma unless it is called as `squeeze_simp?` -/ /-- see `squeeze_simp` -/ /-- `squeeze_dsimp` behaves like `dsimp` (including all its arguments) and prints a `dsimp only` invocation to skip the search through the `simp` lemma list. See the doc string of `squeeze_simp` for examples. -/ end interactive end tactic
5cfdb5baaed0c1da57986019e4f064e43c3da031
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/seminorm.lean
651205d77c8058899639fdbcce57a5e0ee6cf45b
[ "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
26,054
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Yaël Dillies, Moritz Doll -/ import data.real.pointwise import data.real.sqrt import topology.algebra.filter_basis import topology.algebra.module.locally_convex /-! # Seminorms This file defines seminorms. A seminorm is a function to the reals which is positive-semidefinite, absolutely homogeneous, and subadditive. They are closely related to convex sets and a topological vector space is locally convex if and only if its topology is induced by a family of seminorms. ## Main declarations For a module over a normed ring: * `seminorm`: A function to the reals that is positive-semidefinite, absolutely homogeneous, and subadditive. * `norm_seminorm 𝕜 E`: The norm on `E` as a seminorm. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags seminorm, locally convex, LCTVS -/ set_option old_structure_cmd true open normed_field set open_locale big_operators nnreal pointwise topological_space variables {R R' 𝕜 E F G ι : Type*} /-- A seminorm on a module over a normed ring is a function to the reals that is positive semidefinite, positive homogeneous, and subadditive. -/ structure seminorm (𝕜 : Type*) (E : Type*) [semi_normed_ring 𝕜] [add_group E] [has_smul 𝕜 E] extends add_group_seminorm E := (smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ∥a∥ * to_fun x) attribute [nolint doc_blame] seminorm.to_add_group_seminorm /-- `seminorm_class F 𝕜 E` states that `F` is a type of seminorms on the `𝕜`-module E. You should extend this class when you extend `seminorm`. -/ class seminorm_class (F : Type*) (𝕜 E : out_param $ Type*) [semi_normed_ring 𝕜] [add_group E] [has_smul 𝕜 E] extends add_group_seminorm_class F E := (map_smul_eq_mul (f : F) (a : 𝕜) (x : E) : f (a • x) = ∥a∥ * f x) export seminorm_class (map_smul_eq_mul) -- `𝕜` is an `out_param`, so this is a false positive. attribute [nolint dangerous_instance] seminorm_class.to_add_group_seminorm_class section of /-- Alternative constructor for a `seminorm` on an `add_comm_group E` that is a module over a `semi_norm_ring 𝕜`. -/ def seminorm.of [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E] (f : E → ℝ) (add_le : ∀ (x y : E), f (x + y) ≤ f x + f y) (smul : ∀ (a : 𝕜) (x : E), f (a • x) = ∥a∥ * f x) : seminorm 𝕜 E := { to_fun := f, map_zero' := by rw [←zero_smul 𝕜 (0 : E), smul, norm_zero, zero_mul], add_le' := add_le, smul' := smul, neg' := λ x, by rw [←neg_one_smul 𝕜, smul, norm_neg, ← smul, one_smul] } /-- Alternative constructor for a `seminorm` over a normed field `𝕜` that only assumes `f 0 = 0` and an inequality for the scalar multiplication. -/ def seminorm.of_smul_le [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] (f : E → ℝ) (map_zero : f 0 = 0) (add_le : ∀ x y, f (x + y) ≤ f x + f y) (smul_le : ∀ (r : 𝕜) x, f (r • x) ≤ ∥r∥ * f x) : seminorm 𝕜 E := seminorm.of f add_le (λ r x, begin refine le_antisymm (smul_le r x) _, by_cases r = 0, { simp [h, map_zero] }, rw ←mul_le_mul_left (inv_pos.mpr (norm_pos_iff.mpr h)), rw inv_mul_cancel_left₀ (norm_ne_zero_iff.mpr h), specialize smul_le r⁻¹ (r • x), rw norm_inv at smul_le, convert smul_le, simp [h], end) end of namespace seminorm section semi_normed_ring variables [semi_normed_ring 𝕜] section add_group variables [add_group E] section has_smul variables [has_smul 𝕜 E] instance seminorm_class : seminorm_class (seminorm 𝕜 E) 𝕜 E := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_zero := λ f, f.map_zero', map_add_le_add := λ f, f.add_le', map_neg_eq_map := λ f, f.neg', map_smul_eq_mul := λ f, f.smul' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`. -/ instance : has_coe_to_fun (seminorm 𝕜 E) (λ _, E → ℝ) := fun_like.has_coe_to_fun @[ext] lemma ext {p q : seminorm 𝕜 E} (h : ∀ x, (p : E → ℝ) x = q x) : p = q := fun_like.ext p q h instance : has_zero (seminorm 𝕜 E) := ⟨{ smul' := λ _ _, (mul_zero _).symm, ..add_group_seminorm.has_zero.zero }⟩ @[simp] lemma coe_zero : ⇑(0 : seminorm 𝕜 E) = 0 := rfl @[simp] lemma zero_apply (x : E) : (0 : seminorm 𝕜 E) x = 0 := rfl instance : inhabited (seminorm 𝕜 E) := ⟨0⟩ variables (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ) /-- Any action on `ℝ` which factors through `ℝ≥0` applies to a seminorm. -/ instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] : has_smul R (seminorm 𝕜 E) := { smul := λ r p, { to_fun := λ x, r • p x, smul' := λ _ _, begin simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul], rw [map_smul_eq_mul, mul_left_comm], end, ..(r • p.to_add_group_seminorm) }} instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] [has_smul R' ℝ] [has_smul R' ℝ≥0] [is_scalar_tower R' ℝ≥0 ℝ] [has_smul R R'] [is_scalar_tower R R' ℝ] : is_scalar_tower R R' (seminorm 𝕜 E) := { smul_assoc := λ r a p, ext $ λ x, smul_assoc r a (p x) } lemma coe_smul [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] (r : R) (p : seminorm 𝕜 E) : ⇑(r • p) = r • p := rfl @[simp] lemma smul_apply [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] (r : R) (p : seminorm 𝕜 E) (x : E) : (r • p) x = r • p x := rfl instance : has_add (seminorm 𝕜 E) := { add := λ p q, { to_fun := λ x, p x + q x, smul' := λ a x, by simp only [map_smul_eq_mul, map_smul_eq_mul, mul_add], ..(p.to_add_group_seminorm + q.to_add_group_seminorm) }} lemma coe_add (p q : seminorm 𝕜 E) : ⇑(p + q) = p + q := rfl @[simp] lemma add_apply (p q : seminorm 𝕜 E) (x : E) : (p + q) x = p x + q x := rfl instance : add_monoid (seminorm 𝕜 E) := fun_like.coe_injective.add_monoid _ rfl coe_add (λ p n, coe_smul n p) instance : ordered_cancel_add_comm_monoid (seminorm 𝕜 E) := fun_like.coe_injective.ordered_cancel_add_comm_monoid _ rfl coe_add (λ p n, coe_smul n p) instance [monoid R] [mul_action R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] : mul_action R (seminorm 𝕜 E) := fun_like.coe_injective.mul_action _ coe_smul variables (𝕜 E) /-- `coe_fn` as an `add_monoid_hom`. Helper definition for showing that `seminorm 𝕜 E` is a module. -/ @[simps] def coe_fn_add_monoid_hom : add_monoid_hom (seminorm 𝕜 E) (E → ℝ) := ⟨coe_fn, coe_zero, coe_add⟩ lemma coe_fn_add_monoid_hom_injective : function.injective (coe_fn_add_monoid_hom 𝕜 E) := show @function.injective (seminorm 𝕜 E) (E → ℝ) coe_fn, from fun_like.coe_injective variables {𝕜 E} instance [monoid R] [distrib_mul_action R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] : distrib_mul_action R (seminorm 𝕜 E) := (coe_fn_add_monoid_hom_injective 𝕜 E).distrib_mul_action _ coe_smul instance [semiring R] [module R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] : module R (seminorm 𝕜 E) := (coe_fn_add_monoid_hom_injective 𝕜 E).module R _ coe_smul -- TODO: define `has_Sup` too, from the skeleton at -- https://github.com/leanprover-community/mathlib/pull/11329#issuecomment-1008915345 noncomputable instance : has_sup (seminorm 𝕜 E) := { sup := λ p q, { to_fun := p ⊔ q, smul' := λ x v, (congr_arg2 max (map_smul_eq_mul p x v) (map_smul_eq_mul q x v)).trans $ (mul_max_of_nonneg _ _ $ norm_nonneg x).symm, ..(p.to_add_group_seminorm ⊔ q.to_add_group_seminorm) } } @[simp] lemma coe_sup (p q : seminorm 𝕜 E) : ⇑(p ⊔ q) = p ⊔ q := rfl lemma sup_apply (p q : seminorm 𝕜 E) (x : E) : (p ⊔ q) x = p x ⊔ q x := rfl lemma smul_sup [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] (r : R) (p q : seminorm 𝕜 E) : r • (p ⊔ q) = r • p ⊔ r • q := have real.smul_max : ∀ x y : ℝ, r • max x y = max (r • x) (r • y), from λ x y, by simpa only [←smul_eq_mul, ←nnreal.smul_def, smul_one_smul ℝ≥0 r (_ : ℝ)] using mul_max_of_nonneg x y (r • 1 : ℝ≥0).prop, ext $ λ x, real.smul_max _ _ instance : partial_order (seminorm 𝕜 E) := partial_order.lift _ fun_like.coe_injective lemma le_def (p q : seminorm 𝕜 E) : p ≤ q ↔ (p : E → ℝ) ≤ q := iff.rfl lemma lt_def (p q : seminorm 𝕜 E) : p < q ↔ (p : E → ℝ) < q := iff.rfl noncomputable instance : semilattice_sup (seminorm 𝕜 E) := function.injective.semilattice_sup _ fun_like.coe_injective coe_sup end has_smul end add_group section module variables [add_comm_group E] [add_comm_group F] [add_comm_group G] variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G] variables [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] /-- Composition of a seminorm with a linear map is a seminorm. -/ def comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : seminorm 𝕜 E := { to_fun := λ x, p (f x), smul' := λ _ _, (congr_arg p (f.map_smul _ _)).trans (map_smul_eq_mul p _ _), ..(p.to_add_group_seminorm.comp f.to_add_monoid_hom) } lemma coe_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : ⇑(p.comp f) = p ∘ f := rfl @[simp] lemma comp_apply (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (x : E) : (p.comp f) x = p (f x) := rfl @[simp] lemma comp_id (p : seminorm 𝕜 E) : p.comp linear_map.id = p := ext $ λ _, rfl @[simp] lemma comp_zero (p : seminorm 𝕜 F) : p.comp (0 : E →ₗ[𝕜] F) = 0 := ext $ λ _, map_zero p @[simp] lemma zero_comp (f : E →ₗ[𝕜] F) : (0 : seminorm 𝕜 F).comp f = 0 := ext $ λ _, rfl lemma comp_comp (p : seminorm 𝕜 G) (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) : p.comp (g.comp f) = (p.comp g).comp f := ext $ λ _, rfl lemma add_comp (p q : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : (p + q).comp f = p.comp f + q.comp f := ext $ λ _, rfl lemma comp_add_le (p : seminorm 𝕜 F) (f g : E →ₗ[𝕜] F) : p.comp (f + g) ≤ p.comp f + p.comp g := λ _, map_add_le_add p _ _ lemma smul_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : R) : (c • p).comp f = c • (p.comp f) := ext $ λ _, rfl lemma comp_mono {p : seminorm 𝕜 F} {q : seminorm 𝕜 F} (f : E →ₗ[𝕜] F) (hp : p ≤ q) : p.comp f ≤ q.comp f := λ _, hp _ /-- The composition as an `add_monoid_hom`. -/ @[simps] def pullback (f : E →ₗ[𝕜] F) : seminorm 𝕜 F →+ seminorm 𝕜 E := ⟨λ p, p.comp f, zero_comp f, λ p q, add_comp p q f⟩ instance : order_bot (seminorm 𝕜 E) := ⟨0, map_nonneg⟩ @[simp] lemma coe_bot : ⇑(⊥ : seminorm 𝕜 E) = 0 := rfl lemma bot_eq_zero : (⊥ : seminorm 𝕜 E) = 0 := rfl lemma smul_le_smul {p q : seminorm 𝕜 E} {a b : ℝ≥0} (hpq : p ≤ q) (hab : a ≤ b) : a • p ≤ b • q := begin simp_rw [le_def, pi.le_def, coe_smul], intros x, simp_rw [pi.smul_apply, nnreal.smul_def, smul_eq_mul], exact mul_le_mul hab (hpq x) (map_nonneg p x) (nnreal.coe_nonneg b), end lemma finset_sup_apply (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) : s.sup p x = ↑(s.sup (λ i, ⟨p i x, map_nonneg (p i) x⟩) : ℝ≥0) := begin induction s using finset.cons_induction_on with a s ha ih, { rw [finset.sup_empty, finset.sup_empty, coe_bot, _root_.bot_eq_zero, pi.zero_apply, nonneg.coe_zero] }, { rw [finset.sup_cons, finset.sup_cons, coe_sup, sup_eq_max, pi.sup_apply, sup_eq_max, nnreal.coe_max, subtype.coe_mk, ih] } end lemma finset_sup_le_sum (p : ι → seminorm 𝕜 E) (s : finset ι) : s.sup p ≤ ∑ i in s, p i := begin classical, refine finset.sup_le_iff.mpr _, intros i hi, rw [finset.sum_eq_sum_diff_singleton_add hi, le_add_iff_nonneg_left], exact bot_le, end lemma finset_sup_apply_le {p : ι → seminorm 𝕜 E} {s : finset ι} {x : E} {a : ℝ} (ha : 0 ≤ a) (h : ∀ i, i ∈ s → p i x ≤ a) : s.sup p x ≤ a := begin lift a to ℝ≥0 using ha, rw [finset_sup_apply, nnreal.coe_le_coe], exact finset.sup_le h, end lemma finset_sup_apply_lt {p : ι → seminorm 𝕜 E} {s : finset ι} {x : E} {a : ℝ} (ha : 0 < a) (h : ∀ i, i ∈ s → p i x < a) : s.sup p x < a := begin lift a to ℝ≥0 using ha.le, rw [finset_sup_apply, nnreal.coe_lt_coe, finset.sup_lt_iff], { exact h }, { exact nnreal.coe_pos.mpr ha }, end end module end semi_normed_ring section semi_normed_comm_ring variables [semi_normed_comm_ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] lemma comp_smul (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : 𝕜) : p.comp (c • f) = ∥c∥₊ • p.comp f := ext $ λ _, by rw [comp_apply, smul_apply, linear_map.smul_apply, map_smul_eq_mul, nnreal.smul_def, coe_nnnorm, smul_eq_mul, comp_apply] lemma comp_smul_apply (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (c : 𝕜) (x : E) : p.comp (c • f) x = ∥c∥ * p (f x) := map_smul_eq_mul p _ _ end semi_normed_comm_ring section normed_field variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {p q : seminorm 𝕜 E} {x : E} /-- Auxiliary lemma to show that the infimum of seminorms is well-defined. -/ lemma bdd_below_range_add : bdd_below (range $ λ u, p u + q (x - u)) := ⟨0, by { rintro _ ⟨x, rfl⟩, exact add_nonneg (map_nonneg p _) (map_nonneg q _) }⟩ noncomputable instance : has_inf (seminorm 𝕜 E) := { inf := λ p q, { to_fun := λ x, ⨅ u : E, p u + q (x-u), smul' := begin intros a x, obtain rfl | ha := eq_or_ne a 0, { rw [norm_zero, zero_mul, zero_smul], refine cinfi_eq_of_forall_ge_of_forall_gt_exists_lt (λ i, add_nonneg (map_nonneg p _) (map_nonneg q _)) (λ x hx, ⟨0, by rwa [map_zero, sub_zero, map_zero, add_zero]⟩) }, simp_rw [real.mul_infi_of_nonneg (norm_nonneg a), mul_add, ←map_smul_eq_mul p, ←map_smul_eq_mul q, smul_sub], refine function.surjective.infi_congr ((•) a⁻¹ : E → E) (λ u, ⟨a • u, inv_smul_smul₀ ha u⟩) (λ u, _), rw smul_inv_smul₀ ha end, ..(p.to_add_group_seminorm ⊓ q.to_add_group_seminorm) }} @[simp] lemma inf_apply (p q : seminorm 𝕜 E) (x : E) : (p ⊓ q) x = ⨅ u : E, p u + q (x-u) := rfl noncomputable instance : lattice (seminorm 𝕜 E) := { inf := (⊓), inf_le_left := λ p q x, cinfi_le_of_le bdd_below_range_add x $ by simp only [sub_self, map_zero, add_zero], inf_le_right := λ p q x, cinfi_le_of_le bdd_below_range_add 0 $ by simp only [sub_self, map_zero, zero_add, sub_zero], le_inf := λ a b c hab hac x, le_cinfi $ λ u, (le_map_add_map_sub a _ _).trans $ add_le_add (hab _) (hac _), ..seminorm.semilattice_sup } lemma smul_inf [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] (r : R) (p q : seminorm 𝕜 E) : r • (p ⊓ q) = r • p ⊓ r • q := begin ext, simp_rw [smul_apply, inf_apply, smul_apply, ←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul, real.mul_infi_of_nonneg (subtype.prop _), mul_add], end end normed_field /-! ### Seminorm ball -/ section semi_normed_ring variables [semi_normed_ring 𝕜] section add_comm_group variables [add_comm_group E] section has_smul variables [has_smul 𝕜 E] (p : seminorm 𝕜 E) /-- The ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y` with `p (y - x) < `r`. -/ def ball (x : E) (r : ℝ) := { y : E | p (y - x) < r } variables {x y : E} {r : ℝ} @[simp] lemma mem_ball : y ∈ ball p x r ↔ p (y - x) < r := iff.rfl lemma mem_ball_zero : y ∈ ball p 0 r ↔ p y < r := by rw [mem_ball, sub_zero] lemma ball_zero_eq : ball p 0 r = { y : E | p y < r } := set.ext $ λ x, p.mem_ball_zero @[simp] lemma ball_zero' (x : E) (hr : 0 < r) : ball (0 : seminorm 𝕜 E) x r = set.univ := begin rw [set.eq_univ_iff_forall, ball], simp [hr], end lemma ball_smul (p : seminorm 𝕜 E) {c : nnreal} (hc : 0 < c) (r : ℝ) (x : E) : (c • p).ball x r = p.ball x (r / c) := by { ext, rw [mem_ball, mem_ball, smul_apply, nnreal.smul_def, smul_eq_mul, mul_comm, lt_div_iff (nnreal.coe_pos.mpr hc)] } lemma ball_sup (p : seminorm 𝕜 E) (q : seminorm 𝕜 E) (e : E) (r : ℝ) : ball (p ⊔ q) e r = ball p e r ∩ ball q e r := by simp_rw [ball, ←set.set_of_and, coe_sup, pi.sup_apply, sup_lt_iff] lemma ball_finset_sup' (p : ι → seminorm 𝕜 E) (s : finset ι) (H : s.nonempty) (e : E) (r : ℝ) : ball (s.sup' H p) e r = s.inf' H (λ i, ball (p i) e r) := begin induction H using finset.nonempty.cons_induction with a a s ha hs ih, { classical, simp }, { rw [finset.sup'_cons hs, finset.inf'_cons hs, ball_sup, inf_eq_inter, ih] }, end lemma ball_mono {p : seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) : p.ball x r₁ ⊆ p.ball x r₂ := λ _ (hx : _ < _), hx.trans_le h lemma ball_antitone {p q : seminorm 𝕜 E} (h : q ≤ p) : p.ball x r ⊆ q.ball x r := λ _, (h _).trans_lt lemma ball_add_ball_subset (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E): p.ball (x₁ : E) r₁ + p.ball (x₂ : E) r₂ ⊆ p.ball (x₁ + x₂) (r₁ + r₂) := begin rintros x ⟨y₁, y₂, hy₁, hy₂, rfl⟩, rw [mem_ball, add_sub_add_comm], exact (map_add_le_add p _ _).trans_lt (add_lt_add hy₁ hy₂), end end has_smul section module variables [module 𝕜 E] variables [add_comm_group F] [module 𝕜 F] lemma ball_comp (p : seminorm 𝕜 F) (f : E →ₗ[𝕜] F) (x : E) (r : ℝ) : (p.comp f).ball x r = f ⁻¹' (p.ball (f x) r) := begin ext, simp_rw [ball, mem_preimage, comp_apply, set.mem_set_of_eq, map_sub], end variables (p : seminorm 𝕜 E) lemma ball_zero_eq_preimage_ball {r : ℝ} : p.ball 0 r = p ⁻¹' (metric.ball 0 r) := begin ext x, simp only [mem_ball, sub_zero, mem_preimage, mem_ball_zero_iff], rw real.norm_of_nonneg, exact map_nonneg p _, end @[simp] lemma ball_bot {r : ℝ} (x : E) (hr : 0 < r) : ball (⊥ : seminorm 𝕜 E) x r = set.univ := ball_zero' x hr /-- Seminorm-balls at the origin are balanced. -/ lemma balanced_ball_zero (r : ℝ) : balanced 𝕜 (ball p 0 r) := begin rintro a ha x ⟨y, hy, hx⟩, rw [mem_ball_zero, ←hx, map_smul_eq_mul], calc _ ≤ p y : mul_le_of_le_one_left (map_nonneg p _) ha ... < r : by rwa mem_ball_zero at hy, end lemma ball_finset_sup_eq_Inter (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) : ball (s.sup p) x r = ⋂ (i ∈ s), ball (p i) x r := begin lift r to nnreal using hr.le, simp_rw [ball, Inter_set_of, finset_sup_apply, nnreal.coe_lt_coe, finset.sup_lt_iff (show ⊥ < r, from hr), ←nnreal.coe_lt_coe, subtype.coe_mk], end lemma ball_finset_sup (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) : ball (s.sup p) x r = s.inf (λ i, ball (p i) x r) := begin rw finset.inf_eq_infi, exact ball_finset_sup_eq_Inter _ _ _ hr, end lemma ball_smul_ball (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) : metric.ball (0 : 𝕜) r₁ • p.ball 0 r₂ ⊆ p.ball 0 (r₁ * r₂) := begin rw set.subset_def, intros x hx, rw set.mem_smul at hx, rcases hx with ⟨a, y, ha, hy, hx⟩, rw [←hx, mem_ball_zero, map_smul_eq_mul], exact mul_lt_mul'' (mem_ball_zero_iff.mp ha) (p.mem_ball_zero.mp hy) (norm_nonneg a) (map_nonneg p y), end @[simp] lemma ball_eq_emptyset (p : seminorm 𝕜 E) {x : E} {r : ℝ} (hr : r ≤ 0) : p.ball x r = ∅ := begin ext, rw [seminorm.mem_ball, set.mem_empty_eq, iff_false, not_lt], exact hr.trans (map_nonneg p _), end end module end add_comm_group end semi_normed_ring section normed_field variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] (p : seminorm 𝕜 E) {A B : set E} {a : 𝕜} {r : ℝ} {x : E} lemma smul_ball_zero {p : seminorm 𝕜 E} {k : 𝕜} {r : ℝ} (hk : 0 < ∥k∥) : k • p.ball 0 r = p.ball 0 (∥k∥ * r) := begin ext, rw [set.mem_smul_set, seminorm.mem_ball_zero], split; intro h, { rcases h with ⟨y, hy, h⟩, rw [←h, map_smul_eq_mul], rw seminorm.mem_ball_zero at hy, exact (mul_lt_mul_left hk).mpr hy }, refine ⟨k⁻¹ • x, _, _⟩, { rw [seminorm.mem_ball_zero, map_smul_eq_mul, norm_inv, ←(mul_lt_mul_left hk), ←mul_assoc, ←(div_eq_mul_inv ∥k∥ ∥k∥), div_self (ne_of_gt hk), one_mul], exact h}, rw [←smul_assoc, smul_eq_mul, ←div_eq_mul_inv, div_self (norm_pos_iff.mp hk), one_smul], end lemma ball_zero_absorbs_ball_zero (p : seminorm 𝕜 E) {r₁ r₂ : ℝ} (hr₁ : 0 < r₁) : absorbs 𝕜 (p.ball 0 r₁) (p.ball 0 r₂) := begin by_cases hr₂ : r₂ ≤ 0, { rw ball_eq_emptyset p hr₂, exact absorbs_empty }, rw [not_le] at hr₂, rcases exists_between hr₁ with ⟨r, hr, hr'⟩, refine ⟨r₂/r, div_pos hr₂ hr, _⟩, simp_rw set.subset_def, intros a ha x hx, have ha' : 0 < ∥a∥ := lt_of_lt_of_le (div_pos hr₂ hr) ha, rw [smul_ball_zero ha', p.mem_ball_zero], rw p.mem_ball_zero at hx, rw div_le_iff hr at ha, exact hx.trans (lt_of_le_of_lt ha ((mul_lt_mul_left ha').mpr hr')), end /-- Seminorm-balls at the origin are absorbent. -/ protected lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (ball p (0 : E) r) := begin rw absorbent_iff_nonneg_lt, rintro x, have hxr : 0 ≤ p x/r := div_nonneg (map_nonneg p _) hr.le, refine ⟨p x/r, hxr, λ a ha, _⟩, have ha₀ : 0 < ∥a∥ := hxr.trans_lt ha, refine ⟨a⁻¹ • x, _, smul_inv_smul₀ (norm_pos_iff.1 ha₀) x⟩, rwa [mem_ball_zero, map_smul_eq_mul, norm_inv, inv_mul_lt_iff ha₀, ←div_lt_iff hr], end /-- Seminorm-balls containing the origin are absorbent. -/ protected lemma absorbent_ball (hpr : p x < r) : absorbent 𝕜 (ball p x r) := begin refine (p.absorbent_ball_zero $ sub_pos.2 hpr).subset (λ y hy, _), rw p.mem_ball_zero at hy, exact p.mem_ball.2 ((map_sub_le_add p _ _).trans_lt $ add_lt_of_lt_sub_right hy), end lemma symmetric_ball_zero (r : ℝ) (hx : x ∈ ball p 0 r) : -x ∈ ball p 0 r := balanced_ball_zero p r (-1) (by rw [norm_neg, norm_one]) ⟨x, hx, by rw [neg_smul, one_smul]⟩ @[simp] lemma neg_ball (p : seminorm 𝕜 E) (r : ℝ) (x : E) : -ball p x r = ball p (-x) r := by { ext, rw [mem_neg, mem_ball, mem_ball, ←neg_add', sub_neg_eq_add, map_neg_eq_map] } @[simp] lemma smul_ball_preimage (p : seminorm 𝕜 E) (y : E) (r : ℝ) (a : 𝕜) (ha : a ≠ 0) : ((•) a) ⁻¹' p.ball y r = p.ball (a⁻¹ • y) (r / ∥a∥) := set.ext $ λ _, by rw [mem_preimage, mem_ball, mem_ball, lt_div_iff (norm_pos_iff.mpr ha), mul_comm, ←map_smul_eq_mul p, smul_sub, smul_inv_smul₀ ha] end normed_field section convex variables [normed_field 𝕜] [add_comm_group E] [normed_space ℝ 𝕜] [module 𝕜 E] section has_smul variables [has_smul ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E) /-- A seminorm is convex. Also see `convex_on_norm`. -/ protected lemma convex_on : convex_on ℝ univ p := begin refine ⟨convex_univ, λ x _ y _ a b ha hb hab, _⟩, calc p (a • x + b • y) ≤ p (a • x) + p (b • y) : map_add_le_add p _ _ ... = ∥a • (1 : 𝕜)∥ * p x + ∥b • (1 : 𝕜)∥ * p y : by rw [←map_smul_eq_mul p, ←map_smul_eq_mul p, smul_one_smul, smul_one_smul] ... = a * p x + b * p y : by rw [norm_smul, norm_smul, norm_one, mul_one, mul_one, real.norm_of_nonneg ha, real.norm_of_nonneg hb], end end has_smul section module variables [module ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E) (x : E) (r : ℝ) /-- Seminorm-balls are convex. -/ lemma convex_ball : convex ℝ (ball p x r) := begin convert (p.convex_on.translate_left (-x)).convex_lt r, ext y, rw [preimage_univ, sep_univ, p.mem_ball, sub_eq_add_neg], refl, end end module end convex section restrict_scalars variables (𝕜) {𝕜' : Type*} [normed_field 𝕜] [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] [norm_one_class 𝕜'] [add_comm_group E] [module 𝕜' E] [has_smul 𝕜 E] [is_scalar_tower 𝕜 𝕜' E] /-- Reinterpret a seminorm over a field `𝕜'` as a seminorm over a smaller field `𝕜`. This will typically be used with `is_R_or_C 𝕜'` and `𝕜 = ℝ`. -/ protected def restrict_scalars (p : seminorm 𝕜' E) : seminorm 𝕜 E := { smul' := λ a x, by rw [← smul_one_smul 𝕜' a x, p.smul', norm_smul, norm_one, mul_one], ..p } @[simp] lemma coe_restrict_scalars (p : seminorm 𝕜' E) : (p.restrict_scalars 𝕜 : E → ℝ) = p := rfl @[simp] lemma restrict_scalars_ball (p : seminorm 𝕜' E) : (p.restrict_scalars 𝕜).ball = p.ball := rfl end restrict_scalars end seminorm /-! ### The norm as a seminorm -/ section norm_seminorm variables (𝕜) (E) [normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E] {r : ℝ} /-- The norm of a seminormed group as a seminorm. -/ def norm_seminorm : seminorm 𝕜 E := { smul' := norm_smul, ..(norm_add_group_seminorm E)} @[simp] lemma coe_norm_seminorm : ⇑(norm_seminorm 𝕜 E) = norm := rfl @[simp] lemma ball_norm_seminorm : (norm_seminorm 𝕜 E).ball = metric.ball := by { ext x r y, simp only [seminorm.mem_ball, metric.mem_ball, coe_norm_seminorm, dist_eq_norm] } variables {𝕜 E} {x : E} /-- Balls at the origin are absorbent. -/ lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (metric.ball (0 : E) r) := by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball_zero hr } /-- Balls containing the origin are absorbent. -/ lemma absorbent_ball (hx : ∥x∥ < r) : absorbent 𝕜 (metric.ball x r) := by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball hx } /-- Balls at the origin are balanced. -/ lemma balanced_ball_zero : balanced 𝕜 (metric.ball (0 : E) r) := by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).balanced_ball_zero r } end norm_seminorm
980281c94df0f8aecc863b4fa78afae705678608
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/sub/canonical.lean
28a2c7cc3859efa76ab5b5144f0371ee58036363
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
17,180
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 algebra.order.monoid.canonical.defs import algebra.order.sub.defs /-! # Lemmas about subtraction in canonically ordered monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/814 > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} section has_exists_add_of_le variables [add_comm_semigroup α] [partial_order α] [has_exists_add_of_le α] [covariant_class α α (+) (≤)] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma add_tsub_cancel_of_le (h : a ≤ b) : a + (b - a) = b := begin refine le_antisymm _ le_add_tsub, obtain ⟨c, rfl⟩ := exists_add_of_le h, exact add_le_add_left add_tsub_le_left a, end lemma tsub_add_cancel_of_le (h : a ≤ b) : b - a + a = b := by { rw [add_comm], exact add_tsub_cancel_of_le h } lemma add_le_of_le_tsub_right_of_le (h : b ≤ c) (h2 : a ≤ c - b) : a + b ≤ c := (add_le_add_right h2 b).trans_eq $ tsub_add_cancel_of_le h lemma add_le_of_le_tsub_left_of_le (h : a ≤ c) (h2 : b ≤ c - a) : a + b ≤ c := (add_le_add_left h2 a).trans_eq $ add_tsub_cancel_of_le h lemma tsub_le_tsub_iff_right (h : c ≤ b) : a - c ≤ b - c ↔ a ≤ b := by rw [tsub_le_iff_right, tsub_add_cancel_of_le h] lemma tsub_left_inj (h1 : c ≤ a) (h2 : c ≤ b) : a - c = b - c ↔ a = b := by simp_rw [le_antisymm_iff, tsub_le_tsub_iff_right h1, tsub_le_tsub_iff_right h2] lemma tsub_inj_left (h₁ : a ≤ b) (h₂ : a ≤ c) : b - a = c - a → b = c := (tsub_left_inj h₁ h₂).1 /-- See `lt_of_tsub_lt_tsub_right` for a stronger statement in a linear order. -/ lemma lt_of_tsub_lt_tsub_right_of_le (h : c ≤ b) (h2 : a - c < b - c) : a < b := by { refine ((tsub_le_tsub_iff_right h).mp h2.le).lt_of_ne _, rintro rfl, exact h2.false } lemma tsub_add_tsub_cancel (hab : b ≤ a) (hcb : c ≤ b) : (a - b) + (b - c) = a - c := begin convert tsub_add_cancel_of_le (tsub_le_tsub_right hab c) using 2, rw [tsub_tsub, add_tsub_cancel_of_le hcb], end lemma tsub_tsub_tsub_cancel_right (h : c ≤ b) : (a - c) - (b - c) = a - b := by rw [tsub_tsub, add_tsub_cancel_of_le h] /-! #### Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma eq_tsub_iff_add_eq_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a = b - c ↔ a + c = b := ⟨by { rintro rfl, exact tsub_add_cancel_of_le h }, hc.eq_tsub_of_add_eq⟩ protected lemma tsub_eq_iff_eq_add_of_le (hb : add_le_cancellable b) (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [eq_comm, hb.eq_tsub_iff_add_eq_of_le h, eq_comm] protected lemma add_tsub_assoc_of_le (hc : add_le_cancellable c) (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := by conv_lhs { rw [← add_tsub_cancel_of_le h, add_comm c, ← add_assoc, hc.add_tsub_cancel_right] } protected lemma tsub_add_eq_add_tsub (hb : add_le_cancellable b) (h : b ≤ a) : a - b + c = a + c - b := by rw [add_comm a, hb.add_tsub_assoc_of_le h, add_comm] protected lemma tsub_tsub_assoc (hbc : add_le_cancellable (b - c)) (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := hbc.tsub_eq_of_eq_add $ by rw [add_assoc, add_tsub_cancel_of_le h₂, tsub_add_cancel_of_le h₁] protected lemma tsub_add_tsub_comm (hb : add_le_cancellable b) (hd : add_le_cancellable d) (hba : b ≤ a) (hdc : d ≤ c) : a - b + (c - d) = a + c - (b + d) := by rw [hb.tsub_add_eq_add_tsub hba, ←hd.add_tsub_assoc_of_le hdc, tsub_tsub, add_comm d] protected lemma le_tsub_iff_left (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := ⟨add_le_of_le_tsub_left_of_le h, ha.le_tsub_of_add_le_left⟩ protected lemma le_tsub_iff_right (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := by { rw [add_comm], exact ha.le_tsub_iff_left h } protected lemma tsub_lt_iff_left (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < b + c := begin refine ⟨hb.lt_add_of_tsub_lt_left, _⟩, intro h, refine (tsub_le_iff_left.mpr h.le).lt_of_ne _, rintro rfl, exact h.ne' (add_tsub_cancel_of_le hba) end protected lemma tsub_lt_iff_right (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < c + b := by { rw [add_comm], exact hb.tsub_lt_iff_left hba } protected lemma tsub_lt_iff_tsub_lt (hb : add_le_cancellable b) (hc : add_le_cancellable c) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := by rw [hb.tsub_lt_iff_left h₁, hc.tsub_lt_iff_right h₂] protected lemma le_tsub_iff_le_tsub (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := by rw [ha.le_tsub_iff_left h₁, hc.le_tsub_iff_right h₂] protected lemma lt_tsub_iff_right_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ a + c < b := begin refine ⟨λ h', (add_le_of_le_tsub_right_of_le h h'.le).lt_of_ne _, hc.lt_tsub_of_add_lt_right⟩, rintro rfl, exact h'.ne' hc.add_tsub_cancel_right, end protected lemma lt_tsub_iff_left_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ c + a < b := by { rw [add_comm], exact hc.lt_tsub_iff_right_of_le h } protected lemma tsub_inj_right (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := by { rw ← hab.inj, rw [tsub_add_cancel_of_le h₁, h₃, tsub_add_cancel_of_le h₂] } protected lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class α α (+) (<)] (hb : add_le_cancellable b) (hca : c ≤ a) (h : a - b < a - c) : c < b := begin conv_lhs at h { rw [← tsub_add_cancel_of_le hca] }, exact lt_of_add_lt_add_left (hb.lt_add_of_tsub_lt_right h), end protected lemma tsub_lt_tsub_left_of_le (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h : c < b) : a - b < a - c := (tsub_le_tsub_left h.le _).lt_of_ne $ λ h', h.ne' $ hab.tsub_inj_right h₁ (h.le.trans h₁) h' protected lemma tsub_lt_tsub_right_of_le (hc : add_le_cancellable c) (h : c ≤ a) (h2 : a < b) : a - c < b - c := by { apply hc.lt_tsub_of_add_lt_left, rwa [add_tsub_cancel_of_le h] } protected lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class α α (+) (<)] (hb : add_le_cancellable b) (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := ⟨hb.lt_of_tsub_lt_tsub_left_of_le h₂, hab.tsub_lt_tsub_left_of_le h₁⟩ @[simp] protected lemma add_tsub_tsub_cancel (hac : add_le_cancellable (a - c)) (h : c ≤ a) : (a + b) - (a - c) = b + c := hac.tsub_eq_of_eq_add $ by rw [add_assoc, add_tsub_cancel_of_le h, add_comm] protected lemma tsub_tsub_cancel_of_le (hba : add_le_cancellable (b - a)) (h : a ≤ b) : b - (b - a) = a := hba.tsub_eq_of_eq_add (add_tsub_cancel_of_le h).symm protected lemma tsub_tsub_tsub_cancel_left (hab : add_le_cancellable (a - b)) (h : b ≤ a) : a - c - (a - b) = b - c := by rw [tsub_right_comm, hab.tsub_tsub_cancel_of_le h] end add_le_cancellable section contra /-! ### Lemmas where addition is order-reflecting. -/ variable [contravariant_class α α (+) (≤)] lemma eq_tsub_iff_add_eq_of_le (h : c ≤ b) : a = b - c ↔ a + c = b := contravariant.add_le_cancellable.eq_tsub_iff_add_eq_of_le h lemma tsub_eq_iff_eq_add_of_le (h : b ≤ a) : a - b = c ↔ a = c + b := contravariant.add_le_cancellable.tsub_eq_iff_eq_add_of_le h /-- See `add_tsub_le_assoc` for an inequality. -/ lemma add_tsub_assoc_of_le (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := contravariant.add_le_cancellable.add_tsub_assoc_of_le h a lemma tsub_add_eq_add_tsub (h : b ≤ a) : a - b + c = a + c - b := contravariant.add_le_cancellable.tsub_add_eq_add_tsub h lemma tsub_tsub_assoc (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := contravariant.add_le_cancellable.tsub_tsub_assoc h₁ h₂ lemma tsub_add_tsub_comm (hba : b ≤ a) (hdc : d ≤ c) : a - b + (c - d) = a + c - (b + d) := contravariant.add_le_cancellable.tsub_add_tsub_comm contravariant.add_le_cancellable hba hdc lemma le_tsub_iff_left (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := contravariant.add_le_cancellable.le_tsub_iff_left h lemma le_tsub_iff_right (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := contravariant.add_le_cancellable.le_tsub_iff_right h lemma tsub_lt_iff_left (hbc : b ≤ a) : a - b < c ↔ a < b + c := contravariant.add_le_cancellable.tsub_lt_iff_left hbc lemma tsub_lt_iff_right (hbc : b ≤ a) : a - b < c ↔ a < c + b := contravariant.add_le_cancellable.tsub_lt_iff_right hbc lemma tsub_lt_iff_tsub_lt (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := contravariant.add_le_cancellable.tsub_lt_iff_tsub_lt contravariant.add_le_cancellable h₁ h₂ lemma le_tsub_iff_le_tsub (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := contravariant.add_le_cancellable.le_tsub_iff_le_tsub contravariant.add_le_cancellable h₁ h₂ /-- See `lt_tsub_iff_right` for a stronger statement in a linear order. -/ lemma lt_tsub_iff_right_of_le (h : c ≤ b) : a < b - c ↔ a + c < b := contravariant.add_le_cancellable.lt_tsub_iff_right_of_le h /-- See `lt_tsub_iff_left` for a stronger statement in a linear order. -/ lemma lt_tsub_iff_left_of_le (h : c ≤ b) : a < b - c ↔ c + a < b := contravariant.add_le_cancellable.lt_tsub_iff_left_of_le h /-- See `lt_of_tsub_lt_tsub_left` for a stronger statement in a linear order. -/ lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class α α (+) (<)] (hca : c ≤ a) (h : a - b < a - c) : c < b := contravariant.add_le_cancellable.lt_of_tsub_lt_tsub_left_of_le hca h lemma tsub_lt_tsub_left_of_le : b ≤ a → c < b → a - b < a - c := contravariant.add_le_cancellable.tsub_lt_tsub_left_of_le lemma tsub_lt_tsub_right_of_le (h : c ≤ a) (h2 : a < b) : a - c < b - c := contravariant.add_le_cancellable.tsub_lt_tsub_right_of_le h h2 lemma tsub_inj_right (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := contravariant.add_le_cancellable.tsub_inj_right h₁ h₂ h₃ /-- See `tsub_lt_tsub_iff_left_of_le` for a stronger statement in a linear order. -/ lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class α α (+) (<)] (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le_of_le contravariant.add_le_cancellable h₁ h₂ @[simp] lemma add_tsub_tsub_cancel (h : c ≤ a) : (a + b) - (a - c) = b + c := contravariant.add_le_cancellable.add_tsub_tsub_cancel h /-- See `tsub_tsub_le` for an inequality. -/ lemma tsub_tsub_cancel_of_le (h : a ≤ b) : b - (b - a) = a := contravariant.add_le_cancellable.tsub_tsub_cancel_of_le h lemma tsub_tsub_tsub_cancel_left (h : b ≤ a) : a - c - (a - b) = b - c := contravariant.add_le_cancellable.tsub_tsub_tsub_cancel_left h end contra end has_exists_add_of_le /-! ### Lemmas in a canonically ordered monoid. -/ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma add_tsub_cancel_iff_le : a + (b - a) = b ↔ a ≤ b := ⟨λ h, le_iff_exists_add.mpr ⟨b - a, h.symm⟩, add_tsub_cancel_of_le⟩ lemma tsub_add_cancel_iff_le : b - a + a = b ↔ a ≤ b := by { rw [add_comm], exact add_tsub_cancel_iff_le } @[simp] lemma tsub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by rw [← nonpos_iff_eq_zero, tsub_le_iff_left, add_zero] alias tsub_eq_zero_iff_le ↔ _ tsub_eq_zero_of_le attribute [simp] tsub_eq_zero_of_le @[simp] lemma tsub_self (a : α) : a - a = 0 := tsub_eq_zero_of_le le_rfl @[simp] lemma tsub_le_self : a - b ≤ a := tsub_le_iff_left.mpr $ le_add_left le_rfl @[simp] lemma zero_tsub (a : α) : 0 - a = 0 := tsub_eq_zero_of_le $ zero_le a lemma tsub_self_add (a b : α) : a - (a + b) = 0 := tsub_eq_zero_of_le $ self_le_add_right _ _ lemma tsub_pos_iff_not_le : 0 < a - b ↔ ¬ a ≤ b := by rw [pos_iff_ne_zero, ne.def, tsub_eq_zero_iff_le] lemma tsub_pos_of_lt (h : a < b) : 0 < b - a := tsub_pos_iff_not_le.mpr h.not_le lemma tsub_lt_of_lt (h : a < b) : a - c < b := lt_of_le_of_lt tsub_le_self h namespace add_le_cancellable protected lemma tsub_le_tsub_iff_left (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := begin refine ⟨_, λ h, tsub_le_tsub_left h a⟩, rw [tsub_le_iff_left, ← hc.add_tsub_assoc_of_le h, hc.le_tsub_iff_right (h.trans le_add_self), add_comm b], apply ha, end protected lemma tsub_right_inj (ha : add_le_cancellable a) (hb : add_le_cancellable b) (hc : add_le_cancellable c) (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := by simp_rw [le_antisymm_iff, ha.tsub_le_tsub_iff_left hb hba, ha.tsub_le_tsub_iff_left hc hca, and_comm] end add_le_cancellable /-! #### Lemmas where addition is order-reflecting. -/ section contra variable [contravariant_class α α (+) (≤)] lemma tsub_le_tsub_iff_left (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := contravariant.add_le_cancellable.tsub_le_tsub_iff_left contravariant.add_le_cancellable h lemma tsub_right_inj (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := contravariant.add_le_cancellable.tsub_right_inj contravariant.add_le_cancellable contravariant.add_le_cancellable hba hca variables (α) /-- A `canonically_ordered_add_monoid` with ordered subtraction and order-reflecting addition is cancellative. This is not an instance at it would form a typeclass loop. See note [reducible non-instances]. -/ @[reducible] def canonically_ordered_add_monoid.to_add_cancel_comm_monoid : add_cancel_comm_monoid α := { add_left_cancel := λ a b c h, by simpa only [add_tsub_cancel_left] using congr_arg (λ x, x - a) h, ..(by apply_instance : add_comm_monoid α) } end contra end canonically_ordered_add_monoid /-! ### Lemmas in a linearly canonically ordered monoid. -/ section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma tsub_pos_iff_lt : 0 < a - b ↔ b < a := by rw [tsub_pos_iff_not_le, not_le] lemma tsub_eq_tsub_min (a b : α) : a - b = a - min a b := begin cases le_total a b with h h, { rw [min_eq_left h, tsub_self, tsub_eq_zero_of_le h] }, { rw [min_eq_right h] }, end namespace add_le_cancellable protected lemma lt_tsub_iff_right (hc : add_le_cancellable c) : a < b - c ↔ a + c < b := ⟨lt_imp_lt_of_le_imp_le tsub_le_iff_right.mpr, hc.lt_tsub_of_add_lt_right⟩ protected lemma lt_tsub_iff_left (hc : add_le_cancellable c) : a < b - c ↔ c + a < b := ⟨lt_imp_lt_of_le_imp_le tsub_le_iff_left.mpr, hc.lt_tsub_of_add_lt_left⟩ protected lemma tsub_lt_tsub_iff_right (hc : add_le_cancellable c) (h : c ≤ a) : a - c < b - c ↔ a < b := by rw [hc.lt_tsub_iff_left, add_tsub_cancel_of_le h] protected lemma tsub_lt_self (ha : add_le_cancellable a) (h₁ : 0 < a) (h₂ : 0 < b) : a - b < a := begin refine tsub_le_self.lt_of_ne (λ h, _), rw [← h, tsub_pos_iff_lt] at h₁, exact h₂.not_le (ha.add_le_iff_nonpos_left.1 $ add_le_of_le_tsub_left_of_le h₁.le h.ge), end protected lemma tsub_lt_self_iff (ha : add_le_cancellable a) : a - b < a ↔ 0 < a ∧ 0 < b := begin refine ⟨λ h, ⟨(zero_le _).trans_lt h, (zero_le b).lt_of_ne _⟩, λ h, ha.tsub_lt_self h.1 h.2⟩, rintro rfl, rw [tsub_zero] at h, exact h.false end /-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ protected lemma tsub_lt_tsub_iff_left_of_le (ha : add_le_cancellable a) (hb : add_le_cancellable b) (h : b ≤ a) : a - b < a - c ↔ c < b := lt_iff_lt_of_le_iff_le $ ha.tsub_le_tsub_iff_left hb h end add_le_cancellable section contra variable [contravariant_class α α (+) (≤)] /-- This lemma also holds for `ennreal`, but we need a different proof for that. -/ lemma tsub_lt_tsub_iff_right (h : c ≤ a) : a - c < b - c ↔ a < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_right h lemma tsub_lt_self : 0 < a → 0 < b → a - b < a := contravariant.add_le_cancellable.tsub_lt_self lemma tsub_lt_self_iff : a - b < a ↔ 0 < a ∧ 0 < b := contravariant.add_le_cancellable.tsub_lt_self_iff /-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ lemma tsub_lt_tsub_iff_left_of_le (h : b ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le contravariant.add_le_cancellable h end contra /-! ### Lemmas about `max` and `min`. -/ lemma tsub_add_eq_max : a - b + b = max a b := begin cases le_total a b with h h, { rw [max_eq_right h, tsub_eq_zero_of_le h, zero_add] }, { rw [max_eq_left h, tsub_add_cancel_of_le h] } end lemma add_tsub_eq_max : a + (b - a) = max a b := by rw [add_comm, max_comm, tsub_add_eq_max] lemma tsub_min : a - min a b = a - b := begin cases le_total a b with h h, { rw [min_eq_left h, tsub_self, tsub_eq_zero_of_le h] }, { rw [min_eq_right h] } end lemma tsub_add_min : a - b + min a b = a := by { rw [← tsub_min, tsub_add_cancel_of_le], apply min_le_left } end canonically_linear_ordered_add_monoid
001530d3770269a0ba9a890b0af6af8339552b2b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/affine_space/finite_dimensional.lean
f8a0dada1d393dbd8e0e0f1b853437f4a3af5d90
[ "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
16,375
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ noncomputable theory open_locale big_operators classical affine section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace finite_dimensional module /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ h.vsub h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k ((set.finite.of_fintype _).image _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k ((set.finite.of_fintype _).image _) /-- An affine-independent family of points in a finite-dimensional affine space is finite. -/ noncomputable def fintype_of_fin_dim_affine_independent [finite_dimensional k V] {p : ι → P} (hi : affine_independent k p) : fintype ι := if hι : is_empty ι then (@fintype.of_is_empty _ hι) else begin let q := (not_is_empty_iff.mp hι).some, rw affine_independent_iff_linear_independent_vsub k p q at hi, letI : is_noetherian k V := is_noetherian.iff_fg.2 infer_instance, exact fintype_of_fintype_ne _ (fintype_of_is_noetherian_linear_independent hi) end /-- An affine-independent subset of a finite-dimensional affine space is finite. -/ lemma finite_of_fin_dim_affine_independent [finite_dimensional k V] {s : set P} (hi : affine_independent k (coe : s → P)) : s.finite := ⟨fintype_of_fin_dim_affine_independent k hi⟩ variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span_image_finset {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) = n := begin have hi' := hi.range.mono (set.image_subset_range p ↑s), have hc' : (s.image p).card = n + 1, { rwa s.card_image_of_injective hi.injective }, have hn : (s.image p).nonempty, { simp [hc', ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, have hp₁' : p₁ ∈ p '' s := by simpa using hp₁, rw [affine_independent_set_iff_linear_independent_vsub k hp₁', ← finset.coe_singleton, ← finset.coe_image, ← finset.coe_sdiff, finset.sdiff_singleton_eq_erase, ← finset.coe_image] at hi', have hc : (finset.image (λ (p : P), p -ᵥ p₁) ((finset.image p s).erase p₁)).card = n, { rw [finset.card_image_of_injective _ (vsub_left_injective _), finset.card_erase_of_mem hp₁], exact nat.pred_eq_of_eq_succ hc' }, rwa [vector_span_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) = n := begin rw ← finset.card_univ at hc, rw [← set.image_univ, ← finset.coe_univ, ← finset.coe_image], exact hi.finrank_vector_span_image_finset hc end /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (s.image p : set P) ≤ sm) (hc : finset.card s = finrank k sm + 1) : vector_span k (s.image p : set P) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span_image_finset hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = finrank k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (s.image p : set P) ≤ sp) (hc : finset.card s = finrank k sp.direction + 1) : affine_span k (s.image p : set P) = sp := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact hi.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = finrank k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image] at ⊢ hle, exact hi.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_independent.vector_span_eq_top_of_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = finrank k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_finrank_eq $ hi.finrank_vector_span hc /-- The `affine_span` of a finite affinely independent family is `⊤` iff the family's cardinality is one more than that of the finite-dimensional space. -/ lemma affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) : affine_span k (set.range p) = ⊤ ↔ fintype.card ι = finrank k V + 1 := begin split, { intros h_tot, let n := fintype.card ι - 1, have hn : fintype.card ι = n + 1, { exact (nat.succ_pred_eq_of_pos (card_pos_of_affine_span_eq_top k V P h_tot)).symm, }, rw [hn, ← finrank_top, ← (vector_span_eq_top_of_affine_span_eq_top k V P) h_tot, ← hi.finrank_vector_span hn], }, { intros hc, rw [← finrank_top, ← direction_top k V P] at hc, exact hi.affine_span_eq_of_le_of_card_eq_finrank_add_one le_top hc, }, end variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma finrank_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) ≤ n := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_finset_right_ne k hp₁], refine le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image (λ p, p -ᵥ p₁))) _, rw [finset.card_image_of_injective _ (vsub_left_injective p₁), finset.card_erase_of_mem hp₁, nat.pred_le_iff, nat.succ_eq_add_one, ← hc], apply finset.card_image_le end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma finrank_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image], rw ←finset.card_univ at hc, exact finrank_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_finrank_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ finrank k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_finrank_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_finrank_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ finrank k (vector_span k (set.range p)) := begin rw affine_independent_iff_finrank_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (finrank_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_finrank_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ finrank k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_finrank_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma finrank_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : finrank k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_finrank_vector_span_le k p hc).symm).symm /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := module.rank k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ module.rank k (vector_span k s) ≤ 1 := iff.rfl /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_finrank_le_one (s : set P) [finite_dimensional k (vector_span k s)] : collinear k s ↔ finrank k (vector_span k s) ≤ 1 := begin have h := collinear_iff_dim_le_one k s, rw ←finrank_eq_dim at h, exact_mod_cast h end variables (P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_dim_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_dim_le_one, vector_span_singleton], simp end /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ k ∙ v, { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [set_like.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := set_like.le_def.1 hs hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem k hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_vadd, ←add_smul] } } end /-- Two points are collinear. -/ lemma collinear_insert_singleton (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear (p : fin 3 → P) : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_finrank_le_one, affine_independent_iff_not_finrank_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent (p : fin 3 → P) : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_finrank_le_one, finrank_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] end affine_space'
1f574d5d7afe9711b53db40328d785175efc9ea3
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/IO3.lean
9300ee49106d53dec16f02b7b1021c4d82815b40
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
217
lean
import system.io definition main : io unit := do { l ← get_line, if l = "hello" then put_str "you have typed hello\n" else do {put_str "you did not type hello\n", put_str "-----------\n"} }
17533455af50926e280919ec20fcc7c05afb6945
bf3de31b5bab2d2f45db036440db572bf35564cf
/src/lib/dvector.lean
269ab1725d101a7e68029f3e9184878ee21747df
[ "Apache-2.0" ]
permissive
ml-lab/stump-learnable
60920c57e3238801ab97487497de026b0f843fd5
c1156b36eb34f1a21c377d0b0644c1ea7e22686b
refs/heads/master
1,599,132,375,763
1,572,478,931,000
1,572,478,931,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,702
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import tactic.tidy tactic.omega universes u v w @[derive decidable_eq]inductive dvector (α : Type u) : ℕ → Type u | nil {} : dvector 0 | cons : ∀{n} (x : α) (xs : dvector n), dvector (n+1) @[derive decidable_eq]inductive dfin : ℕ → Type | fz {n} : dfin (n+1) | fs {n} : dfin n → dfin (n+1) namespace dfin @[simp] def to_nat : ∀ {n}, dfin n → ℕ | _ fz := 0 | _ (fs n) := n.to_nat + 1 theorem to_nat_lt : ∀ {n} (x : dfin n), x.to_nat < n | _ fz := nat.succ_pos _ | _ (fs n) := nat.succ_lt_succ (to_nat_lt n) def to_fin : ∀ {n}, dfin n → fin n | 0 x := by {cases x} | (n+1) x := ⟨to_nat x, by apply to_nat_lt⟩ @[extensionality] theorem to_nat_inj {n} {x y : dfin n} (e : x.to_nat = y.to_nat) : x = y := by induction x; cases y; injection e with e; [refl, rw x_ih e] def raise : ∀ {n}, dfin n → dfin (n+1) | _ fz := fz | _ (fs n) := fs n.raise def elim0 {α : Sort*} : dfin 0 → α. def cast_le : ∀ {m n}, n ≤ m → dfin n → dfin m | 0 n h x := false.elim (by cases h; cases x) | (m+1) _ _ fz := fz | (m+1) _ h (@fs n s) := fs (s.cast_le (nat.le_of_succ_le_succ h)) @[simp] theorem cast_le_to_nat : ∀ {m n} (h : n ≤ m) (x : dfin n), (x.cast_le h).to_nat = x.to_nat | 0 n h x := false.elim (by cases h; cases x) | (m+1) _ _ fz := rfl | (m+1) _ h (@fs n s) := congr_arg (+1) (cast_le_to_nat _ _) theorem cast_le_rfl {n} (x : dfin n) : x.cast_le (le_refl _) = x := to_nat_inj (by simp) def last : ∀ n, dfin (n+1) | 0 := fz | (n+1) := fs (last n) def of_nat : ∀ n, ℕ → option (dfin n) | 0 m := none | (n+1) 0 := some fz | (n+1) (m+1) := fs <$> of_nat n m def of_nat_lt : ∀ {n} m, m < n → dfin n | 0 m h := (nat.not_lt_zero _ h).elim | (n+1) 0 _ := fz | (n+1) (m+1) h := fs (of_nat_lt m (nat.lt_of_succ_lt_succ h)) @[simp] theorem of_nat_lt_to_nat : ∀ {n m} (h : m < n), (of_nat_lt m h).to_nat = m | 0 m h := (nat.not_lt_zero _ h).elim | (n+1) 0 _ := rfl | (n+1) (m+1) h := congr_arg (+1) (of_nat_lt_to_nat (nat.lt_of_succ_lt_succ h)) def of_fin : ∀{n}, fin n → dfin n | n ⟨val, h⟩ := of_nat_lt val h meta instance reflect : ∀ n, has_reflect (dfin n) | _ fz := `(fz) | _ (fs n) := `(fs).subst (reflect _ n) def fz' : Π{n : ℕ+}, dfin n | ⟨0, h⟩ := false.elim (lt_irrefl 0 h) | ⟨k+1, h⟩ := fz end dfin meta def tactic.interactive.to_dfin (m : ℕ) : tactic unit := do n ← do { `(dfin %%n) ← tactic.target | return (m+1), tactic.eval_expr ℕ n }, m ← dfin.of_nat n m, tactic.exact (reflect m) namespace dfin instance has_zero_dfin {n} : has_zero $ dfin (n+1) := ⟨fz⟩ instance has_one_dfin : ∀ {n}, has_one (dfin (nat.succ n)) | 0 := ⟨fz⟩ | (n+1) := ⟨fs fz⟩ instance has_zero_dfin_pnat {n : ℕ+} : has_zero (dfin n) := ⟨fz'⟩ instance has_one_dfin_pnat : Π{n : ℕ+}, has_one (dfin n) | ⟨0, h⟩ := false.elim (lt_irrefl 0 h) | ⟨1, h⟩ := ⟨fz⟩ | ⟨n+2, h⟩ := ⟨fs fz⟩ instance has_add_dfin {n} : has_add (dfin(n)) := ⟨λ x y, of_fin $ (to_fin x) + (to_fin y)⟩ def max : ∀{n}, dfin n → dfin n → dfin n | 0 x y := by cases x | (n+1) (fz) y := y | (n+1) x (fz) := x | (n+1) (fs k₁) (fs k₂) := fs $ max k₁ k₂ end dfin local notation h :: t := dvector.cons h t local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l namespace dvector variables {α : Type u} {β : Type v} {γ : Type w} {n : ℕ} @[simp] protected def zero_eq : ∀(xs : dvector α 0), xs = [] | [] := rfl @[simp] protected def concat : ∀{n : ℕ} (xs : dvector α n) (x : α), dvector α (n+1) | _ [] x' := [x'] | _ (x::xs) x' := x::concat xs x' @[simp] protected def nth : ∀{n : ℕ} (xs : dvector α n) (m : ℕ) (h : m < n), α | _ [] m h := by exfalso; exact nat.not_lt_zero m h | _ (x::xs) 0 h := x | _ (x::xs) (m+1) h := nth xs m (lt_of_add_lt_add_right h) @[reducible, simp] protected def last {n : ℕ} (xs : dvector α (n+1)) : α := xs.nth n (by {repeat{constructor}}) protected def nth' {n : ℕ} (xs : dvector α n) (m : fin n) : α := xs.nth m.1 m.2 protected def nth'' : ∀ {n : ℕ} (xs : dvector α n) (m : dfin n), α | _ (x::xs) dfin.fz := x | _ (x::xs) (dfin.fs (m)) := nth'' xs m protected def mem : ∀{n : ℕ} (x : α) (xs : dvector α n), Prop | _ x [] := false | _ x (x'::xs) := x = x' ∨ mem x xs instance {n : ℕ} : has_mem α (dvector α n) := ⟨dvector.mem⟩ protected def to_set : ∀{n : ℕ}, dvector α n → set α := λ n xs, λ a, dvector.mem a xs protected def pmem : ∀{n : ℕ} (x : α) (xs : dvector α n), Type | _ x [] := empty | _ x (x'::xs) := psum (x = x') (pmem x xs) protected def mem_of_pmem : ∀{n : ℕ} {x : α} {xs : dvector α n} (hx : xs.pmem x), x ∈ xs | _ x [] hx := by cases hx | _ x (x'::xs) hx := by cases hx;[exact or.inl hx, exact or.inr (mem_of_pmem hx)] @[simp] protected def map (f : α → β) : ∀{n : ℕ}, dvector α n → dvector β n | _ [] := [] | _ (x::xs) := f x :: map xs @[simp] protected lemma map_id : ∀{n : ℕ} (xs : dvector α n), xs.map (λx, x) = xs | _ [] := rfl | _ (x::xs) := by dsimp; simp* @[simp] protected lemma map_congr_pmem {f g : α → β} : ∀{n : ℕ} {xs : dvector α n} (h : ∀x, xs.pmem x → f x = g x), xs.map f = xs.map g | _ [] h := rfl | _ (x::xs) h := begin dsimp, congr' 1, exact h x (psum.inl rfl), apply map_congr_pmem, intros x hx, apply h, right, exact hx end @[simp] protected lemma map_congr_mem {f g : α → β} {n : ℕ} {xs : dvector α n} (h : ∀x, x ∈ xs → f x = g x) : xs.map f = xs.map g := dvector.map_congr_pmem $ λx hx, h x $ dvector.mem_of_pmem hx @[simp] protected lemma map_congr {f g : α → β} (h : ∀x, f x = g x) : ∀{n : ℕ} (xs : dvector α n), xs.map f = xs.map g | _ [] := rfl | _ (x::xs) := by dsimp; simp* @[simp] protected lemma map_map (g : β → γ) (f : α → β): ∀{n : ℕ} (xs : dvector α n), (xs.map f).map g = xs.map (λx, g (f x)) | _ [] := rfl | _ (x::xs) := by dsimp; simp* protected lemma map_inj {f : α → β} (hf : ∀{{x x'}}, f x = f x' → x = x') {n : ℕ} {xs xs' : dvector α n} (h : xs.map f = xs'.map f) : xs = xs' := begin induction xs; cases xs', refl, simp at h, congr;[apply hf, apply xs_ih]; simp [h] end @[simp] protected lemma map_concat (f : α → β) : ∀{n : ℕ} (xs : dvector α n) (x : α), (xs.concat x).map f = (xs.map f).concat (f x) | _ [] x' := by refl | _ (x::xs) x' := by dsimp; congr' 1; exact map_concat xs x' @[simp] protected lemma map_nth (f : α → β) : ∀{n : ℕ} (xs : dvector α n) (m : ℕ) (h : m < n), (xs.map f).nth m h = f (xs.nth m h) | _ [] m h := by exfalso; exact nat.not_lt_zero m h | _ (x::xs) 0 h := by refl | _ (x::xs) (m+1) h := by exact map_nth xs m _ protected lemma concat_nth : ∀{n : ℕ} (xs : dvector α n) (x : α) (m : ℕ) (h' : m < n+1) (h : m < n), (xs.concat x).nth m h' = xs.nth m h | _ [] x' m h' h := by exfalso; exact nat.not_lt_zero m h | _ (x::xs) x' 0 h' h := by refl | _ (x::xs) x' (m+1) h' h := by dsimp; exact concat_nth xs x' m _ _ @[simp] protected lemma concat_nth_last : ∀{n : ℕ} (xs : dvector α n) (x : α) (h : n < n+1), (xs.concat x).nth n h = x | _ [] x' h := by refl | _ (x::xs) x' h := by dsimp; exact concat_nth_last xs x' _ @[simp] protected lemma concat_nth_last' : ∀{n : ℕ} (xs : dvector α n) (x : α) (h : n < n+1), (xs.concat x).last = x := by apply dvector.concat_nth_last @[simp] protected def append : ∀{n m : ℕ} (xs : dvector α n) (xs' : dvector α m), dvector α (m+n) | _ _ [] xs := xs | _ _ (x'::xs) xs' := x'::append xs xs' @[simp]protected def insert : ∀{n : ℕ} (x : α) (k : ℕ) (xs : dvector α n), dvector α (n+1) | n x 0 xs := (x::xs) | 0 x k xs := (x::xs) | (n+1) x (k+1) (y::ys) := (y::insert x k ys) @[simp] protected lemma insert_at_zero : ∀{n : ℕ} (x : α) (xs : dvector α n), dvector.insert x 0 xs = (x::xs) := by {intros, induction n; refl} -- why doesn't {intros, refl} work? @[simp] protected lemma insert_nth : ∀{n : ℕ} (x : α) (k : ℕ) (xs : dvector α n) (h : k < n+1), (dvector.insert x k xs).nth k h = x | 0 x k xs h := by {cases h, refl, exfalso, apply nat.not_lt_zero, exact h_a} | n x 0 xs h := by {induction n, refl, simp*} | (n+1) x (k+1) (y::ys) h := by simp* protected lemma insert_cons {n k} {x y : α} {v : dvector α n} : (x::(v.insert y k)) = (x::v).insert y (k+1) := by {induction v, refl, simp*} /- Given a proof that n ≤ m, return the nth initial segment of -/ @[simp]protected def trunc : ∀ (n) {m : ℕ} (h : n ≤ m) (xs : dvector α m), dvector α n | 0 0 _ xs := [] | 0 (m+1) _ xs := [] | (n+1) 0 _ xs := by {exfalso, cases _x} | (n+1) (m+1) h (x::xs) := (x::@trunc n m (by exact nat.lt_succ_iff.mp h) xs) @[simp]protected lemma trunc_n_n {n : ℕ} {h : n ≤ n} {v : dvector α n} : dvector.trunc n h v = v := by {induction v, refl, solve_by_elim} @[simp]protected lemma trunc_0_n {n : ℕ} {h : 0 ≤ n} {v : dvector α n} : dvector.trunc 0 h v = [] := by {induction v, refl, simp} @[simp]protected lemma trunc_nth {n m l: ℕ} {h : n ≤ m} {h' : l < n} {v : dvector α m} : (v.trunc n h).nth l h' = v.nth l (lt_of_lt_of_le h' h) := begin induction m generalizing n l, have : n = 0, by cases h; simp, subst this, cases h', cases n; cases l, {cases h'}, {cases h'}, {cases v, refl}, cases v, simp only [m_ih, dvector.nth, dvector.trunc] end protected lemma nth_irrel1 : ∀{n k : ℕ} {h : k < n + 1} {h' : k < n + 1 + 1} (v : dvector α (n+1)) (x : α), (x :: (v.trunc n (nat.le_succ n))).nth k h = (x::v).nth k h' := by {intros, apply @dvector.trunc_nth _ _ _ _ (by {simp, exact dec_trivial}) h (x::v)} protected def cast {n m} (p : n = m) : dvector α n → dvector α m := by subst p; exact id @[simp] protected lemma cast_irrel {n m} {p p' : n = m} {v : dvector α n} : v.cast p = v.cast p' := by refl @[simp] protected lemma cast_rfl {n m} {p : n = m} {q : m = n} {v : dvector α n} : (v.cast p).cast q = v := by {subst p, refl} protected lemma cast_hrfl {n m} {p : n = m} {v : dvector α n} : v.cast p == v := by subst p; refl @[simp] protected lemma cast_trans {n m o} {p : n = m} {q : m = o} {v : dvector α n} : (v.cast p).cast q = v.cast (trans p q) := by subst p; subst q; refl @[simp] protected def remove_mth : ∀ {n : ℕ} (m : ℕ) (xs : dvector α (n+1)) , dvector α (n) | 0 _ _ := dvector.nil | n 0 (dvector.cons y ys) := ys | (n+1) (k+1) (dvector.cons y ys) := dvector.cons y (remove_mth k ys) end dvector
a358765069e5f7359ae3e78fd10825fdfee9c6a7
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
/src/exp/default.lean
dde60b5fef119671489419963ef28e0e541ce358
[]
no_license
spl/alpha-conversion-is-easy
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
ed937fe85d8495daffd9412a5524c77b9fcda094
refs/heads/master
1,607,649,280,020
1,517,380,240,000
1,517,380,240,000
52,174,747
4
0
null
1,456,052,226,000
1,456,001,163,000
Lean
UTF-8
Lean
false
false
39
lean
import .type import .map import .subst
6c7eef73daccc76760712f364314d9a1a4bcd96f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tree2.lean
42b65fa37ab93937e4aa9a58d71ee491287555a7
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,085
lean
import logic data.prod open eq.ops prod tactic inductive tree (A : Type) := | leaf : A → tree A | node : tree A → tree A → tree A inductive one1.{l} : Type.{max 1 l} := star : one1 set_option pp.universes true namespace tree namespace manual section universe variables l₁ l₂ variable {A : Type.{l₁}} variable (C : tree A → Type.{l₂}) definition below (t : tree A) : Type := tree.rec_on t (λ a, one1.{l₂}) (λ t₁ t₂ r₁ r₂, C t₁ × C t₂ × r₁ × r₂) end section universe variables l₁ l₂ variable {A : Type.{l₁}} variable {C : tree A → Type.{l₂}} definition below_rec_on (t : tree A) (H : Π (n : tree A), below C n → C n) : C t := have general : C t × below C t, from tree.rec_on t (λa, (H (leaf a) one1.star, one1.star)) (λ (l r : tree A) (Hl : C l × below C l) (Hr : C r × below C r), have b : below C (node l r), from (pr₁ Hl, pr₁ Hr, pr₂ Hl, pr₂ Hr), have c : C (node l r), from H (node l r) b, (c, b)), pr₁ general end end manual check tree.no_confusion theorem leaf_ne_tree {A : Type} (a : A) (l r : tree A) : leaf a ≠ node l r := assume h : leaf a = node l r, tree.no_confusion h constant A : Type₁ constants l₁ l₂ r₁ r₂ : tree A axiom node_eq : node l₁ r₁ = node l₂ r₂ check tree.no_confusion node_eq definition tst : (l₁ = l₂ → r₁ = r₂ → l₁ = l₂) → l₁ = l₂ := tree.no_confusion node_eq check tst (λ e₁ e₂, e₁) theorem node.inj1 {A : Type} (l₁ l₂ r₁ r₂ : tree A) : node l₁ r₁ = node l₂ r₂ → l₁ = l₂ := assume h, have trivial : (l₁ = l₂ → r₁ = r₂ → l₁ = l₂) → l₁ = l₂, from tree.no_confusion h, trivial (λ e₁ e₂, e₁) theorem node.inj2 {A : Type} (l₁ l₂ r₁ r₂ : tree A) : node l₁ r₁ = node l₂ r₂ → l₁ = l₂ := begin intro h, apply (tree.no_confusion h), intros, assumption end end tree
37f86293733b636edc43d8201e957131aafa260d
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/quadratic_discriminant.lean
8f77205bb12d384bf8b196a1d30920ca116f623c
[ "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
5,766
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.char_p.invertible import order.filter.at_top_bot import tactic.linarith /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition - `discrim a b c`: the discriminant of a quadratic `a * x * x + b * x + c` is `b * b - 4 * a * c`. ## Main statements - `quadratic_eq_zero_iff`: roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant. - `quadratic_ne_zero_of_discrim_ne_sq`: if the discriminant has no square root, then the corresponding quadratic has no root. - `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ open filter section ring variables {R : Type*} /-- Discriminant of a quadratic -/ def discrim [ring R] (a b c : R) : R := b^2 - 4 * a * c variables [comm_ring R] [integral_domain R] {a b c : R} /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_sq (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (x : R) : a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 := begin split, { assume h, calc discrim a b c = 4 * a * (a * x * x + b * x + c) + b * b - 4 * a * c : by { rw [h, discrim], ring } ... = (2*a*x + b)^2 : by ring }, { assume h, have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero h2 h2) ha, apply mul_left_cancel₀ ha, calc 2 * 2 * a * (a * x * x + b * x + c) = (2 * a * x + b) ^ 2 - (b ^ 2 - 4 * a * c) : by ring ... = 0 : by { rw [← h, discrim], ring } ... = 2*2*a*0 : by ring } end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_sq (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (h : ∀ s : R, discrim a b c ≠ s * s) (x : R) : a * x * x + b * x + c ≠ 0 := begin assume h', rw [quadratic_eq_zero_iff_discrim_eq_sq h2 ha, sq] at h', exact h _ h' end end ring section field variables {K : Type*} [field K] [invertible (2 : K)] {a b c x : K} /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) : a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := begin have h2 : (2 : K) ≠ 0 := nonzero_of_invertible 2, rw [quadratic_eq_zero_iff_discrim_eq_sq h2 ha, h, sq, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero h2 ha, have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm, have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne, have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne, split, { intro h', rcases h', { left, rw h', simpa [add_comm] }, { right, rw h', simpa [add_comm, sub_eq_add_neg] } }, { intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } } end /-- A quadratic has roots if its discriminant has square roots -/ lemma exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) : a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := begin have : discrim a b c = 0 * 0, by rw [h, mul_zero], rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self] end end field section linear_ordered_field variables {K : Type*} [linear_ordered_field K] {a b c : K} /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discrim_le_zero (h : ∀ x : K, 0 ≤ a * x * x + b * x + c) : discrim a b c ≤ 0 := begin rw [discrim, sq], obtain ha|rfl|ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0, -- if a < 0 { have : tendsto (λ x, (a * x + b) * x + c) at_top at_bot := tendsto_at_bot_add_const_right _ c ((tendsto_at_bot_add_const_right _ b (tendsto_id.neg_const_mul_at_top ha)).at_bot_mul_at_top tendsto_id), rcases (this.eventually (eventually_lt_at_bot 0)).exists with ⟨x, hx⟩, exact false.elim ((h x).not_lt $ by rwa ← add_mul) }, -- if a = 0 { rcases em (b = 0) with (rfl|hb), { simp }, { have := h ((-c - 1) / b), rw [mul_div_cancel' _ hb] at this, linarith } }, -- if a > 0 { have := calc 4 * a * (a * (-(b / a) * (1 / 2)) * (-(b / a) * (1 / 2)) + b * (-(b / a) * (1 / 2)) + c) = (a * (b / a)) * (a * (b / a)) - 2 * (a * (b / a)) * b + 4 * a * c : by ring ... = -(b * b - 4 * a * c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4 * a, by linarith, have h := (mul_nonneg ha' (h (-(b / a) * (1 / 2)))), rw this at h, rwa ← neg_nonneg } end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * x * x + b * x + c) : discrim a b c < 0 := begin have : ∀ x : K, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discrim_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end end linear_ordered_field
f01522e0db45020902c43a2feac3545429d75764
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/nat/part_enat.lean
7f03e53a943cf791ea2461d38bbf5011d2f6c384
[ "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
21,707
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.hom.equiv.basic import data.part import data.enat.lattice import tactic.norm_num /-! # Natural numbers with infinity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The natural numbers and an extra `top` element `⊤`. This implementation uses `part ℕ` as an implementation. Use `ℕ∞` instead unless you care about computability. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid part_enat` * `canonically_ordered_add_monoid part_enat` * `complete_linear_order part_enat` There is no additive analogue of `monoid_with_zero`; if there were then `part_enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `part_enat` to `ℕ∞`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : part_enat ≃+ ℕ∞` * `with_top_order_iso : part_enat ≃o ℕ∞` ## Implementation details `part_enat` is defined to be `part ℕ`. `+` and `≤` are defined on `part_enat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `part_enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags part_enat, ℕ∞ -/ open part (hiding some) /-- Type of natural numbers with infinity (`⊤`) -/ def part_enat : Type := part ℕ namespace part_enat /-- The computable embedding `ℕ → part_enat`. This coincides with the coercion `coe : ℕ → part_enat`, see `part_enat.some_eq_coe`. However, `coe` is noncomputable so `some` is preferable when computability is a concern. -/ def some : ℕ → part_enat := part.some instance : has_zero part_enat := ⟨some 0⟩ instance : inhabited part_enat := ⟨0⟩ instance : has_one part_enat := ⟨some 1⟩ instance : has_add part_enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance (n : ℕ) : decidable (some n).dom := is_true trivial @[simp] lemma dom_some (x : ℕ) : (some x).dom := trivial instance : add_comm_monoid part_enat := { add := (+), zero := (0), add_comm := λ x y, part.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, part.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, part.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, part.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : add_comm_monoid_with_one part_enat := { one := 1, nat_cast := some, nat_cast_zero := rfl, nat_cast_succ := λ _, part.ext' (true_and _).symm (λ _ _, rfl), .. part_enat.add_comm_monoid } lemma some_eq_coe (n : ℕ) : some n = n := rfl @[simp, norm_cast] lemma coe_inj {x y : ℕ} : (x : part_enat) = y ↔ x = y := part.some_inj @[simp] lemma dom_coe (x : ℕ) : (x : part_enat).dom := trivial instance : can_lift part_enat ℕ coe dom := ⟨λ n hn, ⟨n.get hn, part.some_get _⟩⟩ instance : has_le part_enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top part_enat := ⟨none⟩ instance : has_bot part_enat := ⟨0⟩ instance : has_sup part_enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ lemma le_def (x y : part_enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy := iff.rfl @[elab_as_eliminator] protected lemma cases_on' {P : part_enat → Prop} : ∀ a : part_enat, P ⊤ → (∀ n : ℕ, P (some n)) → P a := part.induction_on @[elab_as_eliminator] protected lemma cases_on {P : part_enat → Prop} : ∀ a : part_enat, P ⊤ → (∀ n : ℕ, P n) → P a := by { simp only [← some_eq_coe], exact part_enat.cases_on' } @[simp] lemma top_add (x : part_enat) : ⊤ + x = ⊤ := part.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : part_enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] lemma coe_get {x : part_enat} (h : x.dom) : (x.get h : part_enat) = x := by { rw [← some_eq_coe], exact part.ext' (iff_of_true trivial h) (λ _ _, rfl) } @[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : part_enat).dom) : get (x : part_enat) h = x := by rw [← coe_inj, coe_get] lemma get_coe {x : ℕ} : get (x : part_enat) (dom_coe x) = x := get_coe' _ _ lemma coe_add_get {x : ℕ} {y : part_enat} (h : ((x : part_enat) + y).dom) : get ((x : part_enat) + y) h = x + get y h.2 := by { simp only [← some_eq_coe] at h ⊢, refl } @[simp] lemma get_add {x y : part_enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma get_zero (h : (0 : part_enat).dom) : (0 : part_enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : part_enat).dom) : (1 : part_enat).get h = 1 := rfl lemma get_eq_iff_eq_some {a : part_enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some lemma get_eq_iff_eq_coe {a : part_enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some, some_eq_coe] lemma dom_of_le_of_dom {x y : part_enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h lemma dom_of_le_some {x : part_enat} {y : ℕ} (h : x ≤ some y) : x.dom := dom_of_le_of_dom h trivial lemma dom_of_le_coe {x : part_enat} {y : ℕ} (h : x ≤ y) : x.dom := by { rw [← some_eq_coe] at h, exact dom_of_le_some h } instance decidable_le (x y : part_enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) := if hx : x.dom then decidable_of_decidable_of_iff (show decidable (∀ (hy : (y : part_enat).dom), x.get hx ≤ (y : part_enat).get hy), from forall_prop_decidable _) $ by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] } else if hy : y.dom then is_false $ λ h, hx $ dom_of_le_of_dom h hy else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩ /-- The coercion `ℕ → part_enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ part_enat := ⟨coe, nat.cast_zero, nat.cast_add⟩ @[simp] lemma coe_coe_hom : ⇑coe_hom = coe := rfl instance : partial_order part_enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_rfl⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, part.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } lemma lt_def (x y : part_enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy := begin rw [lt_iff_le_not_le, le_def, le_def, not_exists], split, { rintro ⟨⟨hyx, H⟩, h⟩, by_cases hx : x.dom, { use hx, intro hy, specialize H hy, specialize h (λ _, hy), rw not_forall at h, cases h with hx' h, rw not_le at h, exact h }, { specialize h (λ hx', (hx hx').elim), rw not_forall at h, cases h with hx' h, exact (hx hx').elim } }, { rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ } end @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : part_enat) ≤ y ↔ x ≤ y := by { rw [← some_eq_coe, ← some_eq_coe], exact ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ } @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : part_enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] @[simp] lemma get_le_get {x y : part_enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} lemma le_coe_iff (x : part_enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n := begin rw [← some_eq_coe], show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n, simp only [forall_prop_of_true, some_eq_coe, dom_coe, get_coe'] end lemma lt_coe_iff (x : part_enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe] lemma coe_le_iff (n : ℕ) (x : part_enat) : (n : part_enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h := begin rw [← some_eq_coe], simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end lemma coe_lt_iff (n : ℕ) (x : part_enat) : (n : part_enat) < x ↔ ∀ h : x.dom, n < x.get h := begin rw [← some_eq_coe], simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end instance ne_zero.one : ne_zero (1 : part_enat) := ⟨coe_inj.not.mpr dec_trivial⟩ instance semilattice_sup : semilattice_sup part_enat := { sup := (⊔), le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..part_enat.partial_order } instance order_bot : order_bot part_enat := { bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩ } instance order_top : order_top part_enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩ } lemma eq_zero_iff {x : part_enat} : x = 0 ↔ x ≤ 0 := eq_bot_iff lemma ne_zero_iff {x : part_enat} : x ≠ 0 ↔ ⊥ < x := bot_lt_iff_ne_bot.symm lemma dom_of_lt {x y : part_enat} : x < y → x.dom := part_enat.cases_on x not_top_lt $ λ _ _, dom_coe _ lemma top_eq_none : (⊤ : part_enat) = none := rfl @[simp] lemma coe_lt_top (x : ℕ) : (x : part_enat) < ⊤ := ne.lt_top (λ h, absurd (congr_arg dom h) $ by simpa only [dom_coe] using true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : part_enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma not_is_max_coe (x : ℕ) : ¬ is_max (x : part_enat) := not_is_max_of_lt (coe_lt_top x) lemma ne_top_iff {x : part_enat} : x ≠ ⊤ ↔ ∃ (n : ℕ), x = n := by simpa only [← some_eq_coe] using part.ne_none_iff lemma ne_top_iff_dom {x : part_enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 part.eq_none_iff'.symm lemma not_dom_iff_eq_top {x : part_enat} : ¬ x.dom ↔ x = ⊤ := iff.not_left ne_top_iff_dom.symm lemma ne_top_of_lt {x y : part_enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma eq_top_iff_forall_lt (x : part_enat) : x = ⊤ ↔ ∀ n : ℕ, (n : part_enat) < x := begin split, { rintro rfl n, exact coe_lt_top _ }, { contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ } end lemma eq_top_iff_forall_le (x : part_enat) : x = ⊤ ↔ ∀ n : ℕ, (n : part_enat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ lemma pos_iff_one_le {x : part_enat} : 0 < x ↔ 1 ≤ x := part_enat.cases_on x (by simp only [iff_true, le_top, coe_lt_top, ← @nat.cast_zero part_enat]) $ λ n, by { rw [← nat.cast_zero, ← nat.cast_one, part_enat.coe_lt_coe, part_enat.coe_le_coe], refl } instance : is_total part_enat (≤) := { total := λ x y, part_enat.cases_on x (or.inr le_top) (part_enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))) } noncomputable instance : linear_order part_enat := { le_total := is_total.total, decidable_le := classical.dec_rel _, max := (⊔), max_def := @sup_eq_max_default _ _ (id _) _, ..part_enat.partial_order } instance : bounded_order part_enat := { ..part_enat.order_top, ..part_enat.order_bot } noncomputable instance : lattice part_enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..part_enat.semilattice_sup } instance : ordered_add_comm_monoid part_enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, part_enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro (dom_coe _) (h₁ h.2), λ h, by simpa only [coe_add_get] using add_le_add_left (h₂ _) c⟩), ..part_enat.linear_order, ..part_enat.add_comm_monoid } instance : canonically_ordered_add_monoid part_enat := { le_self_add := λ a b, part_enat.cases_on b (le_top.trans_eq (add_top _).symm) $ λ b, part_enat.cases_on a (top_add _).ge $ λ a, (coe_le_coe.2 le_self_add).trans_eq (nat.cast_add _ _), exists_add_of_le := λ a b, part_enat.cases_on b (λ _, ⟨⊤, (add_top _).symm⟩) $ λ b, part_enat.cases_on a (λ h, ((coe_lt_top _).not_le h).elim) $ λ a h, ⟨(b - a : ℕ), by rw [←nat.cast_add, coe_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩, ..part_enat.semilattice_sup, ..part_enat.order_bot, ..part_enat.ordered_add_comm_monoid } lemma eq_coe_sub_of_add_eq_coe {x y : part_enat} {n : ℕ} (h : x + y = n) : x = ↑(n - y.get (dom_of_le_coe ((le_add_left le_rfl).trans_eq h))) := begin lift x to ℕ using dom_of_le_coe ((le_add_right le_rfl).trans_eq h), lift y to ℕ using dom_of_le_coe ((le_add_left le_rfl).trans_eq h), rw [← nat.cast_add, coe_inj] at h, rw [get_coe, coe_inj, eq_tsub_of_add_eq h] end protected lemma add_lt_add_right {x y z : part_enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using part_enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : part_enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, part_enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : part_enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, part_enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : part_enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← part_enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : part_enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [part_enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : part_enat} (h : x < y + 1) : x ≤ y := begin induction y using part_enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : part_enat} (h : x < y) : x + 1 ≤ y := begin induction y using part_enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : part_enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using part_enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : part_enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using part_enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : part_enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply part_enat.cases_on a; apply part_enat.cases_on b; simp; simp only [(nat.cast_add _ _).symm, part_enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : part_enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply part_enat.cases_on a; apply part_enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : part_enat)]; simp only [(nat.cast_add _ _).symm, add_left_cancel_iff, part_enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : part_enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, part_enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `part_enat` to a `ℕ∞`. -/ def to_with_top (x : part_enat) [decidable x.dom] : ℕ∞ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : part_enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : part_enat).dom} : to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_some (n : ℕ) : to_with_top (some n) = n := rfl lemma to_with_top_coe (n : ℕ) {_ : decidable (n : part_enat).dom} : to_with_top n = n := by simp only [← some_eq_coe, ← to_with_top_some] @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : part_enat).dom} : to_with_top (n : part_enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : part_enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := part_enat.cases_on y (by simp) (part_enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : part_enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le end with_top section with_top_equiv open_locale classical @[simp] lemma to_with_top_add {x y : part_enat} : to_with_top (x + y) = to_with_top x + to_with_top y := by apply part_enat.cases_on y; apply part_enat.cases_on x; simp [← nat.cast_add, ← enat.coe_add] /-- `equiv` between `part_enat` and `ℕ∞` (for the order isomorphism see `with_top_order_iso`). -/ noncomputable def with_top_equiv : part_enat ≃ ℕ∞ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (option.some n) := coe n | none := ⊤ end, left_inv := λ x, by apply part_enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := by simpa only [nat.cast_zero] using with_top_equiv_coe 0 @[simp] lemma with_top_equiv_le {x y : part_enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : part_enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `part_enat` and `ℕ∞`. -/ noncomputable def with_top_order_iso : part_enat ≃o ℕ∞ := { map_rel_iff' := λ _ _, with_top_equiv_le, .. with_top_equiv} @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : ℕ∞} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : ℕ∞} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp /-- `to_with_top` induces an additive monoid isomorphism between `part_enat` and `ℕ∞`. -/ noncomputable def with_top_add_equiv : part_enat ≃+ ℕ∞ := { map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add, ..with_top_equiv} end with_top_equiv lemma lt_wf : @well_founded part_enat (<) := begin classical, change well_founded (λ a b : part_enat, a < b), simp_rw ←to_with_top_lt, exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) end instance : well_founded_lt part_enat := ⟨lt_wf⟩ instance : is_well_order part_enat (<) := { } instance : has_well_founded part_enat := ⟨(<), lt_wf⟩ section find variables (P : ℕ → Prop) [decidable_pred P] /-- The smallest `part_enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : part_enat := ⟨∃ n, P n, nat.find⟩ @[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl lemma find_dom (h : ∃ n, P n) : (find P).dom := h lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : part_enat) < find P := begin rw coe_lt_iff, intro h', rw find_get, have := @nat.find_spec P _ h', contrapose! this, exact h _ this end lemma lt_find_iff (n : ℕ) : (n : part_enat) < find P ↔ (∀ m ≤ n, ¬P m) := begin refine ⟨_, lt_find P n⟩, intros h m hm, by_cases H : (find P).dom, { apply nat.find_min H, rw coe_lt_iff at h, specialize h H, exact lt_of_le_of_lt hm h }, { exact not_exists.mp H m } end lemma find_le (n : ℕ) (h : P n) : find P ≤ n := by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ } lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩ end find noncomputable instance : linear_ordered_add_comm_monoid_with_top part_enat := { top_add' := top_add, .. part_enat.linear_order, .. part_enat.ordered_add_comm_monoid, .. part_enat.order_top } noncomputable instance : complete_linear_order part_enat := { inf := (⊓), sup := (⊔), top := ⊤, bot := ⊥, le := (≤), lt := (<), .. part_enat.lattice, .. with_top_order_iso.symm.to_galois_insertion.lift_complete_lattice, .. part_enat.linear_order, } end part_enat
f141414d12f5b56192de4de7599adffa5a065cc2
5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d
/mm0-lean/x86/separation.lean
7e81c4d7c8fe3f3d91122ccd969bb73e7cfcc038
[ "CC0-1.0" ]
permissive
digama0/mm0
491ac09146708aa1bb775007bf3dbe339ffc0096
98496badaf6464e56ed7b4204e7d54b85667cb01
refs/heads/master
1,692,321,030,902
1,686,254,458,000
1,686,254,458,000
172,456,790
273
38
CC0-1.0
1,689,939,563,000
1,551,080,059,000
Rust
UTF-8
Lean
false
false
23,615
lean
import x86.lemmas data.set.lattice data.list.basic data.list.alist namespace x86 inductive flag_place | CFP | ZFP | SFP | OFP def flag_place.read (f : flags) : flag_place → bool | flag_place.CFP := f.CF | flag_place.ZFP := f.ZF | flag_place.SFP := f.SF | flag_place.OFP := f.OF def flag_place.write (f : flags) (b : bool) : flag_place → flags | flag_place.CFP := {CF := b, ..f} | flag_place.ZFP := {ZF := b, ..f} | flag_place.SFP := {SF := b, ..f} | flag_place.OFP := {OF := b, ..f} inductive place | flag : flag_place → place | reg : regnum → place | rip : place | mem : qword → place inductive place.read (k : config) : place → ∀ {n}, bitvec n → Prop | flag {f} : place.read (place.flag f) (bitvec.singleton (f.read k.flags)) | reg {r} : place.read (place.reg r) (k.regs r) | rip : place.read place.rip k.rip | mem {a b} : k.mem.read1 perm.R a b → place.read (place.mem a) b inductive place.write (k : config) : place → ∀ {n}, bitvec n → config → Prop | flag {f b} : place.write (place.flag f) (bitvec.singleton b) {flags := f.write k.flags b, ..k} | reg {r n q} : place.write (place.reg r) q (k.write_reg r n q) | rip {q} : place.write place.rip q {rip := q, ..k} | mem {a b m'} : k.mem.write1 a b m' → place.write (place.mem a) b {mem := m', ..k} inductive heaplet | flag : flag_place → bool → heaplet | reg : regnum → qword → heaplet | rip : qword → heaplet | mem : qword → perm → byte → heaplet def heaplet.place : heaplet → place | (heaplet.flag fp b) := place.flag fp | (heaplet.reg r q) := place.reg r | (heaplet.rip q) := place.rip | (heaplet.mem a p v) := place.mem a def heaplet.value : heaplet → Σ n, bitvec n | (heaplet.flag fp b) := ⟨_, bitvec.singleton b⟩ | (heaplet.reg r q) := ⟨_, q⟩ | (heaplet.rip q) := ⟨_, q⟩ | (heaplet.mem a p v) := ⟨_, v⟩ def heaplet.read (k : config) : heaplet → Prop | (heaplet.flag fp b) := fp.read k.flags = b | (heaplet.reg r q) := k.regs r = q | (heaplet.rip q) := k.rip = q | (heaplet.mem a p v) := k.mem.read1 p a v def split {α} (H h₁ h₂ : set α) : Prop := H = h₁ ∪ h₂ ∧ disjoint h₁ h₂ theorem sProp.split_comm {α} {h1 h2 h : set α} : split h h1 h2 ↔ split h h2 h1 := sorry theorem sProp.split_assoc {α} {h1 h2 h3 h : set α} : (∃ h23, split h23 h2 h3 ∧ split h h1 h23) ↔ (∃ h12, split h12 h1 h2 ∧ split h h12 h3) := sorry @[reducible] def heap := set heaplet def sProp := heap → Prop def config.heap (k : config) : heap := {h | h.read k} def sProp.sep (P Q : sProp) : sProp := λ S, ∃ S₁ S₂, split S S₁ S₂ ∧ P S₁ ∧ Q S₂ def sProp.sepish (P Q : sProp) : sProp := λ S, ∃ S₁ S₂, S = S₁ ∪ S₂ ∧ P S₁ ∧ Q S₂ instance : has_mul sProp := ⟨sProp.sep⟩ theorem sProp.sep_comm (P Q : sProp) : P * Q = Q * P := sorry theorem sProp.sep_assoc (P Q R : sProp) : P * Q * R = P * (Q * R) := sorry def sProp.wand (P Q : sProp) : sProp := λ S₂, ∀ S₁ S, split S S₁ S₂ → P S₁ → Q S theorem sProp.sep_wand (P Q R : sProp) : (P * Q).wand R = P.wand (Q.wand R) := begin funext h, apply propext, split, { rintro H h' S s p a b c d, obtain ⟨e,f,g⟩ := sProp.split_assoc.1 ⟨_, s, c⟩, exact H _ _ g ⟨_, _, sProp.split_comm.1 f, p, d⟩, }, { rintro H h' S s ⟨a,b,c,d,e⟩, obtain ⟨x,f,g⟩ := sProp.split_assoc.2 ⟨_, sProp.split_comm.1 c, s⟩, refine H _ _ f d _ _ g e } end def heap.sn (H : heap) : sProp := eq H def heaplet.sn (h : heaplet) : sProp := heap.sn {h} def emp : sProp := heap.sn ∅ def lift (p : Prop) : sProp := λ _, p instance lattice.complete_lattice.sProp : complete_lattice sProp := pi.complete_lattice theorem sProp.wand_mp (P Q : sProp) : P * P.wand Q ≤ Q := λ h ⟨a,b,c,d,H⟩, H _ _ c d def sProp.with (p : sProp) (q : Prop) : sProp := p ⊓ lift q def liftE (p : Prop) : sProp := sProp.with emp p def sProp.ex {α} (p : α → sProp) : sProp := λ S, ∃ a, p a S def sProp.al {α} (p : α → sProp) : sProp := λ S, ∀ a, p a S constant heap.sat : heap → config → Prop constant config.ok : config → Prop def s_weak (P Q : sProp) : Prop := ∀ h, P h → ∃ h', Q h' ∧ h' ⊆ h axiom s_weak.sat {P Q} (H : s_weak P Q) : ∀ k, (∃ h, P h ∧ h.sat k) → (∃ h, Q h ∧ h.sat k) theorem s_sep.weak₁ {P Q} : s_weak (P * Q) P := by rintro k ⟨h, h1, ⟨rfl, h2⟩, h3, h4⟩; exact ⟨_, h3, λ _, or.inl⟩ theorem s_sep.weak₂ {P Q} : s_weak (P * Q) Q := by rw sProp.sep_comm; exact s_sep.weak₁ theorem el_s_sep_sn {x y z : heap} : (x.sn * y.sn) z ↔ split z x y := sorry theorem s_sep_sn {x y z : heap} : x.sn * y.sn = z.sn ↔ split z x y := sorry theorem s_sep.mono_right {P Q : sProp} (R) (H : P ≤ Q) : R * P ≤ R * Q := λ a ⟨b,c,d,e,f⟩, ⟨b,c,d,e, H _ f⟩ theorem s_sep.mono_left {P Q : sProp} (R) (H : P ≤ Q) : P * R ≤ Q * R := λ a ⟨b,c,d,e,f⟩, ⟨b,c,d, H _ e, f⟩ theorem s_sep.weak_right {P Q} (R) (H : s_weak P Q) : s_weak (R * P) (R * Q) := by rintro x ⟨a,b,⟨rfl,c⟩,d,e⟩; obtain ⟨f,g,h⟩ := H _ e; exact ⟨_, ⟨_, _, ⟨rfl,c.mono_right h⟩, d, g⟩, set.union_subset_union_right _ h⟩ theorem s_sep.weak_left {P Q} (R) : s_weak P Q → s_weak (P * R) (Q * R) := by rw [sProp.sep_comm P, sProp.sep_comm Q]; exact s_sep.weak_right _ def s_ok (P : sProp) : Prop := ∀ k h, P h → heap.sat h k → k.ok theorem s_ok_sep {R P} : s_ok (R * P) ↔ ∀ fr, R fr → s_ok (fr.sn * P) := sorry def hoare' (P Q : sProp) : Prop := ∀ fr:heap, s_ok (fr.sn * Q) → s_ok (fr.sn * P) theorem s_weak.hoare {P Q} (H : s_weak P Q) : hoare' P Q := by rintro fr H' k h hp b; obtain ⟨c,d,e⟩ := (s_sep.weak_right _ H).sat k ⟨_, hp, b⟩; exact H' _ _ d e theorem hoare'.frame_ok {P Q R} : hoare' P Q → s_ok (R * Q) → s_ok (R * P) := sorry theorem hoare'.ok {P Q} : hoare' P Q → s_ok Q → s_ok P := sorry theorem hoare_frame {P Q} (R) : hoare' P Q → hoare' (R * P) (R * Q) := sorry theorem unframe (R P Q : sProp) (A) (hA : ∀ h, P h → heaplet.place '' h ∩ A = ∅) (H : ∀ h:heap, heaplet.place '' h = A → hoare' (h.sn * P) (h.sn * Q)) : hoare' P Q := begin rintro fr hQ k p ⟨_, a, hp, ⟨⟩, hP⟩ pk, have := hA _ hP, obtain ⟨x:heap, y, z, w, u, hx1, hx2, hx3, hx4, hx5⟩ : ∃ x y z w u:heap, heaplet.place '' x = A ∧ split y w p ∧ split x z w ∧ split fr z u ∧ y.sat k, { sorry }, have : s_ok (u.sn * (x.sn * Q)), { refine (s_weak.hoare _).ok hQ, rw ← sProp.sep_assoc, apply s_sep.weak_left, rw [← s_sep_sn.2 hx4, sProp.sep_comm], apply s_sep.weak_left, rw [← s_sep_sn.2 hx3], exact s_sep.weak₁ }, have := H _ hx1 u this, rw [← sProp.sep_assoc, ← s_sep_sn.2 hx3, ← sProp.sep_assoc, sProp.sep_comm u.sn, s_sep_sn.2 hx4, sProp.sep_comm fr.sn, sProp.sep_assoc] at this, refine this k _ ⟨_, _, hx2, ⟨_⟩, _, _, hp, ⟨_⟩, hP⟩ hx5, end theorem sep_le_sep {P₁ P₂ Q₁ Q₂ : sProp} (H₁ : P₁ ≤ Q₁) (H₂ : P₂ ≤ Q₂) : P₁ * P₂ ≤ Q₁ * Q₂ := λ S ⟨S₁, S₂, h₁, h₂, h₃⟩, ⟨S₁, S₂, h₁, H₁ _ h₂, H₂ _ h₃⟩ def place.clob (p : place) : sProp := sProp.ex $ λ h:heaplet, h.sn.with (h.place = p) def sProp.flags (f : flags) : sProp := sProp.al $ λ p, (heaplet.flag p $ p.read f).sn inductive block | reg : regnum → wsize → block | mem : qword → qword → block | const : list byte → block def block.size : block → qword | (block.reg _ sz) := (sz.to_nat / 8 : ℕ) | (block.mem _ sz) := sz | (block.const l) := l.length inductive block.places : block → set place | reg {r sz} : block.places (block.reg r sz) (place.reg r) | mem {a b sz : qword} : (bitvec.sub b a).to_nat ≤ sz.to_nat → block.places (block.mem a sz) (place.mem b) def block.disj (b1 b2 : block) := disjoint b1.places b2.places def sProp.mem_block (p : perm) : qword → list byte → sProp | a [] := emp | a (b :: v) := sProp.ex (λ q, (heaplet.mem a q b).sn.with (p ≤ q)) * sProp.mem_block (a + 1) v theorem sProp.mem_block.mono {p₁ p₂} (h : p₁ ≤ p₂) : ∀ {a v}, sProp.mem_block p₂ a v ≤ sProp.mem_block p₁ a v | a [] := le_refl _ | a (b :: v) := sep_le_sep (λ S ⟨q, h₁, h₂⟩, ⟨q, h₁, le_trans h h₂⟩) sProp.mem_block.mono def block.read : block → list byte → sProp | (block.reg r sz) v := sProp.ex $ λ q, (heaplet.reg r q).sn.with $ read_full_imm sz q v | (block.mem a sz) v := (sProp.mem_block perm.R a v).with $ v.length = sz.to_nat | (block.const l) v := liftE $ v = l def block.readW : block → list byte → sProp | (block.reg r sz) v := sProp.ex $ λ q, (heaplet.reg r q).sn.with $ read_full_imm sz q v | (block.mem a sz) v := (sProp.mem_block (perm.R + perm.W) a v).with $ v.length = sz.to_nat | (block.const l) v := lift false theorem block.read.size : ∀ {b v k}, block.read b v k → v.length = b.size.to_nat := sorry theorem block.readW_le_read : ∀ {b v}, block.readW b v ≤ block.read b v | (block.reg r sz) v := le_refl _ | (block.mem a sz) v := λ s ⟨h₁, h₂⟩, ⟨sProp.mem_block.mono perm.le_add_left _ h₁, h₂⟩ | (block.const l) v := by rintro _ ⟨⟩ def hoare (P : kcfg → Prop) (Q : kcfg → Prop) := ∀ {{k}}, P k → hoare_p Q k def sHoareIO (P : sProp) (Q : list byte → list byte → sProp) := ∀ i₁ o₁ R, hoare (λ ⟨i, o, k⟩, (P * R) k.heap ∧ i = i₁ ∧ o = o₁) (λ ⟨i₂, o₂, k₂⟩, ∃ i' o', i₁ = i' ++ i₂ ∧ o₂ = o₁ ++ o' ∧ (Q i' o' * R) k₂.heap) def noIO (Q : sProp) (i o : list byte) : sProp := Q.with (i = [] ∧ o = []) def sHoare (P Q : sProp) := sHoareIO P (noIO Q) def sHoareW (C P Q : sProp) := sHoare (P * C) (Q * C) def locals_ctx := alist (λ _ : ℕ, block) def locals_ctx.get (Γ : locals_ctx) (n : ℕ) : option block := Γ.lookup n def labels_ctx := qword × list qword def labels_ctx.cons (q : qword) (L : labels_ctx) : labels_ctx := ⟨L.1, q :: L.2⟩ structure asm_ctx := (L : list qword) (Γ : alist (λ _ : ℕ, block)) (exit : qword) (die : ∃ l, sHoare ((heaplet.rip exit).sn ⊓ sProp.mem_block (perm.R + perm.X) exit l) ⊥) def asm_ctx.read (A : asm_ctx) (n : ℕ) : option block := A.Γ.lookup n def asm_ctx.push_local (A : asm_ctx) (i : ℕ) (b : block) : asm_ctx := ⟨A.1, A.2.insert i b, A.3, A.4⟩ def asm_ctx.push_label (A : asm_ctx) (q : qword) : asm_ctx := ⟨q :: A.1, A.2, A.3, A.4⟩ inductive exit_kind | straight | label (n : ℕ) def exit_kind.result (A : asm_ctx) (pos : qword) : exit_kind → sProp | exit_kind.straight := (heaplet.rip pos).sn | (exit_kind.label n) := sProp.ex $ λ h, (heaplet.rip (A.1.nth_le n h)).sn def stmt : Type := asm_ctx → set place → ∀ rip : qword, list byte → Prop def stmt.hoareIO (A) (P : sProp) (C : stmt) (Q : exit_kind → list byte → list byte → sProp) : Prop := ∀ D rip l, C A D rip l → sHoareIO (P * (heaplet.rip rip).sn * sProp.mem_block (perm.R + perm.X) rip l) (λ i o, sProp.ex $ λ e, Q e i o * e.result A (rip + l.length) * sProp.mem_block (perm.R + perm.X) rip l) def stmt.hoare (A P C) (Q : exit_kind → sProp) : Prop := stmt.hoareIO A P C (λ e, noIO (Q e)) def hstmt (P Q : sProp) : stmt := λ L Γ rip v, sHoareW (sProp.mem_block (perm.R + perm.X) rip v) (P * (heaplet.rip rip).sn) (Q * (heaplet.rip (rip + v.length)).sn) def hstmtW (C P Q : sProp) : stmt := hstmt (P * C) (Q * C) instance complete_lattice.stmt : complete_lattice stmt := pi.complete_lattice def stmt.all {α} (s : α → stmt) : stmt := λ A D rip v, ∀ a, s a A D rip v def stmt.ex {α} (s : α → stmt) : stmt := λ A D rip v, ∃ a, s a A D rip v def stmt.with (p : Prop) (s : stmt) : stmt := stmt.ex $ λ h : p, s def stmt.or (s₁ s₂ : stmt) : stmt := λ A D rip v, s₁ A D rip v ∨ s₂ A D rip v def expr (α : Type) := block → stmt instance complete_lattice.expr {α} : complete_lattice (expr α) := pi.complete_lattice def expr.hoareIO {α} (A) (P : sProp) (E : expr α) (Q : block → list byte → list byte → sProp) : Prop := ∀ b, (E b).hoareIO A P $ λ e i o, (Q b i o).with (e = exit_kind.straight) def expr.hoare {α} (A) (P : sProp) (E : expr α) (Q : block → sProp) : Prop := expr.hoareIO A P E (λ ret i o, noIO (Q ret) i o) class value (α : Type*) := (size : ℕ) (eval : α → list byte → Prop) (eval_eq : ∀ {{a l}}, eval a l → l.length = size) def value.evalB {α} [value α] (x : α) (b : block) : sProp := sProp.ex $ λ l, (block.read b l).with $ value.eval x l def value.read_sized {α} [value α] (a : qword) (x : α) (b : block) : sProp := (value.evalB x b).with (b = block.mem a (value.size α)) class type (α : Type*) := (size : ℕ) (read : α → block → sProp) (read_eq : ∀ {{a b s}}, read a b s → b.size.to_nat = size) instance (α) [value α] : type α := ⟨value.size α, λ a b, sProp.ex $ λ v, (block.read b v).with (value.eval a v), λ a b s ⟨v, h₁, h₂⟩, by rw [← h₁.size, @value.eval_eq α _ a v h₂]⟩ def bits.value {n} (m : ℕ) : value (bitvec n) := ⟨m, bits_to_byte m, λ a v h, h.1⟩ instance unit.value : value unit := ⟨0, λ _ v, v = [], by rintro _ _ ⟨⟩; refl⟩ instance byte.value : value byte := ⟨1, λ b v, v = [b], by rintro _ _ ⟨⟩; refl⟩ instance word.value : value word := bits.value 4 instance qword.value : value qword := bits.value 8 class box (α) [type α] := (deref : α) instance box.type (α) [type α] : type (box α) := ⟨8, λ x b, sProp.ex $ λ a, sProp.ex $ λ v, (block.read b v).with (qword.to_list_byte a v) * type.read x.deref (block.mem a (type.size α)), λ x b s ⟨a, v, _, _, _, ⟨h₁, h₂, _⟩, _⟩, by rw [← h₁.size, h₂]⟩ def ret (α) (b : block) : expr α := λ bl A D a v, bl = b ∧ v = [] def const (α) (l : list byte) : expr α := ret α (block.const l) def name (α : Type) := ℕ def var {α} (i : name α) : expr α := λ bl A D a v, bl ∈ A.read i ∧ v = [] def hexpr {α} (P : sProp) (Q : block → sProp) : expr α := λ ret, hstmt P (Q ret) def hexprW {α} (C P : sProp) (Q : block → sProp) : expr α := λ ret, hstmtW C P (Q ret) def expr.all {α β} (e : α → expr β) : expr β := λ ret, stmt.all $ λ a, e a ret def expr.ex {α β} (e : α → expr β) : expr β := λ ret, stmt.ex $ λ a, e a ret def expr.with {α} (p : Prop) (s : expr α) : expr α := expr.ex $ λ h : p, s def const' {α} [type α] (a : α) : expr α := hexpr ⊤ $ type.read a inductive stmt.seq (s₁ s₂ : stmt) : stmt | mk {A D rip v₁ v₂} : s₁ A D rip v₁ → s₂ A D (rip + v₁.length) v₂ → stmt.seq A D rip (v₁ ++ v₂) inductive expr.bindS {α} (e₁ : expr α) (s₂ : block → stmt) : stmt | mk {b A D rip v₁ v₂} : e₁ b A D rip v₁ → s₂ b A D (rip + v₁.length) v₂ → expr.bindS A D rip (v₁ ++ v₂) def expr.bind {α β} (e₁ : expr α) (e₂ : block → expr β) : expr β := λ b₂, expr.bindS e₁ $ λ b₁, e₂ b₁ b₂ def block.mov (dst src : block) : stmt := λ A D rip v, dst.size = src.size ∧ ∀ val P, sProp.ex (block.readW dst) * P ≤ block.read src val → hstmtW P (sProp.ex (block.readW dst)) (block.readW dst val) A D rip v def expr.set {α} (e₁ e₂ : expr α) : stmt := expr.bindS e₁ $ λ dst, expr.bindS e₂ $ λ src, block.mov dst src inductive label | fail | label (n : ℕ) inductive label.loc (A : asm_ctx) : label → qword → Prop | fail : label.loc label.fail A.exit | label (n h) : label.loc (label.label n) (A.L.nth_le n h) def stmt.jump_cc (p : flags → bool) (l : label) : stmt := λ A D rip v, ∀ tgt, l.loc A tgt → sHoareW (sProp.mem_block (perm.R + perm.X) rip v) (sProp.ex sProp.flags * (heaplet.rip rip).sn) (sProp.ex $ λ f, sProp.flags f * (heaplet.rip (cond (p f) tgt (rip + v.length))).sn) def stmt.jump : label → stmt := stmt.jump_cc (λ _, tt) def boolexpr := (flags → bool) → stmt def boolexpr.hoare (A) (P : sProp) (E : boolexpr) (Q : bool → sProp) : Prop := ∃ p, stmt.hoare A (sProp.ex sProp.flags * P) (E p) (λ e, sProp.ex $ λ f, sProp.flags f * (Q (p f)).with (e = exit_kind.straight)) def boolexpr.not (c : boolexpr) : boolexpr := λ p, c (bnot ∘ p) def boolexpr.jump_if (c : boolexpr) (l : label) : stmt := stmt.ex $ λ p, (c p).seq $ stmt.jump_cc p l def stmt.nop : stmt := λ A D rip v, v = [] def if_stmt (c : boolexpr) (s₁ s₂ : stmt) : stmt := stmt.ex $ λ p, stmt.seq (c p) $ λ A D rip v, ∃ v₁ v₂ v₃, v = v₁ ++ v₂ ++ v₃ ∧ let q₁ := rip + v₁.length, q₂ := q₁ + v₂.length in stmt.jump_cc (bnot ∘ p) (label.label 0) (A.push_label q₁) D rip v₁ ∧ s₁.seq (stmt.jump (label.label 0)) (A.push_label q₂) D q₁ v₂ ∧ s₂.seq (stmt.jump (label.label 0)) (A.push_label q₂) D q₂ v₃ def loop (s : stmt) : stmt := λ A D rip, s (A.push_label rip) D rip def block_stmt (s : stmt) : stmt := λ A D rip v, s (A.push_label (rip + v.length)) D rip v def while (c : boolexpr) (s : stmt) : stmt := block_stmt $ loop $ (c.not.jump_if (label.label 1)).seq $ s.seq $ stmt.jump (label.label 0) def decl_block {α} (b : block) (s : name α → stmt) : stmt := λ A D rip v, ∃ i, s i (A.push_local i b) D rip v def decl {α} (sz : qword) (s : name α → stmt) : stmt := stmt.ex $ λ b, stmt.with (block.size b = sz) $ decl_block b s def init {α} (e : expr α) (s : name α → stmt) : stmt := e.bindS $ λ b, decl_block b s /- def binop_expr {α β γ} [type α] [type β] [type γ] (f : α → β → γ) (e₁ : expr α) (e₂ : expr β) : expr γ := e₁.bind $ λ b₁, e₂.bind $ λ b₂ b, stmt.all $ λ x, stmt.all $ λ y, hstmt (type.read' x b₁ ⊓ type.read' y b₂) (type.write (f x y) b) def asn_binop {α β} [type α] [type β] (f : α → β → α) (e₁ : expr α) (e₂ : expr β) : stmt := e₁.bindS $ λ b₁, (ret α b₁).set (binop_expr f (ret α b₁) e₂) def unop_expr {α β} [type α] [type β] (f : α → β) (e : expr α) : expr β := e.bind $ λ b₁ b, stmt.ex $ λ x, hstmt (type.read' x b₁) (type.write (f x) b) def asn_unop {α} [type α] (f : α → α) (e : expr α) : stmt := e.bindS $ λ b, (ret α b).set (unop_expr f (ret α b)) def for {α} (start : expr α) (test : name α → boolexpr) (incr body : name α → stmt) : stmt := init start $ λ i, while (test i) $ (body i).seq (incr i) def incr {α} [type α] [has_add α] [has_one α] : expr α → stmt := asn_unop (+ 1) def bool_binop {α β} [type α] [type β] (f : α → β → bool) (e₁ : expr α) (e₂ : expr β) : boolexpr := λ p, e₁.bindS $ λ b₁, e₂.bindS $ λ b₂, stmt.ex $ λ x, stmt.ex $ λ y, hstmt (type.read' x b₁ ⊓ type.read' y b₂) (mProp.final mProp.id (λ k, p k.flags = f x y)) def ltq (e₁ e₂ : expr qword) : boolexpr := bool_binop (λ a b : qword, a.to_nat < b.to_nat) e₁ e₂ def for_seq (sz : qword) (max : expr qword) (body : name qword → stmt) : stmt := for (const' (0 : qword)) (λ i, ltq (const' 0) max) (λ i, incr (var i)) body ---------------------------------------- -- Assembly ---------------------------------------- theorem hoare.mono {P Q : kcfg → set place → Prop} (H : ∀ {{k S}}, P k S → Q k S) : hoare P Q := λ k S p, hoare_p.zero (H p) theorem hoare.step {P P' Q : kcfg → set place → Prop} (h₁ : ∀ {{k S}}, P k S → ∃ k', k.step k') (h₂ : ∀ {{k S}}, P k S → ∀ {{k'}}, k.step k' → P' k' S) (h₃ : hoare P' Q) : hoare P Q := λ k S p, hoare_p.step (h₁ p) (λ k' s, h₃ (h₂ p s)) theorem hoare.mono_l {P P' Q : kcfg → set place → Prop} (H : ∀ {{k S}}, P k S → P' k S) : hoare P' Q → hoare P Q := λ H' k S h, H' (H h) theorem hoare_p.mono_l {P P' : kcfg → set place → Prop} (H : ∀ {{k S}}, P k S → P' k S) {k S} : hoare_p P k S → hoare_p P' k S := begin intro h, induction h, exact hoare_p.zero (H h_a), exact hoare_p.step h_a (λ k', h_ih _), exact hoare_p.exit _ _ _ h_a (λ e, H (h_a_1 e)), end theorem hoare.mono_r {P Q Q' : kcfg → set place → Prop} (H : ∀ {{k S}}, Q k S → Q' k S) : hoare P Q → hoare P Q' := λ H' k S h, hoare_p.mono_l H (H' h) theorem sHoareIO.mono {P : sProp} {Q : list byte → list byte → sProp} (H : ∀ {{k S}}, P k S → Q [] [] k S) : sHoareIO P Q := λ i o, hoare.mono $ by rintro k S ⟨h, rfl, rfl⟩; exact ⟨[], [], rfl, (list.append_nil _).symm, H h⟩ theorem sHoareIO.mono_l {P P' : sProp} {Q : list byte → list byte → sProp} (H : ∀ {{k S}}, P k S → P' k S) : sHoareIO P' Q → sHoareIO P Q := λ h i o, hoare.mono_l (by exact λ k S ⟨h₁, h₂⟩, ⟨H h₁, h₂⟩) (@h i o) theorem sHoareIO.mono_r {P : sProp} {Q Q' : list byte → list byte → sProp} (H : ∀ {{i o k S}}, Q i o k S → Q' i o k S) : sHoareIO P Q → sHoareIO P Q' := λ h i o, hoare.mono_r (by exact λ k S ⟨i', o', h₁, h₂, h₃⟩, ⟨i', o', h₁, h₂, H h₃⟩) (@h i o) theorem sHoareIO.step {P P' : sProp} {Q : list byte → list byte → sProp} (h₁ : ∀ ⦃k i o S⦄, P k S → ∃ k', kcfg.step ⟨i, o, k⟩ k') (h₂ : ∀ {{k₁ i₁ o₁ k₂ i₂ o₂ S}}, P k₁ S → kcfg.step ⟨i₁, o₁, k₁⟩ ⟨i₂, o₂, k₂⟩ → P' k₂ S ∧ i₂ = i₁ ∧ o₂ = o₁) (h₃ : sHoareIO P' Q) : sHoareIO P Q := λ i o, hoare.step (λ ⟨i', o', k⟩ S h, h₁ h.1) (by rintro ⟨i₁, o₁, k₁⟩ S ⟨h, rfl, rfl⟩ ⟨i₂, o₂, k₂⟩ h'; exact @h₂ k₁ i₁ o₁ k₂ i₂ o₂ S h h') (@h₃ i o) theorem sHoareIO.asm (P : sProp) (Q : list byte → list byte → sProp) : sHoareIO P Q := λ i o, sorry theorem sHoare.mono {P Q : sProp} (H : ∀ {{k S}}, P k S → Q k S) : sHoare P Q := sHoareIO.mono $ λ k S h, ⟨H h, rfl, rfl⟩ theorem sHoare.mono_l {P P' Q : sProp} (H : ∀ {{k S}}, P k S → P' k S) : sHoare P' Q → sHoare P Q := sHoareIO.mono_l H theorem sHoare.mono_r {P Q Q' : sProp} (H : ∀ {{k S}}, Q k S → Q' k S) : sHoare P Q → sHoare P Q' := sHoareIO.mono_r $ λ i o k S ⟨h₁, h₂⟩, ⟨H h₁, h₂⟩ theorem config.isIO_terminal {k} : (∃ k', config.step k k') → ¬ ∃ k', k.isIO k' := sorry theorem sHoare.step {P P' Q : sProp} (h₁ : ∀ ⦃k S⦄, P k S → ∃ k', config.step k k') (h₂ : ∀ ⦃k S⦄, P k S → ∀ k', config.step k k' → P' k' S) : sHoare P' Q → sHoare P Q := sHoareIO.step (λ k i o S h, let ⟨k', h'⟩ := h₁ h in ⟨_, kcfg.step.noio h'⟩) (λ k₁ i₁ o₁ k₂ i₂ o₂ S h h', begin cases h', exact ⟨h₂ h _ h'_a, rfl, rfl⟩, cases config.isIO_terminal (h₁ h) ⟨_, h'_a⟩ end) def stmt.asm {n} (s : stmt n) := Π L Γ rip, ∃ v, s L Γ rip v theorem hstmt.step {n} {P P' Q : sProp} (h₁ : ∀ (L : labels_ctx) (Γ : locals_ctx n) rip, ∃ l, ∀ v k S, (P * sProp.sn place.rip rip * sProp.mem_block (perm.R + perm.X) rip (l ++ v)) k S → ∃ a k', decode a l ∧ (write_rip (k.rip + bitvec.of_nat 64 l.length) k).P () k' ∧ (execute a k').P () k ∧ ∀ H, P k H → P' k' H) (h₂ : (@hstmt n P' Q).asm) : (@hstmt n P Q).asm := λ L Γ rip, let ⟨l, H⟩ := h₁ L Γ rip, ⟨v, H₂⟩ := h₂ L Γ rip in ⟨l ++ v, begin refine sHoare.step (λ k S h, _) (λ k S h k', _) (sHoare.mono_r _ H₂), { rcases H v k S h with ⟨a, k', h₃, h₄, h₅, h₆⟩, have : mem.readX (k.mem) (k.rip) l, sorry, exact ⟨k, this, h₃, (), k', h₄, h₅⟩ }, { rintro ⟨l, a, _, m, d, h⟩, sorry }, sorry, end⟩ theorem hstmt.asm {n} (P : sProp) (Q : sProp) : (@hstmt n P Q).asm := sorry -/ end x86
583fb134bd924edc6d92ade34ef383d79b1a7f2d
7c4610454cf55b49f0c3cdaeb6b856eb3249cb2d
/src/primes.lean
e6db92499700566e2edc174461db12d9cee4b376
[]
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
41,653
lean
import relatively_prime set_lemmas linear_algebra.projection ring_theory.coprime linear_algebra.basis linear_algebra.direct_sum_module new_file tactic.abel open_locale classical /-- Given prime `p : R`, for all `n : ℕ`, `p ^ (n + 1)` isn't a unit.-/ lemma not_unit_of_prime_pow {R : Type*} [comm_ring R] {p : R} (hp : prime p) {n : ℕ} : ¬(is_unit (p ^ n.succ)) := begin intro hu, rw is_unit_iff_dvd_one at hu, exact hp.2.1 (is_unit_iff_dvd_one.2 $ dvd_trans (⟨p ^ n, by {rw ←pow_succ}⟩) hu) end variables (R : Type*) [integral_domain R] [is_principal_ideal_ring R] [decidable_eq R] [decidable_eq (associates R)] namespace coprimes variable (r : R) def span := submodule.span R (↑(coprimes' r) : set R) variables {R} (hr : r ≠ 0) (hu : ¬is_unit r) include hr hu lemma span_eq_top : span R r = ⊤ := begin cases submodule.is_principal.principal (span R r) with x hx, erw [hx, ideal.span_singleton_eq_top], exact relatively_prime' r hr hu (λ y H, by {rw ←ideal.mem_span_singleton, change _ = ideal.span {x} at hx, rw ←hx, exact submodule.subset_span H}) end end coprimes variables (R) (M : Type*) [add_comm_group M] [module R M] (A : submodule R M) def Tp := submodule.span R $ ⋃ (p : {p : R // prime p}), (prime_pow_ord A p).1 variables {R} {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] set_option class.instance_max_depth 50 lemma ord_eq (y : tors R A) : ord R A (y : A) = ord R (tors R A) y := submodule.ext $ λ x, ⟨λ (h : _ = _), show _ = _, from subtype.ext_iff.2 $ by erw ←submodule.coe_smul at h; erw h; refl, λ (h : _ = _), show _ = _, from subtype.ext_iff.1 h⟩ variables (R) lemma tors_gen : Tp R M A = ⊤ := begin ext, split, tauto, intro, cases classical.em (x = 0), rw [h, ←submodule.mem_coe], exact (Tp R M A).2, cases submodule.is_principal.principal (ord R (tors R A) x) with r hr, change _ = ideal.span {r} at hr, have hr0 : r ≠ 0, by { assume h, rw [h, ideal.span_singleton_eq_bot.2 rfl] at hr, rcases x.2 with ⟨s, hs0, hs⟩, change s ∈ ord R A (x : A) at hs, rw ←ord_eq at hr, rw hr at hs, exact absurd ((submodule.mem_bot R).1 hs) hs0}, have hu : ¬is_unit r, by { assume hu, rw (ideal.span_singleton_eq_top.2 hu) at hr, have h1 : (1 : R) ∈ ord R (tors R A) x, from hr.symm ▸ submodule.mem_top, exact absurd (show x = 0, from one_smul R x ▸ set.mem_def.1 h1) h}, cases exists_repr_of_mem_span (coprimes' r) 1 (show (1:R) ∈ (coprimes.span R r), by rw coprimes.span_eq_top r hr0 hu; simp) with ι h1, rw ←one_smul R x, rw h1, rw finset.sum_smul, rw Tp, refine sum_mem_span _, intros q hq, rcases finset.mem_image.1 hq with ⟨p, hp, h⟩, use p, exact (unique_factorization_domain.prime_factors hr0 p (multiset.mem_to_finset.1 hp)), have hp0 : (multiset.filter (λ x, associated x p) (unique_factorization_domain.factors r)).prod • (ι q * q) • x = 0, begin rw ←mul_smul, rw mul_comm, rw mul_assoc, rw ←h, cases prod_of_dvd_eq' r hr0 p with u hu, rw ←units.eq_mul_inv_iff_mul_eq at hu, erw hu, rw mul_comm r, rw ←mul_assoc, rw mul_smul, convert smul_zero _, show r ∈ ord R (tors R A) x, rw hr, exact ideal.mem_span_singleton.2 ⟨1, (mul_one r).symm⟩, end, have H1 := @associated_pow' _ _ _ _ _ _ (unique_factorization_domain.factors r) rfl p, have H2 := @associated_prod _ _ _ _ _ _ (multiset.filter (λ (x : R), associated x p) (unique_factorization_domain.factors r)) (multiset.repeat p (multiset.filter (λ (x : R), associated x p) (unique_factorization_domain.factors r)).card) rfl (multiset.card_repeat _ _) H1, cases associates.mk_eq_mk_iff_associated.1 H2 with v hv, rw multiset.prod_repeat at hv, cases prime_pow_le _ _ _ _ (by {rw ←hv, rw mul_comm, rw mul_smul, rw hp0, rw smul_zero}) with j hj, use j, exact hj.2, exact (unique_factorization_domain.prime_factors hr0 p (multiset.mem_to_finset.1 hp)), end instance huh {ι : Type*} (s : finset ι) : fintype (↑s : set ι) := fintype.of_finset s (λ x, iff.rfl) local infix ` ~ᵤ ` : 50 := associated variables {R} lemma is_coprime_of_prime {p q : R} (hp : prime p) (h : ¬ p ∣ q) : is_coprime p q := begin cases submodule.is_principal.principal (ideal.span ({p, q} : set R)) with w hw, cases ideal.mem_span_singleton.1 (show p ∈ ideal.span {w}, by rw ideal.span; rw ←hw; exact submodule.subset_span (show p ∈ {p, q}, by simp only [set.mem_insert_iff, true_or, eq_self_iff_true])) with t ht, cases ideal.mem_span_singleton.1 (show q ∈ ideal.span {w}, by rw ideal.span; rw ←hw; exact submodule.subset_span (show q ∈ {p, q}, by simp only [set.mem_insert_iff, set.mem_singleton, or_true])) with r hr, have hwp : ¬ p ∣ w := λ hwp, h $ dvd_trans hwp ⟨r, hr⟩, have hwu : is_unit w := by { refine or.resolve_right ((irreducible_of_prime hp).2 w t ht) _, rintro ⟨s, hs⟩, exact hwp ⟨(s⁻¹ : units R), by {rw ht, rw ←hs, simp only [units.mul_inv_cancel_right],}⟩}, rcases ideal.mem_span_pair.1 (show w ∈ ideal.span {p, q}, by rw hw; exact ideal.mem_span_singleton.2 (dvd_refl _)) with ⟨a, b, hab⟩, cases hwu with u hu, rw ←units.mul_right_inj u⁻¹ at hab, rw ←hu at hab, rw units.inv_mul at hab, rw mul_add at hab,rw ←mul_assoc at hab, rw ←mul_assoc at hab, use [↑u⁻¹ * a, ↑u⁻¹ * b], exact hab, end lemma prime_pow_unique {p : {p : R // prime p}} {q1 q2 : @subtype R (λ q, prime q ∧ ¬ associated q ↑p)} {m n : ℕ} (h0 : m ≠ 0) (h : ideal.span ({q1.1 ^ m} : set R) = ideal.span {q2.1 ^ n}) : associated q1.1 q2.1 ∧ m = n := begin have h1 := ideal.mem_span_singleton.1 (by rw ←h; exact ideal.mem_span_singleton.2 (dvd_refl _)), have h2 := ideal.mem_span_singleton.1 (by rw h; exact ideal.mem_span_singleton.2 (dvd_refl _)), have h12 := associated_of_dvd_dvd h1 h2, cases m, exfalso, exact h0 rfl, rcases unique_factorization_domain.exists_mem_factors_of_dvd (ne_zero_of_prime_pow R n q2.2.1) (irreducible_of_prime q1.2.1) (dvd_trans ⟨q1.1 ^ m, by rw pow_succ; refl⟩ h2) with ⟨r, hrm, hr⟩, have hm2 := factors_prime_pow n q2.2.1, have hra : associated r q2.1 := by {rw ←associates.mk_eq_mk_iff_associated, suffices : associates.mk r ∈ multiset.map associates.mk (unique_factorization_domain.factors (q2.val ^ n)), by {rw hm2 at this, exact multiset.eq_of_mem_repeat this}, exact multiset.mem_map_of_mem _ hrm}, have := associated.trans hr hra, split, exact this, have hunique := associates.rel_associated_iff_map_eq_map.1 (unique_factorization_domain.unique (unique_factorization_domain.irreducible_factors $ ne_zero_of_prime_pow R m.succ q1.2.1) (unique_factorization_domain.irreducible_factors $ ne_zero_of_prime_pow R n q2.2.1) (associated.trans (unique_factorization_domain.factors_prod (ne_zero_of_prime_pow R m.succ q1.2.1)) $ associated.trans h12.symm (unique_factorization_domain.factors_prod (ne_zero_of_prime_pow R n q2.2.1)).symm)), rw hm2 at hunique, have hm1 := factors_prime_pow m.succ q1.2.1, rw hunique at hm1, rw ←multiset.card_repeat (associates.mk q2.1) n, rw ←multiset.card_repeat (associates.mk q1.1) m.succ, rw hm1, end lemma not_dvd (p : {p : R // prime p}) {l : (tors R A) →₀ R} (hS : ↑(l.support) ⊆ (⋃ (q : { q // prime q ∧ ¬associated q ↑p}), (prime_pow_ord A ⟨(q.1 : R), q.2.1⟩).1)) (H : ∀ (x : (tors R A)), x ∈ l.support → (∃ (q : {q // prime q ∧ ¬associated q ↑p}) (n : ℕ), ord R (tors R A) x = ideal.span {(q.1 : R) ^ n})) : ¬ p.1 ∣ @finset.prod (↑l.support : set _) _ _ (@finset.univ (↑l.support : set _) $ huh l.support)(λ x, (classical.some (H x x.2)).1 ^ (classical.some (classical.some_spec $ H x x.2))) := begin set Q := @finset.prod (↑l.support : set _) _ _ (@finset.univ (↑l.support : set _) $ huh l.support) (λ x, (classical.some (H x x.2)).1 ^ (classical.some (classical.some_spec $ H x x.2))), intro hnot, rcases exists_mem_multiset_dvd_of_prime p.2 hnot with ⟨a, hma, ha⟩, cases multiset.mem_map.1 hma with y hy, have h0 : classical.some (classical.some_spec (H y y.2)) ≠ 0 := λ h0, by {rw h0 at hy, rw pow_zero at hy, rw ←hy.2 at ha, exact p.2.2.1 (is_unit_iff_dvd_one.2 ha)}, cases set.mem_Union.1 (hS y.2) with r hr, cases hr with k hk, have hreq : associated (classical.some (H y y.2)).1 r.1 := (prime_pow_unique h0 ((classical.some_spec $ classical.some_spec $ H y.1 y.2).symm.trans hk)).1, have hkeq : (classical.some (classical.some_spec (H y y.2))) = k := (prime_pow_unique h0 ((classical.some_spec $ classical.some_spec $ H y.1 y.2).symm.trans hk)).2, cases hreq.symm with u hu, rw hkeq at hy, rw ←hu at hy, rw ←hy.2 at ha, rw ←multiset.prod_repeat at ha, rcases exists_associated_mem_of_dvd_prod p.2 (λ b hb, by {have hb' : b = r * u := @multiset.eq_of_mem_repeat _ _ _ k hb, rw hb', exact (prime_iff_of_associated ⟨u, rfl⟩).1 r.2.1,}) ha with ⟨s, hms, hs⟩, rw multiset.eq_of_mem_repeat hms at hs, exact r.2.2 (associated.trans (⟨u, rfl⟩) hs.symm), end lemma trivial_inter (p : {p : R // prime p}) : prime_pow_ord A p ⊓ (submodule.span R $ ⋃ (q : {q : R // prime q ∧ ¬ associated q p}), (prime_pow_ord A ⟨q.1, q.2.1⟩).1) = ⊥ := begin rw eq_bot_iff, intros x hx, apply (submodule.mem_bot R).2, cases hx.1 with m hm, have hpm := eq_zero_of_ord_pow m p.2 hm, rcases (@finsupp.mem_span_iff_total (tors R A) (tors R A) R _ _ _ (@id (tors R A)) (⋃ (q : {q : R // prime q ∧ ¬associated q ↑p}), (prime_pow_ord A ⟨q.1, q.2.1⟩).1) x).1 (by {rw set.image_id, exact hx.2}) with ⟨l, hl, hl'⟩, have hS := (finsupp.mem_supported _ _).1 hl, cases (classical.em (l.support = ∅)), rw finsupp.support_eq_empty.1 h at hl', rw ←hl', rw finsupp.total_apply, exact finset.sum_empty, have H : ∀ x ∈ l.support, ∃ (q : {q : R // prime q ∧ ¬ associated q p}) (n : ℕ), ord R (tors R A) x = ideal.span ({q.1 ^ n} : set R) := λ y hy, set.mem_Union.1 (hS (finset.mem_coe.2 hy)), cases finset.nonempty_of_ne_empty h with z hz, let Q := @finset.prod (↑l.support : set _) _ _ (@finset.univ (↑l.support : set _) $ huh l.support) (λ x, (classical.some (H x x.2)).1 ^ (classical.some (classical.some_spec $ H x x.2))), have HQ : Q • x = 0, by {rw ←hl', rw finsupp.total_apply, rw finsupp.smul_sum, rw ←@finset.sum_const_zero _ _ l.support _, apply finset.sum_congr rfl, intros y hy, dsimp, rw smul_comm, let q := classical.some (H y hy), let n := classical.some (classical.some_spec $ H y hy), let hq := classical.some_spec (classical.some_spec $ H y hy), suffices : q.1 ^ n ∣ Q, by {cases this with c hc, rw hc, rw mul_comm, rw mul_smul, rw eq_zero_of_ord_pow n q.2.1 hq, erw smul_zero, erw smul_zero }, refine @dvd_prod_finset (↑l.support : set _) _ _ ⟨y, hy⟩ (λ x, (classical.some (H x x.2)).1 ^ (classical.some (classical.some_spec $ H x x.2))) (@finset.univ (↑l.support : set _) $ huh l.support) _, exact finset.mem_univ _}, rcases (show is_coprime (p.1 ^ m) Q, by { apply is_coprime.pow_left, apply is_coprime_of_prime p.2, exact not_dvd _ _ p hS H }) with ⟨a, b, hab⟩, rw ←one_smul _ x, rw ←hab, rw add_smul, rw mul_smul, rw mul_smul, rw hpm, rw smul_zero, rw HQ, rw smul_zero, rw zero_add, end instance noe (Hfg : A.fg) : is_noetherian R (tors R A) := is_noetherian_of_submodule_of_noetherian R A (tors R A) (is_noetherian_of_fg_of_noetherian A Hfg) noncomputable def prime_gen_set (Hfg : A.fg) (p : {p : R // prime p}) : finset (tors R A) := classical.some (@is_noetherian.noetherian _ _ _ _ _ (noe M A Hfg) (prime_pow_ord A p)) theorem prime_gen_set_gens (Hfg : A.fg) (p : {p : R // prime p}) : submodule.span R (↑(prime_gen_set M A Hfg p) : set _) = prime_pow_ord A p := classical.some_spec (@is_noetherian.noetherian _ _ _ _ _ (noe M A Hfg) (prime_pow_ord A p)) lemma smul_zero_of_Inf {x : R} (Hn : Inf (set.range (ord R M)) = ideal.span ({x} : set R)) (y : M) : x • y = 0 := begin show x ∈ ord R M y, apply Inf_le (show ord R M y ∈ set.range (ord R M), from ⟨y, rfl⟩), rw Hn, exact ideal.mem_span_singleton.2 (dvd_refl _), end lemma exists_inter (n : ℕ) (h0 : n ≠ 0) (p : R) (hp : prime p) (Hn : Inf (set.range (ord R M)) = ideal.span {p ^ n}) (a : M) (ha : p ^ (n - 1) • a ≠ 0) (hna : ∃ b : M, b ∉ submodule.span R ({a} : set M)) : ∃ b : M, b ≠ 0 ∧ ∀ (x : M), x ∈ ((submodule.span R {a}) ⊓ (submodule.span R ({b} : set M))) → x = 0 := begin cases hna with c hc, have hn : p ^ n • c = 0 := by {have : p ^ n ∈ Inf (set.range (ord R M)), by rw Hn; exact ideal.mem_span_singleton.2 (dvd_refl _), have huh : Inf (set.range (ord R M)) ≤ ord R M c := Inf_le (show ord R M c ∈ set.range (ord R M), from ⟨c, rfl⟩), exact huh this}, haveI := classical.dec_pred, let j := @nat.find _ (_inst _) (show ∃ n, p ^ n • c ∈ submodule.span R ({a} : set M), from ⟨n, by { rw hn, exact submodule.zero_mem (submodule.span R ({a} : set M))}⟩), have hj0 : j ≠ 0 := λ hj, absurd (show c ∈ submodule.span R {a}, by {rw [←one_smul _ c, ←pow_zero p, ←hj], exact @nat.find_spec _ (_inst _) (show ∃ n, p ^ n • c ∈ submodule.span R ({a} : set M), from ⟨n, by { rw hn, exact submodule.zero_mem (submodule.span R ({a} : set M)), }⟩), }) hc, have hj : p ^ j • c ∈ submodule.span R {a}, from @nat.find_spec _ (_inst _) (show ∃ n, p ^ n • c ∈ submodule.span R ({a} : set M), from ⟨n, by { rw hn, exact submodule.zero_mem (submodule.span R ({a} : set M)), }⟩), cases submodule.mem_span_singleton.1 hj with r₁ hr₁, have hjs : p ^ (j - 1) • c ∉ submodule.span R {a} := @nat.find_min _ (_inst _) (show ∃ n, p ^ n • c ∈ submodule.span R ({a} : set M), from ⟨n, by { rw hn, exact submodule.zero_mem (submodule.span R ({a} : set M)), }⟩) (j - 1) (nat.pred_lt hj0), cases (classical.em (r₁ = 0)), rw h at hr₁, rw zero_smul at hr₁, use p ^ (j - 1) • c, split, intro hpj0, rw hpj0 at hjs, exact hjs (submodule.zero_mem _), intros x hx, cases submodule.mem_span_singleton.1 hx.2 with t ht, rw ← @classical.not_not (x = 0), intro hn, have hpt : ¬ p ∣ t := λ ⟨m, hm⟩, by {rw hm at ht, rw mul_comm at ht, rw ←mul_smul at ht, rw mul_assoc at ht, rw ←pow_succ at ht, rw nat.sub_add_cancel (nat.succ_le_of_lt $ nat.pos_iff_ne_zero.2 hj0) at ht, rw mul_smul at ht, rw ←hr₁ at ht, rw smul_zero at ht, exact hn ht.symm }, have hcop : is_coprime t (p ^ n) := is_coprime.symm (is_coprime.pow_left (is_coprime_of_prime hp hpt)), rcases hcop with ⟨z, w, hwz⟩, have hbeq : p ^ (j - 1) • c = (z * t) • (p ^ (j - 1) • c) + (w * (p ^ n)) • (p ^ (j - 1) • c) := by {rw ←add_smul, rw hwz, rw one_smul}, have hsb : (z * t) • (p ^ (j - 1) • c) ∈ submodule.span R ({a} : set M) := by {rw mul_smul, refine submodule.smul_mem (submodule.span R ({a} : set M)) z _, rw ht, exact hx.1}, cases submodule.mem_span_singleton.1 hsb with y hy, have hjm : p ^ (j - 1) • c ∈ submodule.span R ({a} : set M) := by {rw ←mul_smul (w * _) at hbeq, rw mul_assoc at hbeq, rw ←pow_add at hbeq, cases nat.le.dest (nat.succ_le_of_lt (nat.pos_iff_ne_zero.2 h0)) with l hl, rw add_comm at hl, rw ←hl at hbeq, rw add_assoc at hbeq, rw add_comm 1 at hbeq, rw nat.sub_add_cancel (nat.succ_le_of_lt (nat.pos_iff_ne_zero.2 hj0)) at hbeq, rw pow_add at hbeq, rw mul_smul at hbeq, rw mul_smul at hbeq, rw mul_smul at hbeq, rw ←hr₁ at hbeq, rw smul_zero at hbeq, rw smul_zero at hbeq, rw add_zero at hbeq, rw hbeq, rw ←mul_smul z t, exact hsb }, exact hjs hjm, let k := @nat.find (λ k, ¬ (p ^ (k + 1) ∣ r₁)) (_inst _) (by {use (multiset.filter (λ x, associated x p) (unique_factorization_domain.factors r₁)).card, exact fin_pow_dvd h hp }), have hk : p ^ k ∣ r₁ := by { cases (classical.em (k = 0)), rw h_1, rw pow_zero, exact one_dvd _, apply classical.not_not.1, intro huh, rw ←nat.succ_pred_eq_of_pos (nat.pos_iff_ne_zero.2 h_1) at huh, exact @nat.find_min _ (_inst _) (by {use (multiset.filter (λ x, associated x p) (unique_factorization_domain.factors r₁)).card, exact fin_pow_dvd h hp }) _ (nat.pred_lt h_1) huh}, cases hk with r hr, have hpr : ¬ p ∣ r := λ hpr, by {cases hpr with m hm, rw hm at hr, rw ←mul_assoc at hr, rw mul_comm _ p at hr, rw ←pow_succ at hr, exact @nat.find_spec (λ k, ¬ (p ^ (k + 1) ∣ r₁)) (_inst _) (by {use (multiset.filter (λ x, associated x p) (unique_factorization_domain.factors r₁)).card, exact fin_pow_dvd h hp }) (show p ^ (k + 1) ∣ r₁, from ⟨m, by rw hr⟩)}, have hjn : j ≤ n := @nat.find_min' _ (_inst _) (show ∃ n, p ^ n • c ∈ submodule.span R ({a} : set M), from ⟨n, by { rw hn, exact submodule.zero_mem (submodule.span R ({a} : set M))}⟩) n (hn.symm ▸ (submodule.span R ({a} : set M)).zero_mem), have hnjk : n ≤ n - j + k := by {suffices : (p ^ (n - j + k) * r) • a = 0, by {rw ←not_lt, intro hnot, have hgh : ord R M a = ideal.span ({p ^ n} : set R) := by rw ←nat.sub_add_cancel (nat.succ_le_of_lt (nat.pos_iff_ne_zero.2 h0)) at ⊢ Hn; exact ord_eq_of_pow hp ha (smul_zero_of_Inf _ Hn a), cases ideal.mem_span_singleton.1 (by rw ←hgh; exact this) with w hw, cases nat.le.dest (nat.succ_le_of_lt hnot) with m hm, conv at hw {to_rhs, rw ←hm}, rw nat.succ_eq_add_one at hw, rw add_assoc at hw, rw pow_add p (n - j + k) (1 + m) at hw, rw mul_assoc at hw, have hhh := mul_left_cancel' (ne_zero_of_prime_pow R (n - j + k) hp) hw, exact hpr (by {rw hhh, rw pow_add, rw mul_assoc, rw pow_one, use p ^ m * w, }), }, rw ←nat.sub_add_cancel hjn at hn, rw pow_add at hn, rw mul_smul at hn, rw ←hr₁ at hn, rw hr at hn, rw ←mul_smul at hn, rw ←mul_assoc at hn, rw ←pow_add at hn, exact hn}, have hjk : j ≤ k := by {rw ←nat.sub_le_sub_left_iff hjn, apply nat.sub_le_left_of_le_add, rw add_comm, exact hnjk }, have h1j : 1 ≤ j := nat.succ_le_of_lt (nat.pos_iff_ne_zero.2 hj0), let b := p ^ (j - 1) • c - (r * p ^ (k - 1)) • a, have hpb : p • b = 0 := show p • (_ - _) = (0 : M), by {rw smul_sub, rw ←mul_smul, rw ←pow_succ, rw ←mul_smul, rw mul_comm r, rw ←mul_assoc, rw ←pow_succ, rw nat.sub_add_cancel h1j, rw nat.sub_add_cancel (le_trans h1j hjk), rw ←hr₁, rw hr, rw sub_self }, use b, split, show _ - _ ≠ (0 : M), intro hb, rw sub_eq_zero at hb, apply hjs, rw hb, exact submodule.mem_span_singleton.2 ⟨r * p ^ (k - 1), rfl⟩, intros x hx, rw ← @classical.not_not (x = 0), intro hn, cases submodule.mem_span_singleton.1 hx.2 with s hs, have hps : ¬ p ∣ s := λ ⟨q, hq⟩, by {rw hq at hs, rw mul_comm at hs, rw mul_smul at hs, rw hpb at hs, rw smul_zero at hs, exact hn hs.symm}, have hcop : is_coprime s (p ^ n) := is_coprime.symm (is_coprime.pow_left (is_coprime_of_prime hp hps)), rcases hcop with ⟨z, w, hwz⟩, have hbeq : b = (z * s) • b + (w * (p ^ n)) • b := by {rw ←add_smul, rw hwz, rw one_smul}, have hsb : (z * s) • b ∈ submodule.span R ({a} : set M) := by {rw mul_smul, refine submodule.smul_mem (submodule.span R ({a} : set M)) z _, rw hs, exact hx.1}, have hjm : p ^ (j - 1) • c ∈ submodule.span R ({a} : set M) := by {cases nat.le.dest (le_trans h1j hjn) with l hl, rw add_comm at hl, rw ←hl at hbeq, rw mul_smul at hbeq, rw pow_add at hbeq, rw pow_one at hbeq, rw mul_smul at hbeq, rw mul_smul at hbeq, rw hpb at hbeq, rw smul_zero at hbeq, rw smul_zero at hbeq, rw add_zero at hbeq, rw ←mul_smul at hbeq, rw ←hbeq at hsb, change _ - _ ∈ _ at hsb, rw sub_eq_add_neg at hsb, rw ←neg_smul at hsb, exact (submodule.add_mem_iff_left _ (submodule.mem_span_singleton.2 ⟨-(r * p ^ (k - 1)), rfl⟩)).1 hsb, }, exact hjs hjm, end lemma span_quotient_iff (a : M) : A ⊔ submodule.span R {a} = ⊤ ↔ submodule.span R ({submodule.quotient.mk a} : set A.quotient) = ⊤ := begin split, intro h, rw eq_top_iff, intros x hx, apply quotient.induction_on' x, intro y, rcases submodule.mem_sup.1 (show y ∈ A ⊔ submodule.span R ({a} : set M), by rw h; exact submodule.mem_top) with ⟨b, hb, c, hc, hbc⟩, cases submodule.mem_span_singleton.1 hc with d hd, rw ←hd at hbc, apply submodule.mem_span_singleton.2, use d, rw ←hbc, apply (submodule.quotient.eq _).2, convert (submodule.neg_mem _ hb), abel, intro h, rw eq_top_iff, intros x hx, apply submodule.mem_sup.2, cases submodule.mem_span_singleton.1 (show submodule.quotient.mk x ∈ submodule.span R ({submodule.quotient.mk a} : set A.quotient), by rw h; exact submodule.mem_top) with y hy, rw ←submodule.quotient.mk_smul at hy, have huh := (submodule.quotient.eq _).1 hy, use (x - y • a), split, convert A.neg_mem huh, abel, use y • a, split, exact submodule.mem_span_singleton.2 ⟨y, rfl⟩, rw sub_add_cancel, end lemma exists_compl (Hfg : A.fg) (n : ℕ) (h0 : n ≠ 0) (p : R) (hp : prime p) (Hn : Inf (set.range (ord R A)) = ideal.span {p ^ n}) (a : A) (ha : p ^ (n - 1) • a ≠ 0) (hna : ∃ b : A, b ∉ submodule.span R ({a} : set A)) : ∃ C : submodule R A, C ⊓ submodule.span R ({a} : set A) = ⊥ ∧ C ⊔ submodule.span R ({a} : set A) = ⊤ := begin cases (classical.em (submodule.span R ({a} : set A) = ⊤)), use ⊥, split, simp, rw h, simp, let S := { B : submodule R A | submodule.span R ({a} : set A) ⊓ B = ⊥ }, have hS : set.nonempty S := by {cases exists_inter _ n h0 p hp Hn a ha hna with b hb, use submodule.span R ({b} : set A), apply eq_bot_iff.2, intros x hx, apply (submodule.mem_bot R).2, exact hb.2 x hx}, let C := @well_founded.min (submodule R A) (>) (is_noetherian_iff_well_founded.1 $ is_noetherian_of_fg_of_noetherian A Hfg) S hS, have hAC : ∀ x : C.quotient, p ^ n • x = 0 := λ x, by {apply quotient.induction_on' x, intros y, erw ←submodule.quotient.mk_smul, rw smul_zero_of_Inf _ Hn, rw submodule.quotient.mk_zero }, have haC : p ^ n • (@submodule.quotient.mk _ _ _ _ _ C a) = 0 := hAC _, have hC : submodule.span R ({a} : set A) ⊓ C = ⊥ := well_founded.min_mem (is_noetherian_iff_well_founded.1 $ is_noetherian_of_fg_of_noetherian A Hfg) S hS, have hanC : p ^ (n - 1) • (@submodule.quotient.mk _ _ _ _ _ C a) ≠ 0 :=λ ha0, by {rw ←submodule.quotient.mk_smul at ha0, rw submodule.quotient.mk_eq_zero at ha0, apply ha,rw ←submodule.mem_bot R, rw ←hC, exact ⟨submodule.mem_span_singleton.2 ⟨p ^ (n - 1), rfl⟩, ha0⟩, }, have hACn : Inf (set.range (ord R C.quotient)) = ideal.span {p ^ n} := by { apply le_antisymm, apply Inf_le _, use (submodule.quotient.mk a), rw ←nat.sub_add_cancel (nat.succ_le_of_lt $ nat.pos_iff_ne_zero.2 h0) at haC ⊢, exact ord_eq_of_pow hp hanC haC, apply le_Inf _, intros b hb, cases hb with c hc, revert hc, apply quotient.induction_on' c, intros d hd, rw ←hd, intros r hr, cases ideal.mem_span_singleton.1 hr with s hs, rw hs, show _ • _ = _, rw mul_smul, exact hAC _,}, use C, split, rw inf_comm, exact hC, rw span_quotient_iff, apply classical.not_not.1, intro HN, cases @exists_inter _ _ _ _ _ C.quotient _ _ n h0 p hp hACn (submodule.quotient.mk a) hanC (by {rcases submodule.exists_of_lt (lt_top_iff_ne_top.2 HN) with ⟨x, _, hx⟩, use x}) with b hb, revert hb, apply @quotient.induction_on _ C.quotient_rel _ b, intros d hd, have hda : submodule.span R {a} ⊓ (submodule.span R {d} ⊔ C) = ⊥ := by {rw eq_bot_iff, intros x hx, apply (submodule.mem_bot R).2, rcases submodule.mem_sup.1 hx.2 with ⟨y, hy, z, hz, hyz⟩, have hyx : submodule.quotient.mk x = submodule.quotient.mk y := (submodule.quotient.eq C).2 (by {rw add_comm at hyz, rw ←eq_sub_iff_add_eq at hyz, rw ←hyz, exact hz}), cases submodule.mem_span_singleton.1 hx.1 with k hk, cases submodule.mem_span_singleton.1 hy with j hj, have hd' := hd.2 (submodule.quotient.mk x) ⟨submodule.mem_span_singleton.2 ⟨k, by {rw ←submodule.quotient.mk_smul, rw hk,}⟩, submodule.mem_span_singleton.2 ⟨j, by {rw hyx, erw ←submodule.quotient.mk_smul, rw hj}⟩⟩, apply (submodule.mem_bot R).1, rw ←hC, exact ⟨hx.1, (submodule.quotient.mk_eq_zero _).1 hd'⟩, }, have : ∀ B, B ∈ S → ¬ C < B := λ B, well_founded.not_lt_min (is_noetherian_iff_well_founded.1 $ is_noetherian_of_fg_of_noetherian A Hfg) S hS, refine this (submodule.span R {d} ⊔ C) hda _, rw submodule.lt_iff_le_and_exists, split, exact le_sup_right, use d, split, exact submodule.le_def.1 le_sup_left (submodule.subset_span $ set.mem_singleton d), intro hdC, rw ←submodule.quotient.mk_eq_zero at hdC, exact hd.1 hdC, end lemma Inf_eq (A : submodule R M) (s : finset M) (hs : submodule.span R (↑s : set _) = A) (p : R) (hp : prime p) (Hp : ∀ (a : M), a ∈ A ∧ a ≠ 0 → (∃! (n : ℕ), p ^ (n + 1) • a = 0 ∧ p ^ n • a ≠ 0)) (X : M) (N : ℕ) (hN : X ∈ finset.erase s 0 ∧ (p ^ (N + 1) • X = 0 ∧ ¬p ^ N • X = 0) ∧ ∀ (b : M) (m : ℕ), b ∈ finset.erase s 0 ∧ p ^ (m + 1) • b = 0 ∧ ¬p ^ m • b = 0 → m ≤ N) : Inf (set.range (ord R A)) = ideal.span {p ^ (N + 1)} := begin have hmem : ∀ x ∈ s, x ∈ A := λ x H, hs ▸ (submodule.subset_span H), apply le_antisymm, apply Inf_le _, use ⟨X, hmem X $ finset.mem_of_mem_erase hN.1⟩, have hX : A.subtype ⟨X, hmem X $ finset.mem_of_mem_erase hN.1⟩ = X := rfl, exact ord_eq_of_pow hp (λ h, hN.2.1.2 $ by {rw ←hX, rw ←linear_map.map_smul, rw h, rw linear_map.map_zero }) (by { have h2 : p ^ (N + 1) • X = 0 := hN.2.1.1, rw ←hX at h2, rw ←linear_map.map_smul at h2, exact linear_map.ker_eq_bot'.1 A.ker_subtype _ h2, }) , apply le_Inf _, intros c hc, cases hc with x hx, cases classical.em (x = 0), rw h at hx, rw ord_ideal_zero_eq_top at hx, rw ←hx, exact le_top, rw ←hx, intros y hy, cases ideal.mem_span_singleton.1 hy with r hr, cases Hp x ⟨x.2, λ h0, h $ subtype.ext_iff.2 $ h0⟩ with n hn, rcases (finsupp.mem_span_iff_total _).1 (show (x : M) ∈ submodule.span R (id '' (↑s : set _)), by rw set.image_id; rw hs; exact x.2) with ⟨l, hlm, hl⟩, rw hr, show _ = (0 : A), apply subtype.ext_iff.2, rw submodule.coe_smul, rw mul_comm, rw mul_smul, rw submodule.coe_zero, rw ←hl, rw finsupp.total_apply, rw finsupp.smul_sum, have hNs : ∀ x, x ∈ (↑s : set _) → p ^ (N + 1) • x = (0 : M) := λ z hz, by {cases classical.em (z = 0), rw h_1, rw smul_zero, cases Hp z ⟨hmem z $ finset.mem_coe.1 hz, h_1⟩ with m hm, cases nat.le.dest (hN.2.2 z m ⟨finset.mem_erase.2 ⟨h_1, hz⟩, hm.1⟩) with k hk, rw ←hk, rw add_comm m k, rw add_assoc,rw pow_add, rw mul_smul, rw hm.1.1, rw smul_zero}, unfold finsupp.sum, convert smul_zero _, rw ←@finset.sum_const_zero M _ l.support _, apply finset.sum_congr rfl, intros z hz, rw smul_comm, convert smul_zero _, exact hNs z ((finsupp.mem_supported _ l).1 hlm hz), end lemma inf_aux {X : M} (hX : X ∈ A) {C : submodule R A} (hC : C ⊓ submodule.span R {⟨X, hX⟩} = ⊥ ∧ C ⊔ submodule.span R {⟨X, hX⟩} = ⊤) {S : finset M} (hS : submodule.span R (↑S : set M) = submodule.map A.subtype C ∧ ∀ (a : M), a ∈ S → submodule.span R {a} ⊓ submodule.span R (↑(S.erase a) : set M) = ⊥) : submodule.span R {X} ⊓ submodule.span R (↑S : set M) ≤ ⊥ := begin have := map_inf' C X hX, rw ←hS.1 at this,rw this, rw hC.1, rw submodule.map_bot, exact le_refl _, end lemma inf_aux' {X : M} (hX : X ∈ A) (hX0 : X ≠ 0) {C : submodule R A} (hC : C ⊓ submodule.span R {⟨X, hX⟩} = ⊥ ∧ C ⊔ submodule.span R {⟨X, hX⟩} = ⊤) {S : finset M} (hS : submodule.span R (↑S : set _) = submodule.map A.subtype C ∧ ∀ (a : M), a ∈ S → submodule.span R {a} ⊓ submodule.span R (↑(S.erase a) : set M) = ⊥) {b : M} (hb : b ∈ S) : submodule.span R ({b} : set M) ⊓ submodule.span R (↑((insert X S).erase b : finset M) : set M) ≤ ⊥ := begin have H := inf_aux _ _ hX hC hS, have := hS.2 b hb, rw erase_insert_eq, intros z hz, rw insert_to_set at hz, rcases submodule.mem_span_insert.1 hz.2 with ⟨r, v, hvm, hv⟩, cases submodule.mem_span_singleton.1 hz.1 with c hc, have H := inf_aux _ _ hX hC hS, rw ←hc at hv, rw ←sub_eq_iff_eq_add at hv, have h0 : r • X = 0 := by {rw ←submodule.mem_bot R, apply H, split, exact submodule.mem_span_singleton.2 ⟨r, rfl⟩, rw ←hv, rw submodule.mem_coe, refine submodule.sub_mem _ _ _, apply submodule.span_mono (show {b} ⊆ S, from finset.singleton_subset_iff.2 hb), show c • b ∈ submodule.span R (↑({b} : finset M) : set M), rw finset.coe_singleton, exact submodule.mem_span_singleton.2 ⟨c, rfl⟩, exact submodule.span_mono (show S.erase b ⊆ S, from finset.erase_subset _ _) hvm,}, rw h0 at hv, rw sub_eq_zero at hv, rw ←this, split, rw ←hc, exact submodule.mem_span_singleton.2 ⟨c, rfl⟩, rw ←hc, rw hv, exact hvm, exact hb, intro hXb, have huh := inf_of_le_left (@submodule.span_mono R _ _ _ _ _ _ (show {X} ⊆ S, by rw hXb; exact finset.singleton_subset_iff.2 hb)), change (submodule.span R (↑({X} : finset M) : set M) ⊓ submodule.span R (↑S : set M) = submodule.span R (↑({X} : finset M) : set M)) at huh, rw finset.coe_singleton at huh, rw huh at H, rw ←eq_bot_iff at H, erw submodule.span_singleton_eq_bot at H, exact hX0 H, end theorem gen_le (s : finset A) (hs : submodule.span R (↑s : set A) = ⊤) (x : A) (hx : x ∈ s) (h0 : x ≠ 0) (C : submodule R A) (h : is_compl C (submodule.span R {x})) : C = submodule.span R ((C.subtype.comp (C.linear_proj_of_is_compl (submodule.span R {x}) h) : A → A)'' (↑(s.erase x) : set A)) := begin apply le_antisymm, intros y hy, have : (⟨y, hy⟩ : C) ∈ (C.linear_proj_of_is_compl _ h).range := by rw submodule.linear_proj_of_is_compl_range h; exact submodule.mem_top, rcases this with ⟨a, hma, ha⟩, have hsa : a ∈ submodule.span R (↑s : set _) := by rw hs; exact submodule.mem_top, rw ←set.image_id (↑s : set _) at hsa, rcases (finsupp.mem_span_iff_total R ).1 hsa with ⟨l, hlm, hl⟩, rw ←hl at ha, rw linear_map.map_finsupp_total at ha, rw finsupp.total_apply at ha, cases classical.em (x ∈ l.support) with hxl hxl, unfold finsupp.sum at ha, rw ←finset.insert_erase hxl at ha, rw finset.sum_insert (finset.not_mem_erase x l.support) at ha, dsimp at ha, rw linear_map.mem_ker.1 (show x ∈ (C.linear_proj_of_is_compl _ h).ker, by {rw submodule.linear_proj_of_is_compl_ker h, exact submodule.subset_span rfl}) at ha, rw smul_zero at ha, rw zero_add at ha, have huh : (⟨y, hy⟩ : C) ∈ submodule.span R ((C.linear_proj_of_is_compl (submodule.span R {x}) h) '' (↑(s.erase x) : _)) := by {rw finsupp.mem_span_iff_total, use l.erase x, split, rw finsupp.mem_supported, rw finsupp.support_erase, convert finset.coe_subset.2 (finset.erase_subset_erase x hlm), rw finsupp.total_apply, rw ← ha, unfold finsupp.sum, rw finsupp.support_erase, refine finset.sum_congr (by {convert (eq.refl (l.support.erase x)), }) _,intros z hz, rw finsupp.erase_ne (finset.ne_of_mem_erase hz) }, rw submodule.span_image at ⊢ huh, rcases huh with ⟨z, hzm, hz⟩, use z, split, exact hzm, rw subtype.ext_iff at hz, exact hz, unfold finsupp.sum at ha, rw submodule.span_image, rw submodule.map_comp, use ⟨y, hy⟩, split, rw ←submodule.span_image, apply (finsupp.mem_span_iff_total R).2, use l, split, intros b hb, apply finset.mem_erase.2, split, intro hbx, rw hbx at hb, exact hxl hb, exact hlm hb, rw finsupp.total_apply, exact ha, refl, intros y hy, rw submodule.span_image at hy, rcases hy with ⟨z, hzm, hz⟩, rw ←set.image_id (↑(s.erase x) : set A) at hzm, rcases (finsupp.mem_span_iff_total R).1 hzm with ⟨l, hlm, hl⟩, rw ←hl at hz, rw linear_map.map_finsupp_total at hz, rw finsupp.total_apply at hz, rw ←hz, apply submodule.sum_mem, intros c hc, apply submodule.smul_mem, simp only [submodule.subtype_apply, function.comp.right_id, submodule.coe_mem, linear_map.comp_apply], end variables {M} {R} noncomputable def map_erase {C : submodule R A} {s : finset M} {X : M} (h : X ∈ s) (hs : submodule.span R (↑s : set M) = A) (hc : is_compl C (submodule.span R {⟨X, subset_span' hs h⟩})) := finset.image (A.subtype.comp (C.subtype.comp (C.linear_proj_of_is_compl (submodule.span R {⟨X, subset_span' hs h⟩}) hc))) ((subtype_mk' s (A : set M) $ (subset_span' hs)).erase ⟨X, subset_span' hs h⟩) lemma card_map_erase {C : submodule R A} {s : finset M} {X : M} (h : X ∈ s) (hs : submodule.span R (↑s : set M) = A) (hc : is_compl C (submodule.span R {⟨X, subset_span' hs h⟩})) : finset.card (map_erase _ h hs hc) ≤ (s.erase X).card := begin have H : finset.card (map_erase _ h hs hc) ≤ s.card.pred := by {have : (map_erase _ h hs hc).card ≤ ((subtype_mk' s ↑A (subset_span' hs)).erase ⟨X, subset_span' hs h⟩).card := finset.card_image_le, have h' : (subtype_mk' s ↑A (subset_span' hs)).card = s.card := by {unfold subtype_mk', rw univ_card s, refine finset.card_image_of_injective _ _, intros x y hxy, simp only [subtype.mk_eq_mk] at hxy, exact subtype.ext_iff.2 hxy}, rw ←h', have := finset.card_erase_of_mem (show (⟨X, subset_span' hs h⟩ : A) ∈ subtype_mk' s ↑A (subset_span' hs), from (mem_subtype_mk' (subset_span' hs)).2 $ by {rw subtype.coe_mk, exact h}), rw ←this, exact finset.card_image_le}, apply le_trans H, rw finset.card_erase_of_mem h, end lemma gen_le2 {C : submodule R A} {s : finset M} {X : M} (h : X ∈ s) (h0 : X ≠ 0) (hs : submodule.span R (↑s : set M) = A) (hc : is_compl C (submodule.span R {⟨X, subset_span' hs h⟩})) : C.map A.subtype = submodule.span R (↑(map_erase _ h hs hc) : set M) := begin have := gen_le M A (subtype_mk' s (A : set M) (subset_span' hs)) (span_subtype hs) ⟨X, subset_span' hs h⟩ ((mem_subtype_mk' (subset_span' hs)).2 h) (λ hn0, h0 $ subtype.ext_iff.1 hn0) C hc, unfold map_erase, rw finset.coe_image, rw submodule.span_image, rw submodule.span_image at this, rw submodule.map_comp, exact congr_arg (submodule.map A.subtype) this, end lemma woohoo (n : ℕ) (s : finset M) (hs : submodule.span R (↑s : set M) = A) (hn : s.card ≤ n) : (∃ (p : R), prime p ∧ ∀ a : M, (a ∈ A ∧ a ≠ 0) → ∃ (n : ℕ), p ^ (n + 1) • a = 0 ∧ p ^ n • a ≠ 0) → ∃ (S : finset M), submodule.span R (↑S : set _) = A ∧ ∀ a ∈ S, submodule.span R {a} ⊓ submodule.span R (↑(S.erase a) : set M) = ⊥ := begin revert A s hs hn, induction n with m Hm, intros A s hs hn H, rw finset.card_eq_zero.1 (nat.le_zero_iff.1 hn) at hs, cases H with p hp, use ∅, split, exact hs, intros a ha, exfalso, exact finset.not_mem_empty _ ha, intros A s hs hm htors, cases htors with p hp, have Hp : ∀ a : M, (a ∈ A ∧ a ≠ 0) → ∃! (n : ℕ), p ^ (n + 1) • a = 0 ∧ p ^ n • a ≠ 0 := λ a ha, exists_unique_of_exists_of_unique (hp.2 a ha) (λ y z hy hz, by {rw ←(@classical.not_not (y = z)), intro hnot, wlog hyz : y < z, exact lt_or_gt_of_ne hnot, cases nat.le.dest (nat.succ_le_of_lt hyz) with k hk, apply hz.2, rw ←hk, rw add_comm, rw pow_add, rw mul_smul, rw hy.1, rw smul_zero, }), have hmem : ∀ x ∈ s, x ∈ A := λ x H, hs ▸ (submodule.subset_span H), cases classical.em (m = 0), use s, split, exact hs, intros a ha, rw h at hm, have h01 : s.card = 0 ∨ s.card = 1 := by {revert hm, omega}, cases h01, rw finset.card_eq_zero.1 h01, simp only [finset.coe_empty, submodule.span_empty, finset.erase_empty, inf_bot_eq], cases finset.card_eq_one.1 h01 with b hb, rw hb at ha ⊢, have hab : a = b := finset.mem_singleton.1 ha, rw hab, rw singleton_erase, erw submodule.span_empty, rw inf_bot_eq, cases (classical.em (s.card ≤ m)) with hsm hsm, cases Hm A s hs hsm ⟨p, hp⟩ with S hS, use S, exact hS, replace hsm : s.card = m.succ := by omega, have hn0 : (s.erase 0).nonempty := by {cases classical.em ((0 : M) ∈ s) with hs0 hs0, have hcard := finset.card_erase_of_mem hs0, rw hsm at hcard, rw nat.pred_succ at hcard, exact finset.card_pos.1 (by {rw hcard, exact nat.pos_iff_ne_zero.2 h}), have heq := finset.erase_eq_of_not_mem hs0, exact finset.card_pos.1 (by {rw heq, rw hsm, exact nat.succ_pos _}) }, rcases exists_max hn0 (λ a ha, Hp a ⟨hmem a $ finset.mem_of_mem_erase ha, finset.ne_of_mem_erase ha⟩) with ⟨X, N, hN⟩, dsimp at hN, have hX0 : (⟨X, hmem X $ finset.mem_of_mem_erase hN.1⟩ : A) ≠ 0 := λ hX0, finset.ne_of_mem_erase hN.1 $ subtype.ext_iff.1 hX0, have hX : A.subtype ⟨X, hmem X $ finset.mem_of_mem_erase hN.1⟩ = X := rfl, cases classical.em ((0 : M) ∈ s), have he0 : submodule.span R (↑(s.erase 0) : set M) = submodule.span R (↑s : set _) := by {conv {to_rhs, rw ←finset.insert_erase h_1}, rw insert_to_set, rw span_insert_zero_eq, }, exact Hm A (s.erase 0) (he0.symm ▸ hs) (by {rw finset.card_erase_of_mem h_1, rw hsm, rw nat.pred_succ}) ⟨p, hp⟩, cases classical.em (∃ b, b ∉ submodule.span R ({⟨X, hmem X $ finset.mem_of_mem_erase hN.1⟩} : set A)) with hmA hmA, cases exists_compl M A ⟨s, hs⟩ (N + 1) (nat.succ_ne_zero N) p hp.1 (Inf_eq _ A s hs p hp.1 Hp X N hN) ⟨X, hmem X $ finset.mem_of_mem_erase hN.1⟩ (by rw nat.add_sub_cancel at *; exact (λ h, hN.2.1.2 $ by {rw ←hX, rw ←linear_map.map_smul, rw h, rw linear_map.map_zero })) hmA with C hC, have hXs : (s.erase X).card = m := by {rw finset.card_erase_of_mem (finset.erase_subset 0 s hN.1), rw hsm, rw nat.pred_succ}, cases Hm (C.map A.subtype) (map_erase A (finset.erase_subset 0 s hN.1) hs ⟨eq_bot_iff.1 hC.1, eq_top_iff.1 hC.2⟩) (gen_le2 A (finset.erase_subset 0 s hN.1) (finset.ne_of_mem_erase hN.1) hs ⟨eq_bot_iff.1 hC.1, eq_top_iff.1 hC.2⟩).symm (by rw ←hXs; exact card_map_erase A (finset.erase_subset 0 s hN.1) hs ⟨eq_bot_iff.1 hC.1, eq_top_iff.1 hC.2⟩) (⟨p, ⟨hp.1, λ a ha, by {rcases ha.1 with ⟨b, hmb, hb⟩, apply hp.2, split, rw ←hb, exact b.2, exact ha.2}⟩⟩) with S hS, use insert X S, split, rw insert_to_set, rw span_insert', rw hS.1, rw sup_comm, rw map_sup' _ _ (hmem X $ finset.mem_of_mem_erase hN.1), rw hC.2, exact submodule.map_subtype_top _, intros b hb, rw finset.mem_insert at hb, cases hb, rw hb, rw eq_bot_iff, refine le_trans _ (inf_aux _ _ (hmem X $ finset.mem_of_mem_erase hN.1) hC hS), exact (@inf_le_inf_left (submodule R M) _ _ _ _ (submodule.span_mono $ show (↑((insert X S).erase X : finset M) : set M) ⊆ (↑S : set _), from finset.erase_insert_subset X S)), rw eq_bot_iff, exact inf_aux' _ _ (hmem X $ finset.mem_of_mem_erase hN.1) (finset.mem_erase.1 hN.1).1 hC hS hb, use {X}, split, apply le_antisymm, exact submodule.span_le.2 (by {rw finset.coe_singleton, exact set.singleton_subset_iff.2 (hmem X $ finset.mem_of_mem_erase hN.1)}), intros Y hY, rw ←@classical.not_not (Y ∈ submodule.span R (↑{X} : set M)), intro hnot, rw finset.coe_singleton at *, exact hmA ⟨⟨Y, hY⟩, λ hmnot, hnot $ (map_singleton (hmem X $ finset.mem_of_mem_erase hN.1) hY).2 hmnot⟩, intros a ha, erw finset.mem_singleton at ha, rw ha, erw singleton_erase, show _ ⊓ submodule.span R ∅ = _, rw submodule.span_empty, rw inf_bot_eq, end instance quotient_module (I : ideal R) : module R I.quotient := submodule.quotient.semimodule I variables (R) {M} lemma ord_eq_ker (a : M) : ord R M a = (linear_map.id.smul_right a).ker := begin ext, rw linear_map.mem_ker, refl, end variables {R} def quotient_congr {A B : submodule R M} (H : A = B) : linear_equiv R A.quotient B.quotient := (@quotient.congr_right _ A.quotient_rel B.quotient_rel $ λ x y : M, H ▸ iff.rfl).to_linear_equiv { map_add := λ x y, quotient.induction_on₂' x y $ λ w z, rfl, map_smul := λ x y, quotient.induction_on' y $ λ w, rfl } lemma smul_range {a : M} : (submodule.span R ({a} : set M)) = (linear_map.id.smul_right a).range := begin ext, rw linear_map.mem_range, rw submodule.mem_span_singleton, refl, end def smul_range_equiv {a : M} : linear_equiv R (submodule.span R ({a} : set M)) ((@linear_map.id R R _ _ _).smul_right a).range := (equiv.set_congr $ submodule.ext'_iff.1 smul_range).to_linear_equiv $ { map_add := λ x y, rfl, map_smul := λ c x, rfl } noncomputable def ord_quotient (a : M) : linear_equiv R (ord R M a).quotient (submodule.span R ({a} : set M)) := (quotient_congr $ ord_eq_ker R a).trans $ (linear_map.quot_ker_equiv_range ((@linear_map.id R R _ _ _).smul_right a)).trans smul_range_equiv.symm
817a7e9f9c2446a4757238e279f523b103fd22c0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/ind_parser_bug.lean
25d4634f58a58fc63e1b7e234abab8c941781894
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
331
lean
import logic inductive acc1 (A : Type) (R : A → A → Prop) (a : A) : Prop := intro : ∀ (x : A), (∀ (y : A), R y x → acc1 A R y) → acc1 A R x section variables (A : Type) (R : A → A → Prop) inductive acc2 (a : A) : Prop := intro : ∀ (x : A), (∀ (y : A), R y x → acc2 y) → acc2 x end print "done"
ff6b70a51d83e7a171db802ad40c3031660811a9
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/eq2.lean
f3639b0aa54270300dbc0da3b052c904a407ea2b
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
173
lean
definition symm {A : Type} : Π {a b : A}, a = b → b = a | symm rfl := rfl definition trans {A : Type} : Π {a b c : A}, a = b → b = c → a = c | trans rfl rfl := rfl
72b5a6bc719f1a7c1a0ce7e670149de709b82ad6
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/measure_theory/decomposition/lebesgue.lean
5f0d7e901918446e0b0d7561f8ef186776c14e8e
[ "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
59,935
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.jordan import measure_theory.measure.with_density_vector_measure /-! # Lebesgue decomposition This file proves the Lebesgue decomposition theorem. The Lebesgue decomposition theorem states that, given two σ-finite measures `μ` and `ν`, there exists a finite measure `ξ` and a measurable function `f` such that `μ = ξ + fν` and `ξ` is mutually singular with respect to `ν`. The Lebesgue decomposition provides the Radon-Nikodym theorem readily. ## Main definitions * `measure_theory.measure.have_lebesgue_decomposition` : A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exists a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` * `measure_theory.measure.singular_part` : If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. * `measure_theory.measure.rn_deriv`: If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function. * `measure_theory.signed_measure.have_lebesgue_decomposition` : A signed measure `s` and a measure `μ` is said to `have_lebesgue_decomposition` if both the positive part and negative part of `s` `have_lebesgue_decomposition` with respect to `μ`. * `measure_theory.signed_measure.singular_part` : The singular part between a signed measure `s` and a measure `μ` is simply the singular part of the positive part of `s` with respect to `μ` minus the singular part of the negative part of `s` with respect to `μ`. * `measure_theory.signed_measure.rn_deriv` : The Radon-Nikodym derivative of a signed measure `s` with respect to a measure `μ` is the Radon-Nikodym derivative of the positive part of `s` with respect to `μ` minus the Radon-Nikodym derivative of the negative part of `s` with respect to `μ`. ## Main results * `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite` : the Lebesgue decomposition theorem. * `measure_theory.measure.eq_singular_part` : Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `s = singular_part μ ν`. * `measure_theory.measure.eq_rn_deriv` : Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = rn_deriv μ ν`. * `measure_theory.signed_measure.singular_part_add_with_density_rn_deriv_eq` : the Lebesgue decomposition theorem between a signed measure and a σ-finite positive measure. # Tags Lebesgue decomposition theorem -/ noncomputable theory open_locale classical measure_theory nnreal ennreal variables {α β : Type*} {m : measurable_space α} {μ ν : measure_theory.measure α} include m namespace measure_theory namespace measure /-- A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exists a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`. -/ class have_lebesgue_decomposition (μ ν : measure α) : Prop := (lebesgue_decomposition : ∃ (p : measure α × (α → ℝ≥0∞)), measurable p.2 ∧ p.1 ⊥ₘ ν ∧ μ = p.1 + ν.with_density p.2) /-- If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. -/ @[irreducible] def singular_part (μ ν : measure α) : measure α := if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).1 else 0 /-- If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function. -/ @[irreducible] def rn_deriv (μ ν : measure α) : α → ℝ≥0∞ := if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).2 else 0 lemma have_lebesgue_decomposition_spec (μ ν : measure α) [h : have_lebesgue_decomposition μ ν] : measurable (rn_deriv μ ν) ∧ (singular_part μ ν) ⊥ₘ ν ∧ μ = (singular_part μ ν) + ν.with_density (rn_deriv μ ν) := begin rw [singular_part, rn_deriv, dif_pos h, dif_pos h], exact classical.some_spec h.lebesgue_decomposition, end lemma have_lebesgue_decomposition_add (μ ν : measure α) [have_lebesgue_decomposition μ ν] : μ = (singular_part μ ν) + ν.with_density (rn_deriv μ ν) := (have_lebesgue_decomposition_spec μ ν).2.2 instance have_lebesgue_decomposition_smul (μ ν : measure α) [have_lebesgue_decomposition μ ν] (r : ℝ≥0) : (r • μ).have_lebesgue_decomposition ν := { lebesgue_decomposition := begin obtain ⟨hmeas, hsing, hadd⟩ := have_lebesgue_decomposition_spec μ ν, refine ⟨⟨r • μ.singular_part ν, r • μ.rn_deriv ν⟩, _, hsing.smul _, _⟩, { change measurable ((r : ℝ≥0∞) • _), -- cannot remove this line exact hmeas.const_smul _ }, { change _ = (r : ℝ≥0∞) • _ + ν.with_density ((r : ℝ≥0∞) • _), rw [with_density_smul _ hmeas, ← smul_add, ← hadd], refl } end } @[measurability] lemma measurable_rn_deriv (μ ν : measure α) : measurable $ rn_deriv μ ν := begin by_cases h : have_lebesgue_decomposition μ ν, { exactI (have_lebesgue_decomposition_spec μ ν).1 }, { rw [rn_deriv, dif_neg h], exact measurable_zero } end lemma mutually_singular_singular_part (μ ν : measure α) : singular_part μ ν ⊥ₘ ν := begin by_cases h : have_lebesgue_decomposition μ ν, { exactI (have_lebesgue_decomposition_spec μ ν).2.1 }, { rw [singular_part, dif_neg h], exact mutually_singular.zero.symm } end lemma singular_part_le (μ ν : measure α) : singular_part μ ν ≤ μ := begin by_cases hl : have_lebesgue_decomposition μ ν, { casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h, conv_rhs { rw h }, exact measure.le_add_right (le_refl _) }, { rw [singular_part, dif_neg hl], exact measure.zero_le μ } end lemma with_density_rn_deriv_le (μ ν : measure α) : ν.with_density (rn_deriv μ ν) ≤ μ := begin by_cases hl : have_lebesgue_decomposition μ ν, { casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h, conv_rhs { rw h }, exact measure.le_add_left (le_refl _) }, { rw [rn_deriv, dif_neg hl, with_density_zero], exact measure.zero_le μ } end instance [is_finite_measure μ] : is_finite_measure (singular_part μ ν) := is_finite_measure_of_le μ $ singular_part_le μ ν instance [sigma_finite μ] : sigma_finite (singular_part μ ν) := sigma_finite_of_le μ $ singular_part_le μ ν instance [is_finite_measure μ] : is_finite_measure (ν.with_density $ rn_deriv μ ν) := is_finite_measure_of_le μ $ with_density_rn_deriv_le μ ν instance [sigma_finite μ] : sigma_finite (ν.with_density $ rn_deriv μ ν) := sigma_finite_of_le μ $ with_density_rn_deriv_le μ ν lemma lintegral_rn_deriv_lt_top (μ ν : measure α) [is_finite_measure μ] : ∫⁻ x, μ.rn_deriv ν x ∂ν < ∞ := begin by_cases hl : have_lebesgue_decomposition μ ν, { haveI := hl, obtain ⟨-, -, hadd⟩ := have_lebesgue_decomposition_spec μ ν, rw [← set_lintegral_univ, ← with_density_apply _ measurable_set.univ], refine lt_of_le_of_lt (le_add_left (le_refl _) : _ ≤ μ.singular_part ν set.univ + ν.with_density (μ.rn_deriv ν) set.univ) _, rw [← measure.add_apply, ← hadd], exact measure_lt_top _ _ }, { erw [measure.rn_deriv, dif_neg hl, lintegral_zero], exact with_top.zero_lt_top }, end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `s = singular_part μ ν`. This theorem provides the uniqueness of the `singular_part` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_rn_deriv` provides the uniqueness of the `rn_deriv`. -/ theorem eq_singular_part {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⊥ₘ ν) (hadd : μ = s + ν.with_density f) : s = μ.singular_part ν := begin haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩, obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν, obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩, rw hadd' at hadd, have hνinter : ν (S ∩ T)ᶜ = 0, { rw set.compl_inter, refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _), rw [hT₃, hS₃, add_zero], exact le_refl _ }, have heq : s.restrict (S ∩ T)ᶜ = (μ.singular_part ν).restrict (S ∩ T)ᶜ, { ext1 A hA, have hf : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0, { refine with_density_absolutely_continuous ν _ _, rw ← nonpos_iff_eq_zero, exact hνinter ▸ measure_mono (set.inter_subset_right _ _) }, have hrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0, { refine with_density_absolutely_continuous ν _ _, rw ← nonpos_iff_eq_zero, exact hνinter ▸ measure_mono (set.inter_subset_right _ _) }, rw [restrict_apply hA, restrict_apply hA, ← add_zero (s (A ∩ (S ∩ T)ᶜ)), ← hf, ← add_apply, ← hadd, add_apply, hrn, add_zero] }, have heq' : ∀ A : set α, measurable_set A → s A = s.restrict (S ∩ T)ᶜ A, { intros A hA, have hsinter : s (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hS₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_left _ _)) }, rw [restrict_apply hA, ← add_zero (s (A ∩ (S ∩ T)ᶜ)), ← hsinter, ← measure_union, ← set.inter_union_distrib_left, set.compl_union_self, set.inter_univ], { exact disjoint.inter_left' _ ( disjoint.inter_right' _ disjoint_compl_left) }, { measurability }, { measurability } }, ext1 A hA, have hμinter : μ.singular_part ν (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hT₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_right _ _)) }, rw [heq' A hA, heq, ← add_zero ((μ.singular_part ν).restrict (S ∩ T)ᶜ A), ← hμinter, restrict_apply hA, ← measure_union, ← set.inter_union_distrib_left, set.compl_union_self, set.inter_univ], { exact disjoint.inter_left' _ ( disjoint.inter_right' _ disjoint_compl_left) }, { measurability }, { measurability } end lemma singular_part_zero (ν : measure α) : (0 : measure α).singular_part ν = 0 := begin refine (eq_singular_part measurable_zero mutually_singular.zero.symm _).symm, rw [zero_add, with_density_zero], end lemma singular_part_smul (μ ν : measure α) (r : ℝ≥0) : (r • μ).singular_part ν = r • (μ.singular_part ν) := begin by_cases hr : r = 0, { rw [hr, zero_smul, zero_smul, singular_part_zero] }, by_cases hl : have_lebesgue_decomposition μ ν, { haveI := hl, refine (eq_singular_part ((measurable_rn_deriv μ ν).const_smul (r : ℝ≥0∞)) (mutually_singular.smul r (have_lebesgue_decomposition_spec _ _).2.1) _).symm, rw with_density_smul _ (measurable_rn_deriv _ _), change _ = _ + r • _, rw [← smul_add, ← have_lebesgue_decomposition_add μ ν] }, { rw [singular_part, singular_part, dif_neg hl, dif_neg, smul_zero], refine λ hl', hl _, rw ← inv_smul_smul₀ hr μ, exact @measure.have_lebesgue_decomposition_smul _ _ _ _ hl' _ } end lemma singular_part_add (μ₁ μ₂ ν : measure α) [have_lebesgue_decomposition μ₁ ν] [have_lebesgue_decomposition μ₂ ν] : (μ₁ + μ₂).singular_part ν = μ₁.singular_part ν + μ₂.singular_part ν := begin refine (eq_singular_part ((measurable_rn_deriv μ₁ ν).add (measurable_rn_deriv μ₂ ν)) ((have_lebesgue_decomposition_spec _ _).2.1.add (have_lebesgue_decomposition_spec _ _).2.1) _).symm, erw with_density_add (measurable_rn_deriv μ₁ ν) (measurable_rn_deriv μ₂ ν), conv_rhs { rw [add_assoc, add_comm (μ₂.singular_part ν), ← add_assoc, ← add_assoc] }, rw [← have_lebesgue_decomposition_add μ₁ ν, add_assoc, add_comm (ν.with_density (μ₂.rn_deriv ν)), ← have_lebesgue_decomposition_add μ₂ ν] end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = rn_deriv μ ν`. This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the `singular_part`. -/ theorem eq_rn_deriv {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⊥ₘ ν) (hadd : μ = s + ν.with_density f) : ν.with_density f = ν.with_density (μ.rn_deriv ν) := begin haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩, obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν, obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩, rw hadd' at hadd, have hνinter : ν (S ∩ T)ᶜ = 0, { rw set.compl_inter, refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _), rw [hT₃, hS₃, add_zero], exact le_refl _ }, have heq : (ν.with_density f).restrict (S ∩ T) = (ν.with_density (rn_deriv μ ν)).restrict (S ∩ T), { ext1 A hA, have hs : s (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hS₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_left _ _)) }, have hsing : μ.singular_part ν (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hT₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_right _ _)) }, rw [restrict_apply hA, restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hs, ← add_apply, add_comm, ← hadd, add_apply, hsing, zero_add] }, have heq' : ∀ A : set α, measurable_set A → ν.with_density f A = (ν.with_density f).restrict (S ∩ T) A, { intros A hA, have hνfinter : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0, { rw ← nonpos_iff_eq_zero, exact with_density_absolutely_continuous ν f hνinter ▸ measure_mono (set.inter_subset_right _ _) }, rw [restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hνfinter, ← measure_union, ← set.inter_union_distrib_left, set.union_compl_self, set.inter_univ], { exact disjoint.inter_left' _ (disjoint.inter_right' _ disjoint_compl_right) }, { measurability }, { measurability } }, ext1 A hA, have hνrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0, { rw ← nonpos_iff_eq_zero, exact with_density_absolutely_continuous ν (μ.rn_deriv ν) hνinter ▸ measure_mono (set.inter_subset_right _ _) }, rw [heq' A hA, heq, ← add_zero ((ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T) A), ← hνrn, restrict_apply hA, ← measure_union, ← set.inter_union_distrib_left, set.union_compl_self, set.inter_univ], { exact disjoint.inter_left' _ (disjoint.inter_right' _ disjoint_compl_right) }, { measurability }, { measurability } end open vector_measure signed_measure /-- If two finite measures `μ` and `ν` are not mutually singular, there exists some `ε > 0` and a measurable set `E`, such that `ν(E) > 0` and `E` is positive with respect to `μ - εν`. This lemma is useful for the Lebesgue decomposition theorem. -/ lemma exists_positive_of_not_mutually_singular (μ ν : measure α) [is_finite_measure μ] [is_finite_measure ν] (h : ¬ μ ⊥ₘ ν) : ∃ ε : ℝ≥0, 0 < ε ∧ ∃ E : set α, measurable_set E ∧ 0 < ν E ∧ 0 ≤[E] μ.to_signed_measure - (ε • ν).to_signed_measure := begin -- for all `n : ℕ`, obtain the Hahn decomposition for `μ - (1 / n) ν` have : ∀ n : ℕ, ∃ i : set α, measurable_set i ∧ 0 ≤[i] (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ∧ (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[iᶜ] 0, { intro, exact exists_compl_positive_negative _ }, choose f hf₁ hf₂ hf₃ using this, -- set `A` to be the intersection of all the negative parts of obtained Hahn decompositions -- and we show that `μ A = 0` set A := ⋂ n, (f n)ᶜ with hA₁, have hAmeas : measurable_set A, { exact measurable_set.Inter (λ n, (hf₁ n).compl) }, have hA₂ : ∀ n : ℕ, (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[A] 0, { intro n, exact restrict_le_restrict_subset _ _ (hf₁ n).compl (hf₃ n) (set.Inter_subset _ _) }, have hA₃ : ∀ n : ℕ, μ A ≤ (1 / (n + 1) : ℝ≥0) * ν A, { intro n, have := nonpos_of_restrict_le_zero _ (hA₂ n), rwa [to_signed_measure_sub_apply hAmeas, sub_nonpos, ennreal.to_real_le_to_real] at this, exacts [ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)] }, have hμ : μ A = 0, { lift μ A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with μA, lift ν A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with νA, rw ennreal.coe_eq_zero, by_cases hb : 0 < νA, { suffices : ∀ b, 0 < b → μA ≤ b, { by_contra, have h' := this (μA / 2) (nnreal.half_pos (zero_lt_iff.2 h)), rw ← @not_not (μA ≤ μA / 2) at h', exact h' (not_le.2 (nnreal.half_lt_self h)) }, intros c hc, have : ∃ n : ℕ, 1 / (n + 1 : ℝ) < c * νA⁻¹, refine exists_nat_one_div_lt _, { refine mul_pos hc _, rw _root_.inv_pos, exact hb }, rcases this with ⟨n, hn⟩, have hb₁ : (0 : ℝ) < νA⁻¹, { rw _root_.inv_pos, exact hb }, have h' : 1 / (↑n + 1) * νA < c, { rw [← nnreal.coe_lt_coe, ← mul_lt_mul_right hb₁, nnreal.coe_mul, mul_assoc, ← nnreal.coe_inv, ← nnreal.coe_mul, _root_.mul_inv_cancel, ← nnreal.coe_mul, mul_one, nnreal.coe_inv], { convert hn, simp }, { exact ne.symm (ne_of_lt hb) } }, refine le_trans _ (le_of_lt h'), rw [← ennreal.coe_le_coe, ennreal.coe_mul], exact hA₃ n }, { rw [not_lt, le_zero_iff] at hb, specialize hA₃ 0, simp [hb, le_zero_iff] at hA₃, assumption } }, -- since `μ` and `ν` are not mutually singular, `μ A = 0` implies `ν Aᶜ > 0` rw mutually_singular at h, push_neg at h, have := h _ hAmeas hμ, simp_rw [hA₁, set.compl_Inter, compl_compl] at this, -- as `Aᶜ = ⋃ n, f n`, `ν Aᶜ > 0` implies there exists some `n` such that `ν (f n) > 0` obtain ⟨n, hn⟩ := exists_measure_pos_of_not_measure_Union_null this, -- thus, choosing `f n` as the set `E` suffices exact ⟨1 / (n + 1), by simp, f n, hf₁ n, hn, hf₂ n⟩, end namespace lebesgue_decomposition /-- Given two measures `μ` and `ν`, `measurable_le μ ν` is the set of measurable functions `f`, such that, for all measurable sets `A`, `∫⁻ x in A, f x ∂μ ≤ ν A`. This is useful for the Lebesgue decomposition theorem. -/ def measurable_le (μ ν : measure α) : set (α → ℝ≥0∞) := { f | measurable f ∧ ∀ (A : set α) (hA : measurable_set A), ∫⁻ x in A, f x ∂μ ≤ ν A } lemma zero_mem_measurable_le : (0 : α → ℝ≥0∞) ∈ measurable_le μ ν := ⟨measurable_zero, λ A hA, by simp⟩ lemma max_measurable_le (f g : α → ℝ≥0∞) (hf : f ∈ measurable_le μ ν) (hg : g ∈ measurable_le μ ν) (A : set α) (hA : measurable_set A) : ∫⁻ a in A, max (f a) (g a) ∂μ ≤ ∫⁻ a in A ∩ { a | f a ≤ g a }, g a ∂μ + ∫⁻ a in A ∩ { a | g a < f a }, f a ∂μ := begin rw [← lintegral_indicator _ hA, ← lintegral_indicator f, ← lintegral_indicator g, ← lintegral_add], { refine lintegral_mono (λ a, _), by_cases haA : a ∈ A, { by_cases f a ≤ g a, { simp only, rw [set.indicator_of_mem haA, set.indicator_of_mem, set.indicator_of_not_mem, add_zero], simp only [le_refl, max_le_iff, and_true, h], { rintro ⟨_, hc⟩, exact false.elim ((not_lt.2 h) hc) }, { exact ⟨haA, h⟩ } }, { simp only, rw [set.indicator_of_mem haA, set.indicator_of_mem _ f, set.indicator_of_not_mem, zero_add], simp only [true_and, le_refl, max_le_iff, le_of_lt (not_le.1 h)], { rintro ⟨_, hc⟩, exact false.elim (h hc) }, { exact ⟨haA, not_le.1 h⟩ } } }, { simp [set.indicator_of_not_mem haA] } }, { exact measurable.indicator hg.1 (hA.inter (measurable_set_le hf.1 hg.1)) }, { exact measurable.indicator hf.1 (hA.inter (measurable_set_lt hg.1 hf.1)) }, { exact hA.inter (measurable_set_le hf.1 hg.1) }, { exact hA.inter (measurable_set_lt hg.1 hf.1) }, end lemma sup_mem_measurable_le {f g : α → ℝ≥0∞} (hf : f ∈ measurable_le μ ν) (hg : g ∈ measurable_le μ ν) : (λ a, f a ⊔ g a) ∈ measurable_le μ ν := begin simp_rw ennreal.sup_eq_max, refine ⟨measurable.max hf.1 hg.1, λ A hA, _⟩, have h₁ := hA.inter (measurable_set_le hf.1 hg.1), have h₂ := hA.inter (measurable_set_lt hg.1 hf.1), refine le_trans (max_measurable_le f g hf hg A hA) _, refine le_trans (add_le_add (hg.2 _ h₁) (hf.2 _ h₂)) _, { rw [← measure_union _ h₁ h₂], { refine le_of_eq _, congr, convert set.inter_union_compl A _, ext a, simpa }, rintro x ⟨⟨-, hx₁⟩, -, hx₂⟩, exact (not_le.2 hx₂) hx₁ } end lemma supr_succ_eq_sup {α} (f : ℕ → α → ℝ≥0∞) (m : ℕ) (a : α) : (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a := begin ext x, simp only [option.mem_def, ennreal.some_eq_coe], split; intro h; rw ← h, symmetry, all_goals { set c := (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) with hc, set d := (f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a) with hd, suffices : c ≤ d ∧ d ≤ c, { change c = d, -- removing this line breaks exact le_antisymm this.1 this.2 }, rw [hc, hd], refine ⟨_, _⟩, { refine bsupr_le (λ n hn, _), rcases nat.of_le_succ hn with (h | h), { exact le_sup_of_le_right (le_bsupr n h) }, { exact h ▸ le_sup_left } }, { refine sup_le _ _, { convert @le_bsupr _ _ _ (λ i, i ≤ m + 1) _ m.succ (le_refl _), refl }, { refine bsupr_le (λ n hn, _), have := (le_trans hn (nat.le_succ m)), -- replacing `this` below with the proof breaks exact (le_bsupr n this) } } }, end lemma supr_mem_measurable_le (f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) : (λ x, ⨆ k (hk : k ≤ n), f k x) ∈ measurable_le μ ν := begin induction n with m hm, { refine ⟨_, _⟩, { simp [(hf 0).1] }, { intros A hA, simp [(hf 0).2 A hA] } }, { have : (λ (a : α), ⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = (λ a, f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a), { exact funext (λ _, supr_succ_eq_sup _ _ _) }, refine ⟨measurable_supr (λ n, measurable.supr_Prop _ (hf n).1), λ A hA, _⟩, rw this, exact (sup_mem_measurable_le (hf m.succ) hm).2 A hA } end lemma supr_mem_measurable_le' (f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) : (⨆ k (hk : k ≤ n), f k) ∈ measurable_le μ ν := begin convert supr_mem_measurable_le f hf n, ext, simp end section supr_lemmas --TODO: these statements should be moved elsewhere omit m lemma supr_monotone {α : Type*} (f : ℕ → α → ℝ≥0∞) : monotone (λ n x, ⨆ k (hk : k ≤ n), f k x) := begin intros n m hnm x, simp only, refine bsupr_le (λ k hk, _), have : k ≤ m := le_trans hk hnm, -- replacing `this` below with the proof breaks exact le_bsupr k this, end lemma supr_monotone' {α : Type*} (f : ℕ → α → ℝ≥0∞) (x : α) : monotone (λ n, ⨆ k (hk : k ≤ n), f k x) := λ n m hnm, supr_monotone f hnm x lemma supr_le_le {α : Type*} (f : ℕ → α → ℝ≥0∞) (n k : ℕ) (hk : k ≤ n) : f k ≤ λ x, ⨆ k (hk : k ≤ n), f k x := λ x, le_bsupr k hk end supr_lemmas /-- `measurable_le_eval μ ν` is the set of `∫⁻ x, f x ∂μ` for all `f ∈ measurable_le μ ν`. -/ def measurable_le_eval (μ ν : measure α) : set ℝ≥0∞ := (λ f : α → ℝ≥0∞, ∫⁻ x, f x ∂μ) '' measurable_le μ ν end lebesgue_decomposition open lebesgue_decomposition /-- Any pair of finite measures `μ` and `ν`, `have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`. This is not an instance since this is also shown for the more general σ-finite measures with `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite`. -/ theorem have_lebesgue_decomposition_of_finite_measure [is_finite_measure μ] [is_finite_measure ν] : have_lebesgue_decomposition μ ν := ⟨begin have h := @exists_seq_tendsto_Sup _ _ _ _ _ (measurable_le_eval ν μ) ⟨0, 0, zero_mem_measurable_le, by simp⟩ (order_top.bdd_above _), choose g hmono hg₂ f hf₁ hf₂ using h, -- we set `ξ` to be the supremum of an increasing sequence of functions obtained from above set ξ := ⨆ n k (hk : k ≤ n), f k with hξ, -- we see that `ξ` has the largest integral among all functions in `measurable_le` have hξ₁ : Sup (measurable_le_eval ν μ) = ∫⁻ a, ξ a ∂ν, { have := @lintegral_tendsto_of_tendsto_of_monotone _ _ ν (λ n, ⨆ k (hk : k ≤ n), f k) (⨆ n k (hk : k ≤ n), f k) _ _ _, { refine tendsto_nhds_unique _ this, refine tendsto_of_tendsto_of_tendsto_of_le_of_le hg₂ tendsto_const_nhds _ _, { intro n, rw ← hf₂ n, apply lintegral_mono, simp only [supr_apply, supr_le_le f n n (le_refl _)] }, { intro n, exact le_Sup ⟨⨆ (k : ℕ) (hk : k ≤ n), f k, supr_mem_measurable_le' _ hf₁ _, rfl⟩ } }, { intro n, refine measurable.ae_measurable _, convert (supr_mem_measurable_le _ hf₁ n).1, ext, simp }, { refine filter.eventually_of_forall (λ a, _), simp [supr_monotone' f _] }, { refine filter.eventually_of_forall (λ a, _), simp [tendsto_at_top_supr (supr_monotone' f a)] } }, have hξm : measurable ξ, { convert measurable_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1), ext, simp [hξ] }, -- `ξ` is the `f` in the theorem statement and we set `μ₁` to be `μ - ν.with_density ξ` -- since we need `μ₁ + ν.with_density ξ = μ` set μ₁ := μ - ν.with_density ξ with hμ₁, have hle : ν.with_density ξ ≤ μ, { intros B hB, rw [hξ, with_density_apply _ hB], simp_rw [supr_apply], rw lintegral_supr (λ i, (supr_mem_measurable_le _ hf₁ i).1) (supr_monotone _), exact supr_le (λ i, (supr_mem_measurable_le _ hf₁ i).2 B hB) }, haveI : is_finite_measure (ν.with_density ξ), { refine is_finite_measure_with_density _, have hle' := hle set.univ measurable_set.univ, rw [with_density_apply _ measurable_set.univ, measure.restrict_univ] at hle', exact ne_top_of_le_ne_top (measure_ne_top _ _) hle' }, refine ⟨⟨μ₁, ξ⟩, hξm, _, _⟩, { by_contra, -- if they are not mutually singular, then from `exists_positive_of_not_mutually_singular`, -- there exists some `ε > 0` and a measurable set `E`, such that `μ(E) > 0` and `E` is -- positive with respect to `ν - εμ` obtain ⟨ε, hε₁, E, hE₁, hE₂, hE₃⟩ := exists_positive_of_not_mutually_singular μ₁ ν h, simp_rw hμ₁ at hE₃, have hξle : ∀ A, measurable_set A → ∫⁻ a in A, ξ a ∂ν ≤ μ A, { intros A hA, rw hξ, simp_rw [supr_apply], rw lintegral_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1) (supr_monotone _), exact supr_le (λ n, (supr_mem_measurable_le _ hf₁ n).2 A hA) }, -- since `E` is positive, we have `∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E)` for all `A` have hε₂ : ∀ A : set α, measurable_set A → ∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E), { intros A hA, have := subset_le_of_restrict_le_restrict _ _ hE₁ hE₃ (set.inter_subset_right A E), rwa [zero_apply, to_signed_measure_sub_apply (hA.inter hE₁), measure.sub_apply (hA.inter hE₁) hle, ennreal.to_real_sub_of_le _ (ne_of_lt (measure_lt_top _ _)), sub_nonneg, le_sub_iff_add_le, ← ennreal.to_real_add, ennreal.to_real_le_to_real, measure.coe_nnreal_smul, pi.smul_apply, with_density_apply _ (hA.inter hE₁), show ε • ν (A ∩ E) = (ε : ℝ≥0∞) * ν (A ∩ E), by refl, ← set_lintegral_const, ← lintegral_add measurable_const hξm] at this, { rw [ne.def, ennreal.add_eq_top, not_or_distrib], exact ⟨ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)⟩ }, { exact ne_of_lt (measure_lt_top _ _) }, { exact ne_of_lt (measure_lt_top _ _) }, { exact ne_of_lt (measure_lt_top _ _) }, { rw with_density_apply _ (hA.inter hE₁), exact hξle (A ∩ E) (hA.inter hE₁) }, { apply_instance } }, -- from this, we can show `ξ + ε * E.indicator` is a function in `measurable_le` with -- integral greater than `ξ` have hξε : ξ + E.indicator (λ _, ε) ∈ measurable_le ν μ, { refine ⟨measurable.add hξm (measurable.indicator measurable_const hE₁), λ A hA, _⟩, have : ∫⁻ a in A, (ξ + E.indicator (λ _, ε)) a ∂ν = ∫⁻ a in A ∩ E, ε + ξ a ∂ν + ∫⁻ a in A ∩ Eᶜ, ξ a ∂ν, { rw [lintegral_add measurable_const hξm, add_assoc, ← lintegral_union (hA.inter hE₁) (hA.inter (hE₁.compl)) (disjoint.mono (set.inter_subset_right _ _) (set.inter_subset_right _ _) disjoint_compl_right), set.inter_union_compl], simp_rw [pi.add_apply], rw [lintegral_add hξm (measurable.indicator measurable_const hE₁), add_comm], refine congr_fun (congr_arg has_add.add _) _, rw [set_lintegral_const, lintegral_indicator _ hE₁, set_lintegral_const, measure.restrict_apply hE₁, set.inter_comm] }, conv_rhs { rw ← set.inter_union_compl A E }, rw [this, measure_union _ (hA.inter hE₁) (hA.inter hE₁.compl)], { exact add_le_add (hε₂ A hA) (hξle (A ∩ Eᶜ) (hA.inter hE₁.compl)) }, { exact disjoint.mono (set.inter_subset_right _ _) (set.inter_subset_right _ _) disjoint_compl_right } }, have : ∫⁻ a, ξ a + E.indicator (λ _, ε) a ∂ν ≤ Sup (measurable_le_eval ν μ) := le_Sup ⟨ξ + E.indicator (λ _, ε), hξε, rfl⟩, -- but this contradicts the maximality of `∫⁻ x, ξ x ∂ν` refine not_lt.2 this _, rw [hξ₁, lintegral_add hξm (measurable.indicator (measurable_const) hE₁), lintegral_indicator _ hE₁, set_lintegral_const], refine ennreal.lt_add_right _ (ennreal.mul_pos_iff.2 ⟨ennreal.coe_pos.2 hε₁, hE₂⟩).ne', have := measure_ne_top (ν.with_density ξ) set.univ, rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ] at this }, -- since `ν.with_density ξ ≤ μ`, it is clear that `μ = μ₁ + ν.with_density ξ` { rw hμ₁, ext1 A hA, rw [measure.coe_add, pi.add_apply, measure.sub_apply hA hle, add_comm, ennreal.add_sub_cancel_of_le (hle A hA)] }, end⟩ local attribute [instance] have_lebesgue_decomposition_of_finite_measure instance {S : μ.finite_spanning_sets_in {s : set α | measurable_set s}} (n : ℕ) : is_finite_measure (μ.restrict $ S.set n) := ⟨by { rw [restrict_apply measurable_set.univ, set.univ_inter], exact S.finite _ }⟩ /-- **The Lebesgue decomposition theorem**: Any pair of σ-finite measures `μ` and `ν` `have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` -/ @[priority 100] -- see Note [lower instance priority] instance have_lebesgue_decomposition_of_sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] : have_lebesgue_decomposition μ ν := ⟨begin -- Since `μ` and `ν` are both σ-finite, there exists a sequence of pairwise disjoint spanning -- sets which are finite with respect to both `μ` and `ν` obtain ⟨S, T, h₁, h₂⟩ := exists_eq_disjoint_finite_spanning_sets_in μ ν, have h₃ : pairwise (disjoint on T.set) := h₁ ▸ h₂, -- We define `μn` and `νn` as sequences of measures such that `μn n = μ ∩ S n` and -- `νn n = ν ∩ S n` where `S` is the aforementioned finite spanning set sequence. -- Since `S` is spanning, it is clear that `sum μn = μ` and `sum νn = ν` set μn : ℕ → measure α := λ n, μ.restrict (S.set n) with hμn, have hμ : μ = sum μn, { rw [hμn, ← restrict_Union h₂ S.set_mem, S.spanning, restrict_univ] }, set νn : ℕ → measure α := λ n, ν.restrict (T.set n) with hνn, have hν : ν = sum νn, { rw [hνn, ← restrict_Union h₃ T.set_mem, T.spanning, restrict_univ] }, -- As `S` is finite with respect to both `μ` and `ν`, it is clear that `μn n` and `νn n` are -- finite measures for all `n : ℕ`. Thus, we may apply the finite Lebesgue decomposition theorem -- to `μn n` and `νn n`. We define `ξ` as the sum of the singular part of the Lebesgue -- decompositions of `μn n` and `νn n`, and `f` as the sum of the Radon-Nikodym derviatives of -- `μn n` and `νn n` restricted on `S n` set ξ := sum (λ n, singular_part (μn n) (νn n)) with hξ, set f := ∑' n, (S.set n).indicator (rn_deriv (μn n) (νn n)) with hf, -- I claim `ξ` and `f` form a Lebesgue decomposition of `μ` and `ν` refine ⟨⟨ξ, f⟩, _, _, _⟩, { exact measurable.ennreal_tsum' (λ n, measurable.indicator (measurable_rn_deriv (μn n) (νn n)) (S.set_mem n)) }, -- We show that `ξ` is mutually singular with respect to `ν` { choose A hA₁ hA₂ hA₃ using λ n, mutually_singular_singular_part (μn n) (νn n), simp only [hξ], -- We use the set `B := ⋃ j, (S.set j) ∩ A j` where `A n` is the set provided as -- `singular_part (μn n) (νn n) ⊥ₘ νn n` refine ⟨⋃ j, (S.set j) ∩ A j, measurable_set.Union (λ n, (S.set_mem n).inter (hA₁ n)), _, _⟩, -- `ξ B = 0` since `ξ B = ∑ i j, singular_part (μn j) (νn j) (S.set i ∩ A i)` -- `= ∑ i, singular_part (μn i) (νn i) (S.set i ∩ A i)` -- `≤ ∑ i, singular_part (μn i) (νn i) (A i) = 0` -- where the second equality follows as `singular_part (μn j) (νn j) (S.set i ∩ A i)` vanishes -- for all `i ≠ j` { rw [measure_Union], { have : ∀ i, (sum (λ n, (μn n).singular_part (νn n))) (S.set i ∩ A i) = (μn i).singular_part (νn i) (S.set i ∩ A i), { intro i, rw [sum_apply _ ((S.set_mem i).inter (hA₁ i)), tsum_eq_single i], { intros j hij, rw [hμn, ← nonpos_iff_eq_zero], refine le_trans ((singular_part_le _ _) _ ((S.set_mem i).inter (hA₁ i))) (le_of_eq _), rw [restrict_apply ((S.set_mem i).inter (hA₁ i)), set.inter_comm, ← set.inter_assoc], have : disjoint (S.set j) (S.set i) := h₂ j i hij, rw set.disjoint_iff_inter_eq_empty at this, rw [this, set.empty_inter, measure_empty] }, { apply_instance } }, simp_rw [this, tsum_eq_zero_iff ennreal.summable], intro n, exact measure_mono_null (set.inter_subset_right _ _) (hA₂ n) }, { exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) }, { exact λ n, (S.set_mem n).inter (hA₁ n) } }, -- We will now show `ν Bᶜ = 0`. This follows since `Bᶜ = ⋃ n, S.set n ∩ (A n)ᶜ` and thus, -- `ν Bᶜ = ∑ i, ν (S.set i ∩ (A i)ᶜ) = ∑ i, (νn i) (A i)ᶜ = 0` { have hcompl : is_compl (⋃ n, (S.set n ∩ A n)) (⋃ n, S.set n ∩ (A n)ᶜ), { split, { rintro x ⟨hx₁, hx₂⟩, rw set.mem_Union at hx₁ hx₂, obtain ⟨⟨i, hi₁, hi₂⟩, ⟨j, hj₁, hj₂⟩⟩ := ⟨hx₁, hx₂⟩, have : i = j, { by_contra hij, exact h₂ i j hij ⟨hi₁, hj₁⟩ }, exact hj₂ (this ▸ hi₂) }, { intros x hx, simp only [set.mem_Union, set.sup_eq_union, set.mem_inter_eq, set.mem_union_eq, set.mem_compl_eq, or_iff_not_imp_left], intro h, push_neg at h, rw [set.top_eq_univ, ← S.spanning, set.mem_Union] at hx, obtain ⟨i, hi⟩ := hx, exact ⟨i, hi, h i hi⟩ } }, rw [hcompl.compl_eq, measure_Union, tsum_eq_zero_iff ennreal.summable], { intro n, rw [set.inter_comm, ← restrict_apply (hA₁ n).compl, ← hA₃ n, hνn, h₁] }, { exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) }, { exact λ n, (S.set_mem n).inter (hA₁ n).compl } } }, -- Finally, it remains to show `μ = ξ + ν.with_density f`. Since `μ = sum μn`, and -- `ξ + ν.with_density f = ∑ n, singular_part (μn n) (νn n)` -- `+ ν.with_density (rn_deriv (μn n) (νn n)) ∩ (S.set n)`, -- it suffices to show that the individual summands are equal. This follows by the -- Lebesgue decomposition properties on the individual `μn n` and `νn n` { simp only [hξ, hf, hμ], rw [with_density_tsum _, sum_add_sum], { refine sum_congr (λ n, _), conv_lhs { rw have_lebesgue_decomposition_add (μn n) (νn n) }, suffices heq : (νn n).with_density ((μn n).rn_deriv (νn n)) = ν.with_density ((S.set n).indicator ((μn n).rn_deriv (νn n))), { rw heq }, rw [hν, with_density_indicator (S.set_mem n), restrict_sum _ (S.set_mem n)], suffices hsumeq : sum (λ (i : ℕ), (νn i).restrict (S.set n)) = νn n, { rw hsumeq }, ext1 s hs, rw [sum_apply _ hs, tsum_eq_single n, hνn, h₁, restrict_restrict (T.set_mem n), set.inter_self], { intros m hm, rw [hνn, h₁, restrict_restrict (T.set_mem n), set.inter_comm, set.disjoint_iff_inter_eq_empty.1 (h₃ m n hm), restrict_empty, coe_zero, pi.zero_apply] }, { apply_instance } }, { exact λ n, measurable.indicator (measurable_rn_deriv _ _) (S.set_mem n) } }, end⟩ end measure namespace signed_measure open measure /-- A signed measure `s` is said to `have_lebesgue_decomposition` with respect to a measure `μ` if the positive part and the negative part of `s` both `have_lebesgue_decomposition` with respect to `μ`. -/ class have_lebesgue_decomposition (s : signed_measure α) (μ : measure α) : Prop := (pos_part : s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ) (neg_part : s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ) attribute [instance] have_lebesgue_decomposition.pos_part attribute [instance] have_lebesgue_decomposition.neg_part lemma not_have_lebesgue_decomposition_iff (s : signed_measure α) (μ : measure α) : ¬ s.have_lebesgue_decomposition μ ↔ ¬ s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ ∨ ¬ s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ := ⟨λ h, not_or_of_imp (λ hp hn, h ⟨hp, hn⟩), λ h hl, (not_and_distrib.2 h) ⟨hl.1, hl.2⟩⟩ -- `infer_instance` directly does not work @[priority 100] -- see Note [lower instance priority] instance have_lebesgue_decomposition_of_sigma_finite (s : signed_measure α) (μ : measure α) [sigma_finite μ] : s.have_lebesgue_decomposition μ := { pos_part := infer_instance, neg_part := infer_instance } instance have_lebesgue_decomposition_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] : (-s).have_lebesgue_decomposition μ := { pos_part := by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part], apply_instance }, neg_part := by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part], apply_instance } } instance have_lebesgue_decomposition_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ≥0) : (r • s).have_lebesgue_decomposition μ := { pos_part := by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part], apply_instance }, neg_part := by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part], apply_instance } } instance have_lebesgue_decomposition_smul_real (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) : (r • s).have_lebesgue_decomposition μ := begin by_cases hr : 0 ≤ r, { lift r to ℝ≥0 using hr, exact s.have_lebesgue_decomposition_smul μ _ }, { rw not_le at hr, refine { pos_part := by { rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_pos_part_neg _ _ hr], apply_instance }, neg_part := by { rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_neg_part_neg _ _ hr], apply_instance } } } end /-- Given a signed measure `s` and a measure `μ`, `s.singular_part μ` is the signed measure such that `s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s` and `s.singular_part μ` is mutually singular with respect to `μ`. -/ def singular_part(s : signed_measure α) (μ : measure α) : signed_measure α := (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure - (s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure section lemma singular_part_mutually_singular (s : signed_measure α) (μ : measure α) : s.to_jordan_decomposition.pos_part.singular_part μ ⊥ₘ s.to_jordan_decomposition.neg_part.singular_part μ := begin by_cases hl : s.have_lebesgue_decomposition μ, { haveI := hl, obtain ⟨i, hi, hpos, hneg⟩ := s.to_jordan_decomposition.mutually_singular, rw s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ at hpos, rw s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ at hneg, rw [add_apply, add_eq_zero_iff] at hpos hneg, exact ⟨i, hi, hpos.1, hneg.1⟩ }, { rw not_have_lebesgue_decomposition_iff at hl, cases hl with hp hn, { rw [measure.singular_part, dif_neg hp], exact mutually_singular.zero.symm }, { rw [measure.singular_part, measure.singular_part, dif_neg hn], exact mutually_singular.zero } } end lemma singular_part_total_variation (s : signed_measure α) (μ : measure α) : (s.singular_part μ).total_variation = s.to_jordan_decomposition.pos_part.singular_part μ + s.to_jordan_decomposition.neg_part.singular_part μ := begin have : (s.singular_part μ).to_jordan_decomposition = ⟨s.to_jordan_decomposition.pos_part.singular_part μ, s.to_jordan_decomposition.neg_part.singular_part μ, singular_part_mutually_singular s μ⟩, { refine jordan_decomposition.to_signed_measure_injective _, rw to_signed_measure_to_jordan_decomposition, refl }, { rw [total_variation, this] }, end lemma mutually_singular_singular_part (s : signed_measure α) (μ : measure α) : singular_part s μ ⊥ᵥ μ.to_ennreal_vector_measure := begin rw [mutually_singular_ennreal_iff, singular_part_total_variation], change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ), rw vector_measure.equiv_measure.right_inv μ, exact measure.mutually_singular.add (mutually_singular_singular_part _ _) (mutually_singular_singular_part _ _), end end /-- The Radon-Nikodym derivative between a signed measure and a positive measure. `rn_deriv s μ` satisfies `μ.with_densityᵥ (s.rn_deriv μ) = s` if and only if `s` is absolutely continuous with respect to `μ` and this fact is known as `measure_theory.signed_measure.absolutely_continuous_iff_with_density_rn_deriv_eq` and can be found in `measure_theory.decomposition.radon_nikodym`. -/ def rn_deriv (s : signed_measure α) (μ : measure α) : α → ℝ := λ x, (s.to_jordan_decomposition.pos_part.rn_deriv μ x).to_real - (s.to_jordan_decomposition.neg_part.rn_deriv μ x).to_real variables {s t : signed_measure α} @[measurability] lemma measurable_rn_deriv (s : signed_measure α) (μ : measure α) : measurable (rn_deriv s μ) := begin rw [rn_deriv], measurability, end lemma integrable_rn_deriv (s : signed_measure α) (μ : measure α) : integrable (rn_deriv s μ) μ := begin refine integrable.sub _ _; { split, measurability, exact has_finite_integral_to_real_of_lintegral_ne_top (lintegral_rn_deriv_lt_top _ μ).ne } end /-- **The Lebesgue Decomposition theorem between a signed measure and a measure**: Given a signed measure `s` and a σ-finite measure `μ`, there exist a signed measure `t` and a measurable and integrable function `f`, such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`. In this case `t = s.singular_part μ` and `f = s.rn_deriv μ`. -/ theorem singular_part_add_with_density_rn_deriv_eq [s.have_lebesgue_decomposition μ] : s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s := begin conv_rhs { rw [← to_signed_measure_to_jordan_decomposition s, jordan_decomposition.to_signed_measure] }, rw [singular_part, rn_deriv, with_densityᵥ_sub' (integrable_to_real_of_lintegral_ne_top _ _) (integrable_to_real_of_lintegral_ne_top _ _), with_densityᵥ_to_real, with_densityᵥ_to_real, sub_eq_add_neg, sub_eq_add_neg, add_comm (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, ← add_assoc, add_assoc (-(s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure), ← to_signed_measure_add, add_comm, ← add_assoc, ← neg_add, ← to_signed_measure_add, add_comm, ← sub_eq_add_neg], convert rfl, -- `convert rfl` much faster than `congr` { exact (s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ) }, { rw add_comm, exact (s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ) }, all_goals { exact (lintegral_rn_deriv_lt_top _ _).ne <|> measurability } end lemma jordan_decomposition_add_with_density_mutually_singular {f : α → ℝ} (hf : measurable f) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) : t.to_jordan_decomposition.pos_part + μ.with_density (λ (x : α), ennreal.of_real (f x)) ⊥ₘ t.to_jordan_decomposition.neg_part + μ.with_density (λ (x : α), ennreal.of_real (-f x)) := begin rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ, change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧ _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv] at htμ, exact ((jordan_decomposition.mutually_singular _).symm.add (htμ.1.symm.of_absolutely_continuous (with_density_absolutely_continuous _ _))).symm.add ((htμ.2.symm.of_absolutely_continuous (with_density_absolutely_continuous _ _)).symm.add (with_density_of_real_mutually_singular hf).symm).symm end lemma to_jordan_decomposition_eq_of_eq_add_with_density {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.to_jordan_decomposition = @jordan_decomposition.mk α _ (t.to_jordan_decomposition.pos_part + μ.with_density (λ x, ennreal.of_real (f x))) (t.to_jordan_decomposition.neg_part + μ.with_density (λ x, ennreal.of_real (- f x))) (by { haveI := is_finite_measure_with_density_of_real hfi.2, apply_instance }) (by { haveI := is_finite_measure_with_density_of_real hfi.neg.2, apply_instance }) (jordan_decomposition_add_with_density_mutually_singular hf htμ) := begin haveI := is_finite_measure_with_density_of_real hfi.2, haveI := is_finite_measure_with_density_of_real hfi.neg.2, refine to_jordan_decomposition_eq _, simp_rw [jordan_decomposition.to_signed_measure, hadd], ext i hi, rw [vector_measure.sub_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi, add_apply, add_apply, ennreal.to_real_add, ennreal.to_real_add, add_sub_comm, ← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi, ← vector_measure.sub_apply, ← jordan_decomposition.to_signed_measure, to_signed_measure_to_jordan_decomposition, vector_measure.add_apply, ← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi, with_densityᵥ_eq_with_density_pos_part_sub_with_density_neg_part hfi, vector_measure.sub_apply]; exact (measure_lt_top _ _).ne end private lemma have_lebesgue_decomposition_mk' (μ : measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.have_lebesgue_decomposition μ := begin have htμ' := htμ, rw mutually_singular_ennreal_iff at htμ, change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv, total_variation_mutually_singular_iff] at htμ, refine { pos_part := by { use ⟨t.to_jordan_decomposition.pos_part, λ x, ennreal.of_real (f x)⟩, refine ⟨hf.ennreal_of_real, htμ.1, _⟩, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd }, neg_part := by { use ⟨t.to_jordan_decomposition.neg_part, λ x, ennreal.of_real (-f x)⟩, refine ⟨hf.neg.ennreal_of_real, htμ.2, _⟩, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } } end lemma have_lebesgue_decomposition_mk (μ : measure α) {f : α → ℝ} (hf : measurable f) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.have_lebesgue_decomposition μ := begin by_cases hfi : integrable f μ, { exact have_lebesgue_decomposition_mk' μ hf hfi htμ hadd }, { rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd, refine have_lebesgue_decomposition_mk' μ measurable_zero (integrable_zero _ _ μ) htμ _, rwa [with_densityᵥ_zero, add_zero] } end private theorem eq_singular_part' (t : signed_measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : t = s.singular_part μ := begin have htμ' := htμ, rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ, change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧ _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv] at htμ, { rw [singular_part, ← t.to_signed_measure_to_jordan_decomposition, jordan_decomposition.to_signed_measure], congr, { have hfpos : measurable (λ x, ennreal.of_real (f x)), { measurability }, refine eq_singular_part hfpos htμ.1 _, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd }, { have hfneg : measurable (λ x, ennreal.of_real (-f x)), { measurability }, refine eq_singular_part hfneg htμ.2 _, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } }, end /-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have `t = singular_part s μ`, i.e. `t` is the singular part of the Lebesgue decomposition between `s` and `μ`. -/ theorem eq_singular_part (t : signed_measure α) (f : α → ℝ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : t = s.singular_part μ := begin by_cases hfi : integrable f μ, { refine eq_singular_part' t hfi.1.measurable_mk (hfi.congr hfi.1.ae_eq_mk) htμ _, convert hadd using 2, exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm }, { rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd, refine eq_singular_part' t measurable_zero (integrable_zero _ _ μ) htμ _, rwa [with_densityᵥ_zero, add_zero] } end lemma singular_part_zero (μ : measure α) : (0 : signed_measure α).singular_part μ = 0 := begin refine (eq_singular_part 0 0 vector_measure.mutually_singular.zero_left _).symm, rw [zero_add, with_densityᵥ_zero], end lemma singular_part_neg (s : signed_measure α) (μ : measure α) : (-s).singular_part μ = - s.singular_part μ := begin have h₁ : ((-s).to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure = (s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure, { refine to_signed_measure_congr _, rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part] }, have h₂ : ((-s).to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure = (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, { refine to_signed_measure_congr _, rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part] }, rw [singular_part, singular_part, neg_sub, h₁, h₂], end lemma singular_part_smul_nnreal (s : signed_measure α) (μ : measure α) (r : ℝ≥0) : (r • s).singular_part μ = r • s.singular_part μ := begin rw [singular_part, singular_part, smul_sub, ← to_signed_measure_smul, ← to_signed_measure_smul], conv_lhs { congr, congr, rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part, singular_part_smul], skip, congr, rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part, singular_part_smul] } end lemma singular_part_smul (s : signed_measure α) (μ : measure α) (r : ℝ) : (r • s).singular_part μ = r • s.singular_part μ := begin by_cases hr : 0 ≤ r, { lift r to ℝ≥0 using hr, exact singular_part_smul_nnreal s μ r }, { rw [singular_part, singular_part], conv_lhs { congr, congr, rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_pos_part_neg _ _ (not_le.1 hr), singular_part_smul], skip, congr, rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_neg_part_neg _ _ (not_le.1 hr), singular_part_smul] }, rw [to_signed_measure_smul, to_signed_measure_smul, ← neg_sub, ← smul_sub], change -(((-r).to_nnreal : ℝ) • _) = _, rw [← neg_smul, real.coe_to_nnreal _ (le_of_lt (neg_pos.mpr (not_le.1 hr))), neg_neg] } end lemma singular_part_add (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] : (s + t).singular_part μ = s.singular_part μ + t.singular_part μ := begin refine (eq_singular_part _ (s.rn_deriv μ + t.rn_deriv μ) ((mutually_singular_singular_part s μ).add_left (mutually_singular_singular_part t μ)) _).symm, erw [with_densityᵥ_add (integrable_rn_deriv s μ) (integrable_rn_deriv t μ)], rw [add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq, ← add_assoc, singular_part_add_with_density_rn_deriv_eq], end lemma singular_part_sub (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] : (s - t).singular_part μ = s.singular_part μ - t.singular_part μ := by { rw [sub_eq_add_neg, sub_eq_add_neg, singular_part_add, singular_part_neg] } /-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have `f = rn_deriv s μ`, i.e. `f` is the Radon-Nikodym derivative of `s` and `μ`. -/ theorem eq_rn_deriv (t : signed_measure α) (f : α → ℝ) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : f =ᵐ[μ] s.rn_deriv μ := begin set f' := hfi.1.mk f, have hadd' : s = t + μ.with_densityᵥ f', { convert hadd using 2, exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm }, haveI := have_lebesgue_decomposition_mk μ hfi.1.measurable_mk htμ hadd', refine (integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) hfi _).symm, rw [← add_right_inj t, ← hadd, eq_singular_part _ f htμ hadd, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] : (-s).rn_deriv μ =ᵐ[μ] - s.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) (integrable_rn_deriv _ _).neg _, rw [with_densityᵥ_neg, ← add_right_inj ((-s).singular_part μ), singular_part_add_with_density_rn_deriv_eq, singular_part_neg, ← neg_add, singular_part_add_with_density_rn_deriv_eq] end lemma rn_deriv_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) : (r • s).rn_deriv μ =ᵐ[μ] r • s.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).smul r) _, change _ = μ.with_densityᵥ ((r : ℝ) • s.rn_deriv μ), rw [with_densityᵥ_smul (rn_deriv s μ) (r : ℝ), ← add_right_inj ((r • s).singular_part μ), singular_part_add_with_density_rn_deriv_eq, singular_part_smul], change _ = _ + r • _, rw [← smul_add, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_add (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] [(s + t).have_lebesgue_decomposition μ] : (s + t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ + t.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).add (integrable_rn_deriv _ _)) _, rw [← add_right_inj ((s + t).singular_part μ), singular_part_add_with_density_rn_deriv_eq, with_densityᵥ_add (integrable_rn_deriv _ _) (integrable_rn_deriv _ _), singular_part_add, add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq, ← add_assoc, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_sub (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] [hst : (s - t).have_lebesgue_decomposition μ] : (s - t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ - t.rn_deriv μ := begin rw sub_eq_add_neg at hst, rw [sub_eq_add_neg, sub_eq_add_neg], exactI ae_eq_trans (rn_deriv_add _ _ _) (filter.eventually_eq.add (ae_eq_refl _) (rn_deriv_neg _ _)), end end signed_measure end measure_theory
05dd33adfac272218bf46bd73cf99c3afc6ba7e8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/group/is_unit.lean
98b34be9360f9e4fd41bd8657e427918524e60a1
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
4,079
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 Contents of this file was cherry-picked from `algebra/associated` by Yury Kudryashov. I copied the original copyright header from there. -/ import algebra.group.units_hom /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, a = u @[simp, to_additive is_add_unit_add_unit] lemma is_unit_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[to_additive] lemma is_unit.map [monoid M] [monoid N] (f : M →* N) {x : M} (h : is_unit x) : is_unit (f x) := by rcases h with ⟨y, rfl⟩; exact is_unit_unit (units.map f y) @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_zero] theorem is_unit_of_mul_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv.symm ▸ ⟨v * u, (units.coe_mul v u).symm⟩) @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[simp] theorem is_unit_nat {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) /-- If a homomorphism `f : M →* N` sends each element to an `is_unit`, then it can be lifted to `f : M →* units N`. See also `units.lift_right` for a computable version. -/ @[to_additive "If a homomorphism `f : M →+ N` sends each element to an `is_add_unit`, then it can be lifted to `f : M →+ add_units N`. See also `add_units.lift_right` for a computable version."] noncomputable def is_unit.lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) : M →* units N := units.lift_right f (λ x, classical.some (hf x)) (λ x, (classical.some_spec (hf x)).symm) @[simp, to_additive] lemma is_unit.coe_lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) (x) : (is_unit.lift_right f hf x : N) = f x := units.coe_lift_right _ x
fd131a61d3d1cd0f4fae29eff1e53235ac30f7d5
1437b3495ef9020d5413178aa33c0a625f15f15f
/category_theory/functor.lean
9bc43ddf9b836875acb411c8f6302bfc55a0ee90
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,542
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison Defines a functor between categories. (As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised by the underlying function on objects, the name is capitalised.) Introduces notations `C ⥤ D` for the type of all functors from `C` to `D`. (I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.) -/ import category_theory.category import tactic.tidy namespace category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`. The axiom `map_id_lemma` expresses preservation of identities, and `map_comp_lemma` expresses functoriality. -/ structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] : Type (max u₁ v₁ u₂ v₂) := (obj : C → D) (map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) infixr ` ⥤ `:70 := functor -- type as \func -- restate_axiom functor.map_id' attribute [simp] functor.map_id restate_axiom functor.map_comp' attribute [simp] functor.map_comp namespace functor section variables (C : Type u₁) [𝒞 : category.{v₁} C] include 𝒞 /-- `functor.id C` is the identity functor on a category `C`. -/ protected def id : C ⥤ C := { obj := λ X, X, map := λ _ _ f, f } variable {C} @[simp] lemma id_obj (X : C) : (functor.id C).obj X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (functor.id C).map f = f := rfl end section variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G.obj (F.obj X), map := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) (X Y : C) (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl end section variables (C : Type u₁) [𝒞 : category.{v₁} C] include 𝒞 @[simp] def ulift_down : (ulift.{u₂} C) ⥤ C := { obj := λ X, X.down, map := λ X Y f, f } @[simp] def ulift_up : C ⥤ (ulift.{u₂} C) := { obj := λ X, ⟨ X ⟩, map := λ X Y f, f } end end functor def bundled.map {c : Type u → Type v} {d : Type u → Type v} (f : Π{a}, c a → d a) (s : bundled c) : bundled d := { α := s.α, str := f s.str } def concrete_functor {C : Type u → Type v} {hC : ∀{α β}, C α → C β → (α → β) → Prop} [concrete_category @hC] {D : Type u → Type v} {hD : ∀{α β}, D α → D β → (α → β) → Prop} [concrete_category @hD] (m : ∀{α}, C α → D α) (h : ∀{α β} {ia : C α} {ib : C β} {f}, hC ia ib f → hD (m ia) (m ib) f) : bundled C ⥤ bundled D := { obj := bundled.map @m, map := λ X Y f, ⟨ f, h f.2 ⟩} end category_theory
c8f7c3432f7cb52cc433deca1354ade3382df4b3
cbcb0199842f03e7606d4e43666573fc15dd07a5
/src/analysis/complex/exponential.lean
9c1342a87ad75771d6ba515a5cc07bfc3a04d373
[ "Apache-2.0" ]
permissive
truonghoangle/mathlib
a6a7c14b3767ec71156239d8ea97f6921fe79627
673bae584febcd830c2c9256eb7e7a81e27ed303
refs/heads/master
1,590,347,998,944
1,559,728,860,000
1,559,728,860,000
187,431,971
0
0
null
1,558,238,525,000
1,558,238,525,000
null
UTF-8
Lean
false
false
60,450
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import topology.instances.complex tactic.linarith data.complex.exponential group_theory.quotient_group topology.metric_space.basic open finset filter metric namespace complex lemma tendsto_exp_zero_one : tendsto exp (nhds 0) (nhds 1) := tendsto_nhds_nhds.2 $ λ ε ε0, ⟨min (ε / 2) 1, lt_min (div_pos ε0 (by norm_num)) (by norm_num), λ x h, have h : abs x < min (ε / 2) 1, by simpa [dist_eq] using h, calc abs (exp x - 1) ≤ 2 * abs x : abs_exp_sub_one_le (le_trans (le_of_lt h) (min_le_right _ _)) ... = abs x + abs x : two_mul (abs x) ... < ε / 2 + ε / 2 : add_lt_add (lt_of_lt_of_le h (min_le_left _ _)) (lt_of_lt_of_le h (min_le_left _ _)) ... = ε : by rw add_halves⟩ lemma continuous_exp : continuous exp := continuous_iff_continuous_at.2 (λ x, have H1 : tendsto (λ h, exp (x + h)) (nhds 0) (nhds (exp x)), by simpa [exp_add] using tendsto_mul tendsto_const_nhds tendsto_exp_zero_one, have H2 : tendsto (λ y, y - x) (nhds x) (nhds (x - x)) := tendsto_sub tendsto_id (@tendsto_const_nhds _ _ _ x _), suffices tendsto ((λ h, exp (x + h)) ∘ (λ y, id y - (λ z, x) y)) (nhds x) (nhds (exp x)), by simp only [function.comp, add_sub_cancel'_right, id.def] at this; exact this, tendsto.comp (by rw [sub_self] at H2; exact H2) H1) lemma continuous_sin : continuous sin := continuous_mul (continuous_mul (continuous_sub (continuous_exp.comp (continuous_mul continuous_neg' continuous_const)) (continuous_exp.comp (continuous_mul continuous_id continuous_const))) continuous_const) continuous_const lemma continuous_cos : continuous cos := continuous_mul (continuous_add (continuous_exp.comp (continuous_mul continuous_id continuous_const)) (continuous_exp.comp (continuous_mul continuous_neg' continuous_const))) continuous_const lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := continuous_mul (continuous_sin.comp continuous_subtype_val) (continuous_inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_sinh : continuous sinh := continuous_mul (continuous_sub continuous_exp (continuous_exp.comp continuous_neg')) continuous_const lemma continuous_cosh : continuous cosh := continuous_mul (continuous_add continuous_exp (continuous_exp.comp continuous_neg')) continuous_const end complex namespace real lemma continuous_exp : continuous exp := complex.continuous_re.comp (complex.continuous_exp.comp complex.continuous_of_real) lemma continuous_sin : continuous sin := complex.continuous_re.comp (complex.continuous_sin.comp complex.continuous_of_real) lemma continuous_cos : continuous cos := complex.continuous_re.comp (complex.continuous_cos.comp complex.continuous_of_real) lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact continuous_mul (continuous_sin.comp continuous_subtype_val) (continuous_inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_sinh : continuous sinh := complex.continuous_re.comp (complex.continuous_sinh.comp complex.continuous_of_real) lemma continuous_cosh : continuous cosh := complex.continuous_re.comp (complex.continuous_cosh.comp complex.continuous_of_real) private lemma exists_exp_eq_of_one_le {x : ℝ} (hx : 1 ≤ x) : ∃ y, exp y = x := let ⟨y, hy⟩ := @intermediate_value real.exp 0 (x - 1) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_exp _) (by simpa) (by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hx)) (sub_nonneg.2 hx) in ⟨y, hy.2.2⟩ lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := exists_exp_eq_of_one_le (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := exists_exp_eq_of_one_le hx1 end noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma exists_cos_eq_zero : ∃ x, 1 ≤ x ∧ x ≤ 2 ∧ cos x = 0 := real.intermediate_value' (λ x _ _, continuous_iff_continuous_at.1 continuous_cos _) (le_of_lt cos_one_pos) (le_of_lt cos_two_neg) (by norm_num) noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero local notation `π` := pi @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.1 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith using [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith using [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith using [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : ∃ y, -(π / 2) ≤ y ∧ y ≤ π / 2 ∧ sin y = x := @real.intermediate_value sin (-(π / 2)) (π / 2) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_sin _) (by rwa [sin_neg, sin_pi_div_two]) (by rwa sin_pi_div_two) (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : sin x > x - x ^ 3 / 4 := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end namespace angle /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : is_add_group_hom (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := is_add_group_hom.map_gsmul _ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ two_ne_zero, ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ two_ne_zero, eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_left_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero, cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx.1 hx.2) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).2.1 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq hx₁ hx₂)).2.2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith using [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith using [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith using [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith using [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith using [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex local notation `π` := real.pi /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x,abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith using [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith using [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := if hx : x = 0 then by simp [hx] else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx, div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)] lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := begin rw [rpow_def_of_nonneg (le_of_lt hx)]; split_ifs, { exact zero_lt_one }, { rwa h at hx }, { apply exp_pos } end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_lt hx).symm, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y): (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul hx hy, add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z): x^z ≤ y^z := begin rw le_iff_eq_or_lt at h h₂, cases h₂, { rw [←h₂, rpow_zero, rpow_zero]}, { cases h, { rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs, { exact zero_le_one}, { refl}, { exact le_of_lt (exp_pos (log y * z))}, { rwa ←h at h₁}, { exact ne.symm (ne_of_lt h₂)}}, { have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁, have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂), rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc], rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm], exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } } end lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 := by rw ←one_rpow e; apply rpow_le_rpow; assumption lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero'] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] end real
dff99049443c1a7667cc8428350da245ffab18df
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed/group/SemiNormedGroup/kernels.lean
37053908549f7eb5229376ade4d37ced6ab6b5c2
[ "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
13,146
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca, Johan Commelin, Scott Morrison -/ import analysis.normed.group.SemiNormedGroup import analysis.normed.group.quotient import category_theory.limits.shapes.kernels /-! # Kernels and cokernels in SemiNormedGroup₁ and SemiNormedGroup We show that `SemiNormedGroup₁` has cokernels (for which of course the `cokernel.π f` maps are norm non-increasing), as well as the easier result that `SemiNormedGroup` has cokernels. We also show that `SemiNormedGroup` has kernels. So far, I don't see a way to state nicely what we really want: `SemiNormedGroup` has cokernels, and `cokernel.π f` is norm non-increasing. The problem is that the limits API doesn't promise you any particular model of the cokernel, and in `SemiNormedGroup` one can always take a cokernel and rescale its norm (and hence making `cokernel.π f` arbitrarily large in norm), obtaining another categorical cokernel. -/ open category_theory category_theory.limits universe u namespace SemiNormedGroup₁ noncomputable theory /-- Auxiliary definition for `has_cokernels SemiNormedGroup₁`. -/ def cokernel_cocone {X Y : SemiNormedGroup₁.{u}} (f : X ⟶ Y) : cofork f 0 := cofork.of_π (@SemiNormedGroup₁.mk_hom _ (SemiNormedGroup.of (quotient_add_group.quotient (normed_group_hom.range f.1))) f.1.range.normed_mk (normed_group_hom.is_quotient_quotient _).norm_le) begin ext, simp only [comp_apply, limits.zero_comp, normed_group_hom.zero_apply, SemiNormedGroup₁.mk_hom_apply, SemiNormedGroup₁.zero_apply, ←normed_group_hom.mem_ker, f.1.range.ker_normed_mk, f.1.mem_range], use x, refl, end /-- Auxiliary definition for `has_cokernels SemiNormedGroup₁`. -/ def cokernel_lift {X Y : SemiNormedGroup₁.{u}} (f : X ⟶ Y) (s : cokernel_cofork f) : (cokernel_cocone f).X ⟶ s.X := begin fsplit, -- The lift itself: { apply normed_group_hom.lift _ s.π.1, rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, }, -- The lift has norm at most one: exact normed_group_hom.lift_norm_noninc _ _ _ s.π.2, end instance : has_cokernels SemiNormedGroup₁.{u} := { has_colimit := λ X Y f, has_colimit.mk { cocone := cokernel_cocone f, is_colimit := is_colimit_aux _ (cokernel_lift f) (λ s, begin ext, apply normed_group_hom.lift_mk f.1.range, rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, end) (λ s m w, subtype.eq (normed_group_hom.lift_unique f.1.range _ _ _ (congr_arg subtype.val w : _))), } } -- Sanity check example : has_cokernels SemiNormedGroup₁ := by apply_instance end SemiNormedGroup₁ namespace SemiNormedGroup section equalizers_and_kernels /-- The equalizer cone for a parallel pair of morphisms of seminormed groups. -/ def parallel_pair_cone {V W : SemiNormedGroup.{u}} (f g : V ⟶ W) : cone (parallel_pair f g) := @fork.of_ι _ _ _ _ _ _ (of (f - g).ker) (normed_group_hom.incl (f - g).ker) $ begin ext v, have : v.1 ∈ (f - g).ker := v.2, simpa only [normed_group_hom.incl_apply, pi.zero_apply, coe_comp, normed_group_hom.coe_zero, subtype.val_eq_coe, normed_group_hom.mem_ker, normed_group_hom.coe_sub, pi.sub_apply, sub_eq_zero] using this end instance has_limit_parallel_pair {V W : SemiNormedGroup.{u}} (f g : V ⟶ W) : has_limit (parallel_pair f g) := { exists_limit := nonempty.intro { cone := parallel_pair_cone f g, is_limit := fork.is_limit.mk _ (λ c, normed_group_hom.ker.lift (fork.ι c) _ $ show normed_group_hom.comp_hom (f - g) c.ι = 0, by { rw [add_monoid_hom.map_sub, add_monoid_hom.sub_apply, sub_eq_zero], exact c.condition }) (λ c, normed_group_hom.ker.incl_comp_lift _ _ _) (λ c g h, by { ext x, dsimp, rw ← h, refl }) } } instance : limits.has_equalizers.{u (u+1)} SemiNormedGroup := @has_equalizers_of_has_limit_parallel_pair SemiNormedGroup _ $ λ V W f g, SemiNormedGroup.has_limit_parallel_pair f g end equalizers_and_kernels section cokernel -- PROJECT: can we reuse the work to construct cokernels in `SemiNormedGroup₁` here? -- I don't see a way to do this that is less work than just repeating the relevant parts. /-- Auxiliary definition for `has_cokernels SemiNormedGroup`. -/ def cokernel_cocone {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : cofork f 0 := @cofork.of_π _ _ _ _ _ _ (SemiNormedGroup.of (quotient_add_group.quotient (normed_group_hom.range f))) f.range.normed_mk begin ext, simp only [comp_apply, limits.zero_comp, normed_group_hom.zero_apply, ←normed_group_hom.mem_ker, f.range.ker_normed_mk, f.mem_range, exists_apply_eq_apply], end /-- Auxiliary definition for `has_cokernels SemiNormedGroup`. -/ def cokernel_lift {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) (s : cokernel_cofork f) : (cokernel_cocone f).X ⟶ s.X := normed_group_hom.lift _ s.π begin rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, end /-- Auxiliary definition for `has_cokernels SemiNormedGroup`. -/ def is_colimit_cokernel_cocone {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : is_colimit (cokernel_cocone f) := is_colimit_aux _ (cokernel_lift f) (λ s, begin ext, apply normed_group_hom.lift_mk f.range, rintro _ ⟨b, rfl⟩, change (f ≫ s.π) b = 0, simp, end) (λ s m w, normed_group_hom.lift_unique f.range _ _ _ w) instance : has_cokernels SemiNormedGroup.{u} := { has_colimit := λ X Y f, has_colimit.mk { cocone := cokernel_cocone f, is_colimit := is_colimit_cokernel_cocone f } } -- Sanity check example : has_cokernels SemiNormedGroup := by apply_instance section explicit_cokernel /-- An explicit choice of cokernel, which has good properties with respect to the norm. -/ def explicit_cokernel {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : SemiNormedGroup.{u} := (cokernel_cocone f).X /-- Descend to the explicit cokernel. -/ def explicit_cokernel_desc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : explicit_cokernel f ⟶ Z := (is_colimit_cokernel_cocone f).desc (cofork.of_π g (by simp [w])) /-- The projection from `Y` to the explicit cokernel of `X ⟶ Y`. -/ def explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : Y ⟶ explicit_cokernel f := (cokernel_cocone f).ι.app walking_parallel_pair.one lemma explicit_cokernel_π_surjective {X Y : SemiNormedGroup.{u}} {f : X ⟶ Y} : function.surjective (explicit_cokernel_π f) := surjective_quot_mk _ @[simp, reassoc] lemma comp_explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : f ≫ explicit_cokernel_π f = 0 := begin convert (cokernel_cocone f).w walking_parallel_pair_hom.left, simp, end @[simp] lemma explicit_cokernel_π_apply_dom_eq_zero {X Y : SemiNormedGroup.{u}} {f : X ⟶ Y} (x : X) : (explicit_cokernel_π f) (f x) = 0 := show (f ≫ (explicit_cokernel_π f)) x = 0, by { rw [comp_explicit_cokernel_π], refl } @[simp, reassoc] lemma explicit_cokernel_π_desc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : explicit_cokernel_π f ≫ explicit_cokernel_desc w = g := (is_colimit_cokernel_cocone f).fac _ _ @[simp] lemma explicit_cokernel_π_desc_apply {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {cond : f ≫ g = 0} (x : Y) : explicit_cokernel_desc cond (explicit_cokernel_π f x) = g x := show (explicit_cokernel_π f ≫ explicit_cokernel_desc cond) x = g x, by rw explicit_cokernel_π_desc lemma explicit_cokernel_desc_unique {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) (e : explicit_cokernel f ⟶ Z) (he : explicit_cokernel_π f ≫ e = g) : e = explicit_cokernel_desc w := begin apply (is_colimit_cokernel_cocone f).uniq (cofork.of_π g (by simp [w])), rintro (_|_), { convert w.symm, simp }, { exact he } end lemma explicit_cokernel_desc_comp_eq_desc {X Y Z W : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {h : Z ⟶ W} {cond : f ≫ g = 0} : explicit_cokernel_desc cond ≫ h = explicit_cokernel_desc (show f ≫ (g ≫ h) = 0, by rw [← category_theory.category.assoc, cond, limits.zero_comp]) := begin refine explicit_cokernel_desc_unique _ _ _, rw [← category_theory.category.assoc, explicit_cokernel_π_desc] end @[simp] lemma explicit_cokernel_desc_zero {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} : explicit_cokernel_desc (show f ≫ (0 : Y ⟶ Z) = 0, from category_theory.limits.comp_zero) = 0 := eq.symm $ explicit_cokernel_desc_unique _ _ category_theory.limits.comp_zero @[ext] lemma explicit_cokernel_hom_ext {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} (e₁ e₂ : explicit_cokernel f ⟶ Z) (h : explicit_cokernel_π f ≫ e₁ = explicit_cokernel_π f ≫ e₂) : e₁ = e₂ := begin let g : Y ⟶ Z := explicit_cokernel_π f ≫ e₂, have w : f ≫ g = 0, by simp, have : e₂ = explicit_cokernel_desc w, { apply explicit_cokernel_desc_unique, refl }, rw this, apply explicit_cokernel_desc_unique, exact h, end instance explicit_cokernel_π.epi {X Y : SemiNormedGroup.{u}} {f : X ⟶ Y} : epi (explicit_cokernel_π f) := begin constructor, intros Z g h H, ext x, obtain ⟨x, hx⟩ := explicit_cokernel_π_surjective (explicit_cokernel_π f x), change (explicit_cokernel_π f ≫ g) _ = _, rw [H] end lemma is_quotient_explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : normed_group_hom.is_quotient (explicit_cokernel_π f) := normed_group_hom.is_quotient_quotient _ lemma norm_noninc_explicit_cokernel_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : (explicit_cokernel_π f).norm_noninc := (is_quotient_explicit_cokernel_π f).norm_le open_locale nnreal lemma explicit_cokernel_desc_norm_le_of_norm_le {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) (c : ℝ≥0) (h : ∥ g ∥ ≤ c) : ∥ explicit_cokernel_desc w ∥ ≤ c := normed_group_hom.lift_norm_le _ _ _ h lemma explicit_cokernel_desc_norm_noninc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {cond : f ≫ g = 0} (hg : g.norm_noninc) : (explicit_cokernel_desc cond).norm_noninc := begin refine normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2 _, rw [← nnreal.coe_one], exact explicit_cokernel_desc_norm_le_of_norm_le cond 1 (normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1 hg) end lemma explicit_cokernel_desc_comp_eq_zero {X Y Z W : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} {h : Z ⟶ W} (cond : f ≫ g = 0) (cond2 : g ≫ h = 0) : explicit_cokernel_desc cond ≫ h = 0 := begin rw [← cancel_epi (explicit_cokernel_π f), ← category.assoc, explicit_cokernel_π_desc], simp [cond2] end lemma explicit_cokernel_desc_norm_le {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : ∥ explicit_cokernel_desc w ∥ ≤ ∥ g ∥ := explicit_cokernel_desc_norm_le_of_norm_le w ∥ g ∥₊ (le_refl _) /-- The explicit cokernel is isomorphic to the usual cokernel. -/ def explicit_cokernel_iso {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : explicit_cokernel f ≅ cokernel f := (is_colimit_cokernel_cocone f).cocone_point_unique_up_to_iso (colimit.is_colimit _) @[simp] lemma explicit_cokernel_iso_hom_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : explicit_cokernel_π f ≫ (explicit_cokernel_iso f).hom = cokernel.π _ := by simp [explicit_cokernel_π, explicit_cokernel_iso] @[simp] lemma explicit_cokernel_iso_inv_π {X Y : SemiNormedGroup.{u}} (f : X ⟶ Y) : cokernel.π f ≫ (explicit_cokernel_iso f).inv = explicit_cokernel_π f := by simp [explicit_cokernel_π, explicit_cokernel_iso] @[simp] lemma explicit_cokernel_iso_hom_desc {X Y Z : SemiNormedGroup.{u}} {f : X ⟶ Y} {g : Y ⟶ Z} (w : f ≫ g = 0) : (explicit_cokernel_iso f).hom ≫ cokernel.desc f g w = explicit_cokernel_desc w := begin ext1, simp [explicit_cokernel_desc, explicit_cokernel_π, explicit_cokernel_iso], end /-- A special case of `category_theory.limits.cokernel.map` adapted to `explicit_cokernel`. -/ noncomputable def explicit_cokernel.map {A B C D : SemiNormedGroup.{u}} {fab : A ⟶ B} {fbd : B ⟶ D} {fac : A ⟶ C} {fcd : C ⟶ D} (h : fab ≫ fbd = fac ≫ fcd) : explicit_cokernel fab ⟶ explicit_cokernel fcd := @explicit_cokernel_desc _ _ _ fab (fbd ≫ explicit_cokernel_π _) $ by simp [reassoc_of h] /-- A special case of `category_theory.limits.cokernel.map_desc` adapted to `explicit_cokernel`. -/ lemma explicit_coker.map_desc {A B C D B' D' : SemiNormedGroup.{u}} {fab : A ⟶ B} {fbd : B ⟶ D} {fac : A ⟶ C} {fcd : C ⟶ D} {h : fab ≫ fbd = fac ≫ fcd} {fbb' : B ⟶ B'} {fdd' : D ⟶ D'} {condb : fab ≫ fbb' = 0} {condd : fcd ≫ fdd' = 0} {g : B' ⟶ D'} (h' : fbb' ≫ g = fbd ≫ fdd'): explicit_cokernel_desc condb ≫ g = explicit_cokernel.map h ≫ explicit_cokernel_desc condd := begin delta explicit_cokernel.map, simp [← cancel_epi (explicit_cokernel_π fab), category.assoc, explicit_cokernel_π_desc, h'] end end explicit_cokernel end cokernel end SemiNormedGroup
b720c60569742ab03af9c8d60adbd5e8e644274b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Do.lean
847791bc12f5d562ff13afe960ba766a3e8c3efd
[ "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
72,794
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 open TSyntax.Compat private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == ``Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == ``Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtin_term_elab 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 == ``Parser.Term.do || k == ``Parser.Term.doSeqIndent || k == ``Parser.Term.doSeqBracketed || k == ``Parser.Term.termReturn || k == ``Parser.Term.termUnless || k == ``Parser.Term.termTry || k == ``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 == ``Parser.Term.letPatDecl then false else if k == ``Parser.Term.letEqnsDecl then true else if k == ``Parser.Term.letIdDecl then -- letIdLhs := binderIdent >> checkWsBefore "expected space before binders" >> many (ppSpace >> letIdBinder)) >> 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 == ``Parser.Term.fun || k == ``Parser.Term.matchAlts || k == ``Parser.Term.doLetRec || k == ``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 == ``Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``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 == ``Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr returnType : Expr expectedType : Expr private def mkUnknownMonadResult : MetaM ExtractMonadResult := do let u ← mkFreshLevelMVar let v ← mkFreshLevelMVar let m ← mkFreshExprMVar (← mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v))) let returnType ← mkFreshExprMVar (mkSort (mkLevelSucc u)) return { m, returnType, expectedType := mkApp m returnType } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do let some expectedType := expectedType? | mkUnknownMonadResult let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do let .app m returnType := type | return none try let bindInstType ← mkAppM ``Bind #[m] discard <| Meta.synthInstance bindInstType return some { m, returnType, expectedType } catch _ => 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 mkUnknownMonadResult else 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 abbrev Var := Syntax -- TODO: should be `Ident` /-- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Var 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 Var) (doElem : Syntax) (k : Code) | reassign (xs : Array Var) (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 (Var × 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 Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | match (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited def Code.getRef? : Code → Option Syntax | .decl _ doElem _ => doElem | .reassign _ doElem _ => doElem | .joinpoint .. => none | .seq a _ => a | .action a => a | .break ref => ref | .continue ref => ref | .return ref _ => ref | .ite ref .. => ref | .match ref .. => ref | .jmp ref .. => ref abbrev VarSet := RBMap Name Syntax Name.cmp /-- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : VarSet := {} -- set of variables updated by `code` private def varSetToArray (s : VarSet) : Array Var := s.fold (fun xs _ x => xs.push x) #[] private def varsToMessageData (vars : Array Var) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax let rec loop : Code → MessageData | .decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | .reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | .joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | .seq e k => m!"{e}\n{loop k}" | .action e => e | .ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | .jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | .break _ => m!"break {us}" | .continue _ => m!"continue {us}" | .return _ v => m!"return {v} {us}" | .match _ _ ds _ 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 | .decl _ _ k => loop k | .reassign _ _ k => loop k | .joinpoint _ _ b k => loop b || loop k | .seq _ k => loop k | .ite _ _ _ _ t e => loop t || loop e | .match _ _ _ _ alts => alts.any (loop ·.rhs) | .jmp .. => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun _ => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | .return .. => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | .action _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | .break _ => true | .continue _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | .break _ => true | .continue _ => true | .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 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 return .decl #[y] 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 Var) : MacroM Code := let rec loop : Code → MacroM Code | .decl xs stx k => return .decl xs stx (← loop k) | .reassign xs stx k => return .reassign xs stx (← loop k) | .joinpoint n ps b k => return .joinpoint n ps (← loop b) (← loop k) | .seq e k => return .seq e (← loop k) | .ite ref x? h c t e => return .ite ref x? h c (← loop t) (← loop e) | .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | .action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.push y return Code.jmp ref jp jmpArgs | c => return c loop code structure JPDecl where name : Name params : Array (Var × 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 (Var × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← `(y) pure #[(y.raw, 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 addFreshJP (ps : Array (Var × 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 : VarSet) (xs : Array Var) : VarSet := xs.foldl (fun rs x => rs.insert x.getId x) rs def eraseVars (rs : VarSet) (xs : Array Var) : VarSet := xs.foldl (·.erase ·.getId) rs def eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet := match x? with | none => rs | some x => rs.insert x.getId x /-- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := varSetToArray 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 /-- 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 : VarSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := varSetToArray rs let args := xs.push val let yFresh ← withRef ref `(y) let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM <| mkJPBody yFresh let jp ← addFreshJP ps jpBody return 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 (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := match c with | .decl xs stx k => return .decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | .reassign xs stx k => return .reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | .joinpoint j ps b k => return .joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | .seq e k => return .seq e (← pullExitPointsAux rs k) | .ite ref x? o c t e => return .ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | .jmp .. => return c | .break ref => mkSimpleJmp ref rs (.break ref) | .continue ref => mkSimpleJmp ref rs (.continue ref) | .return ref val => mkJmp ref rs val (fun y => return .return ref y) | .action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => return .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 #[] return attachJPs jpDecls c else return c partial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code := let rec update (c : Code) : TermElabM Code := do match c with | .joinpoint j ps b k => return .joinpoint j ps (← update b) (← update k) | .seq e k => return .seq e (← update k) | .match ref g ds t alts => if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | .ite ref none o c t e => return .ite ref none o c (← update t) (← update e) | .ite ref (some h) o cond t e => if ws.contains h.getId then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else return Code.ite ref (some h) o cond (← update t) (← update e) | .reassign xs stx k => return .reassign xs stx (← update k) | .decl xs stx k => do if xs.any fun x => ws.contains x.getId then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else return .decl xs stx (← update k) | c => return 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 : VarSet) : 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₂ : VarSet) : VarSet := 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 Var) (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 Var) (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.getId then extendUpdatedVarsAux c.code ws else pure c.code pure { code := .reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := .seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := .action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := .return ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := .break ref } def mkContinue (ref : Syntax) : CodeBlock := { code := .continue ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := optIdent.getOptional? let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch return { 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 return mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction return { c with code := .ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : 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 return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } return { code := .match ref genParam discrs optMotive 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 Var) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "`do` element is unreachable" let (terminal, k) ← homogenize terminal k let xs := varSetToArray k.uvars let y ← match y? with | some y => pure y | none => `(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 return { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVars (letIdDecl : Syntax) : Array Var := if letIdDecl[0].isIdent then #[letIdDecl[0]] else #[] -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) := getPatternVars pattern <|> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) := getPatternsVars patterns <|> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVars (letEqnsDecl : Syntax) : Array Var := if letEqnsDecl[0].isIdent then #[letEqnsDecl[0]] else #[] def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do let arg := letDecl[0] if arg.getKind == ``Parser.Term.letIdDecl then return getLetIdDeclVars arg else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Parser.Term.letEqnsDecl then return getLetEqnsDeclVars arg else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Var) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getHaveIdLhsVar (optIdent : Syntax) : Var := if optIdent.getKind == hygieneInfoKind then HygieneInfo.mkIdent optIdent[0] `this else optIdent def getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do -- doHave := leading_parser "have " >> Term.haveDecl -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl let arg := doHave[1][0] if arg.getKind == ``Parser.Term.haveIdDecl then -- haveIdDecl := leading_parser atomic (haveIdLhs >> " := ") >> termParser -- haveIdLhs := (binderIdent <|> hygieneInfo) >> many letIdBinder >> optType return #[getHaveIdLhsVar arg[0]] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Parser.Term.haveEqnsDecl then -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts return #[getHaveIdLhsVar arg[0]] else throwError "unexpected kind of have declaration" def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := 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 return allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Var := doIdDecl[0] -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do let decl := doLetArrow[2] if decl.getKind == ``Parser.Term.doIdDecl then return #[getDoIdDeclVar decl] else if decl.getKind == ``Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of `do` declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do let arg := doReassign[0] if arg.getKind == ``Parser.Term.letIdDecl then return getLetIdDeclVars arg else if arg.getKind == ``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]] /-- If the given syntax is a `doIf`, return an equivalent `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 $_:doIfProp then $_ else $_) => pure none | `(doElem|if $cond:doIfCond then $t $[else if $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (cond, t) in Array.zip (conds.reverse.push cond) (ts.reverse.push t) do e ← if eIsSeq then pure e else `(doSeq|$e:doElem) e ← match cond with | `(doIfCond|let $pat := $d) => `(doElem| match $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if $cond:doIfProp then $t else $e) | _ => `(doElem| if $(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) : DoIfView := { 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 return elems[0]! else elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple => ``(MProd.mk $elem $tuple) /-- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == ``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 Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(uvars[0]!):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $a:ident := $x.1; let $b:ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $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` -/ /-- Helper method for annotating `term` with the raw syntax `ref`. We use this method to implement finer-grained term infos for `do`-blocks. We use `withRef term` to make sure the synthetic position for the `with_annotate_term` is equal to the one for `term`. This is important for producing error messages when there is a type mismatch. Consider the following example: ``` opaque f : IO Nat def g : IO String := do f ``` There is at type mismatch at `f`, but it is detected when elaborating the expanded term containing the `with_annotate_term .. f`. The current `getRef` when this `annotate` is invoked is not necessarily `f`. Actually, it is the whole `do`-block. By using `withRef` we ensure the synthetic position for the `with_annotate_term ..` is equal to `term`. Recall that synthetic positions are used when generating error messages. -/ def annotate [Monad m] [MonadRef m] [MonadQuotation m] (ref : Syntax) (term : Syntax) : m Syntax := withRef term <| `(with_annotate_term $ref $term) namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | .regular => true | _ => false structure Context where /-- Syntax to reference the monad associated with the do notation. -/ m : Syntax /-- Syntax to reference the result of the monadic computation performed by the do notation. -/ returnType : Syntax uvars : Array Var kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read mkTuple ctx.uvars def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | .forIn => ``(Pure.pure (ForInStep.done $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | .nestedBC => unreachable! | .nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | .nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => unreachable! | .forIn => ``(Pure.pure (ForInStep.yield $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | .nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | .nestedPR => unreachable! | .nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => unreachable! | .forIn => ``(Pure.pure (ForInStep.done $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | .nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | .nestedPR => unreachable! | .nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | .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 | .regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | .forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | .forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | .nestedBC => unreachable! | .nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | .nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | .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 == ``Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == ``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 == ``Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == ``Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] return mkNode ``Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == ``Parser.Term.doLetArrow then let arg := decl[2] if arg.getKind == ``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 == ``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] return 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 match reassign with | `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote "invalid reassignment, value") $rhs; $k) | `(doElem| $e:term := $rhs) => `(let $e:term := ensure_type_of% $e $(quote "invalid reassignment, value") $rhs; $k) | _ => -- 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 (Syntax × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $id) else `(_) let ps := ps.map (·.1) /- 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 (c : Code) : M Syntax := do let term ← go c if let some ref := c.getRef? then annotate ref term else return term where go (c : Code) : M Syntax := do match c with | .return ref val => withRef ref <| returnToTerm val | .continue ref => withRef ref continueToTerm | .break ref => withRef ref breakToTerm | .action e => actionTerminalToTerm e | .joinpoint j ps b k => mkJoinPoint j ps (← toTerm b) (← toTerm k) | .jmp ref j args => return mkJmp ref j args | .decl _ stx k => declToTerm stx (← toTerm k) | .reassign _ stx k => reassignToTerm stx (← toTerm k) | .seq stx k => seqToTerm stx (← toTerm k) | .ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | .match ref genParam discrs optMotive alts => let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", mkNullNode #[alt.patterns], mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] return mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, optMotive, discrs, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax := toTerm code { m, returnType, kind, uvars } /-- 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 => .regular | false, true, false => .regular | false, false, true => .nestedBC | true, true, false => .nestedPR | true, false, true => .nestedSBC | false, true, true => .nestedSBC | true, true, true => .nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m returnType 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 Var) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple uvars match a, r, bc with | true, false, false => if uvars.isEmpty then return toDoElems (← `(do $term:term)) else return toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then return toDoElems (← `(do let r ← $term:term; return r)) else return 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 | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | .pure a u => $u:term := u; pure a | .return b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | .pureReturn a u => $u:term := u; pure a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | .pureReturn a u => $u:term := u; return a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | .pure a u => $u:term := u; pure a | .return a u => $u:term := u; return a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == ``doLetArrow || kind == ``doLet || kind == ``doLetElse) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax /-- Syntax representing the monad associated with the do notation. -/ m : Syntax /-- Syntax to reference the result of the monadic computation performed by the do notation. -/ returnType : Syntax mutableVars : VarSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM def withNewMutableVars {α} (newVars : Array Var) (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 Var) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "`{x.simpMacroScopes}` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intent to mutate but define `{x.simpMacroScopes}`, consider using `let {x.simpMacroScopes}` instead" let ctx ← read for x in xs do unless ctx.mutableVars.contains x.getId do throwInvalidReassignment x.getId def checkNotShadowingMutable (xs : Array Var) : 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.getId then withRef x <| throwInvalidShadowing x.getId def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Var term : Syntax def mkForInBody (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := varSetToArray uvars let term ← liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) return ⟨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" variable (baseId : Name) in private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax | stx@(Syntax.node i k args) => if k == choiceKind then do -- choice node: check that lifts are consistent let alts ← stx.getArgs.mapM (expandLiftMethodAux inQuot inBinder · |>.run []) let (_, lifts) := alts[0]! unless alts.all (·.2 == lifts) do throwErrorAt stx "cannot lift `(<- ...)` over inconsistent syntax variants, consider lifting out the binding manually" modify (· ++ lifts) return .node i k (alts.map (·.1)) else if liftMethodDelimiter k then return stx else if k == ``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 -- keep name deterministic across choice branches let id ← mkIdentFromRef (.num baseId (← get).length) let auxDoElem : Syntax ← `(doElem| let $id:ident ← $term:term) modify fun s => s ++ [auxDoElem] return id 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 => return stx def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do if !hasLiftMethod doElem then return ([], doElem) else let baseId ← withFreshMacroScope (MonadQuotation.addMacroScope `__do_lift) let (doElem, doElemsNew) ← (expandLiftMethodAux baseId false false doElem).run [] return (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == ``Parser.Term.doLetArrow || kind == ``Parser.Term.doLet || kind == ``Parser.Term.doLetRec || kind == ``Parser.Term.doHave || kind == ``Parser.Term.doReassign || kind == ``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) : VarSet := let ws := tryCode.uvars let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars 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 (" | " >> doSeq) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let decl := doLetArrow[2] if decl.getKind == ``Parser.Term.doIdDecl then let y := decl[0] checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some _ => return 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 == ``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%$doLetArrow __discr ← $doElem; let%$doLetArrow mut $pattern:term := __discr) else `(do let%$doLetArrow __discr ← $doElem; let%$doLetArrow $pattern:term := __discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else let contSeq ← if isMutableLet doLetArrow then let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var) pure (vars ++ doElems.toArray) else pure doElems.toArray let contSeq := mkDoSeq contSeq let elseSeq := optElse[1] let auxDo ← `(do let%$doLetArrow __discr ← $doElem; match%$doLetArrow __discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of `do` declaration" partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do -- "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doSeq let pattern := doLetElse[2] let val := doLetElse[4] let elseSeq := doLetElse[6] let contSeq ← if isMutableLet doLetElse then let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var) pure (vars ++ doElems.toArray) else pure doElems.toArray let contSeq := mkDoSeq contSeq let auxDo ← `(do let __discr := $val; match __discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) /-- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let decl := doReassignArrow[0] if decl.getKind == ``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 == ``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 := 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 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]! unless doForDecl[0].isNone do throwErrorAt doForDecl[0] "the proof annotation here has not been implemented yet" let y := doForDecl[1] let ys := doForDecl[3] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do /- Recall that `@` (explicit) disables `coeAtOutParam`. We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/ let toStreamApp ← withRef ys `(@toStream _ _ _ $ys) let auxDo ← `(do let mut s := $toStreamApp:term 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 h? := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0] let x := doForDecls[0]![1] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0]![3] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let ctx ← read -- semantic no-op that replaces the `uvars`' position information (which all point inside the loop) -- with that of the respective mutable declarations outside the loop, which allows the language -- server to identify them as conceptually identical variables let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v let uvarsTuple ← liftMacroM do mkTuple uvars if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let optType ← `(Option $((← read).returnType)) let forInTerm ← if let some h := h? then annotate doFor (← `(for_in'% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody)) else annotate doFor (← `(for_in% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => 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 ← if let some h := h? then annotate doFor (← `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody)) else annotate doFor (← `(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 optMotive := doMatch[2] let discrs := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let matchAlts ← matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (← liftMacroM <| expandMatchAlt matchAlt) let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1][0] 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 optMotive 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 tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx : Syntax => do if catchStx.getKind == ``Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) return { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == ``Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) return { 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 := varSetToArray 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 ctx.returnType uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (init := term) fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then annotate doTry (← ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm))) else let type := «catch».optType[1] annotate doTry (← ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) 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 ctx.returnType {} ToTerm.Kind.regular annotate doTry (← ``(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 k := doElem.getKind if k == ``Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == ``Parser.Term.doHave then let vars ← getDoHaveVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == ``Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == ``Parser.Term.doLetElse then doLetElseToCode doElem doElems else if k == ``Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == ``Parser.Term.doIf then doIfToCode doElem doElems else if k == ``Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == ``Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == ``Parser.Term.doMatch then doMatchToCode doElem doElems else if k == ``Parser.Term.doTry then doTryToCode doElem doElems else if k == ``Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == ``Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == ``Parser.Term.doReturn then doReturnToCode doElem doElems else if k == ``Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == ``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) (returnType : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType } end ToCodeBlock @[builtin_term_elab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← Term.exprToSyntax bindInfo.m let returnType ← Term.exprToSyntax bindInfo.returnType let codeBlock ← ToCodeBlock.run stx m returnType let stxNew ← liftMacroM <| ToTerm.run codeBlock.code m returnType 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) @[builtin_macro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem ``Parser.Term.doFor @[builtin_macro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem ``Parser.Term.doTry @[builtin_macro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem ``Parser.Term.doUnless @[builtin_macro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem ``Parser.Term.doReturn end Lean.Elab.Term
3fb842b168e40c556268fb9431cb2199c09c68e9
d320d01276642370017b4ce56793b5f73e0016f9
/lean projects and notes/12.3.lean
f52d38e2a568c5f9edc35573dddc31da5e6296f1
[]
no_license
samiazam00/my-work
388d815ddc7e47860375959ba31be2530be7f11e
e9a8218b2441dce00bf117d3d985d00e6ee14ec0
refs/heads/master
1,608,518,076,248
1,580,268,523,000
1,580,268,523,000
236,280,156
0
0
null
null
null
null
UTF-8
Lean
false
false
942
lean
axiom P : Prop axiom Q : Prop axiom q : Q --assume Q is a proposition and q is a proof of Q -- 2 induction rules for OR: or.inl takes a proof of P and returns a proof of P v Q -- inr takes a proof of Q and returns a proof of P v Q (ex of polymorphism) example : P ∨ Q := or.inr q -- ima, kono bishounen wa watashi no tonari ni suwaru..... -- uwaa chotto kinchou suruuuu, kare no me wa meccha kakkoiiii -- soshite, kare no hada wa kireiii kyaaaahh example : 0 = 1 ∨ 2 = 2 := or.inr (eq.refl 2) example : (P ∧ Q) ∨ Q := or.inr q --Constructive Logic: example : P ∨ ¬ P := begin _ end --Classical Logic axiom em : ∀ (P: Prop), P ∨ ¬ P #check em --for any propositon P, not not P implies P (¬ ¬ P = true if P = true) example : ∀ (P : Prop), ¬ (¬ P) → P := begin assume P, assume (nnp : ¬ ¬ P), cases (em P), exact h, have f : false := (nnp h), exact false.elim f end
6a21c8f9bddb225ebe1fab734367f9875a04fc1e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/imo/imo2020_q2.lean
beea58a78ff17093d90a4438e21ab6acb9fa5b87
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,201
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import analysis.mean_inequalities /-! # IMO 2020 Q2 The real numbers `a`, `b`, `c`, `d` are such that `a ≥ b ≥ c ≥ d > 0` and `a + b + c + d = 1`. Prove that `(a + 2b + 3c + 4d) a^a b^b c^c d^d < 1`. A solution is to eliminate the powers using weighted AM-GM and replace `1` by `(a+b+c+d)^3`, leaving a homogeneous inequality that can be proved in many ways by expanding, rearranging and comparing individual terms. The version here using factors such as `a+3b+3c+3d` is from the official solutions. -/ open real theorem imo2020_q2 (a b c d : ℝ) (hd0 : 0 < d) (hdc : d ≤ c) (hcb : c ≤ b) (hba : b ≤ a) (h1 : a + b + c + d = 1) : (a + 2 * b + 3 * c + 4 * d) * a ^ a * b ^ b * c ^ c * d ^ d < 1 := begin have hp : a ^ a * b ^ b * c ^ c * d ^ d ≤ a * a + b * b + c * c + d * d, by refine geom_mean_le_arith_mean4_weighted _ _ _ _ _ _ _ _ h1; linarith, calc (a + 2 * b + 3 * c + 4 * d) * a ^ a * b ^ b * c ^ c * d ^ d = (a + 2 * b + 3 * c + 4 * d) * (a ^ a * b ^ b * c ^ c * d ^ d) : by ac_refl ... ≤ (a + 2 * b + 3 * c + 4 * d) * (a * a + b * b + c * c + d * d) : mul_le_mul_of_nonneg_left hp (by linarith) ... = (a + 2 * b + 3 * c + 4 * d) * (a * a) + (a + 2 * b + 3 * c + 4 * d) * (b * b) + (a + 2 * b + 3 * c + 4 * d) * (c * c) + (a + 2 * b + 3 * c + 4 * d) * (d * d) : by simp only [mul_add] ... ≤ (a + 3 * b + 3 * c + 3 * d) * (a * a) + (3 * a + b + 3 * c + 3 * d) * (b * b) + (3 * a + 3 * b + c + 3 * d) * (c * c) + (3 * a + 3 * b + 3 * c + d) * (d * d) : by apply_rules [add_le_add]; refine mul_le_mul_of_nonneg_right _ (mul_self_nonneg _); linarith ... < (a + 3 * b + 3 * c + 3 * d) * (a * a) + (3 * a + b + 3 * c + 3 * d) * (b * b) + (3 * a + 3 * b + c + 3 * d) * (c * c) + (3 * a + 3 * b + 3 * c + d) * (d * d) + (6 * a * b * c + 6 * a * b * d + 6 * a * c * d + 6 * b * c * d) : lt_add_of_pos_right _ (by apply_rules [add_pos, mul_pos, zero_lt_one]; linarith) ... = (a + b + c + d) ^ 3 : by ring ... = 1 : by simp [h1] end
d920e4f747b8f4c6c43d3e3e18b3c3d0789c79b0
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/646.lean
71b49d0a9e1fe0572af0b03b6698225e01e7ea68
[ "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
383
lean
def build (n : Nat) : Array Unit := Id.run <| do let mut out := #[] for _ in [0:n] do out := out.push () out @[noinline] def size : IO Nat := pure 50000 def bench (f : ∀ {α : Type}, α → IO Unit := fun _ => ()) : IO Unit := do let n ← size let arr := build n timeit "time" $ for _ in [:1000] do f $ #[1, 2, 3, 4].map fun ty => arr[ty] #eval bench
11f4e51f6df12bcdff49ab5860a510f5d0f683df
359199d7253811b032ab92108191da7336eba86e
/src/mywork/mid-term_exam_practice.lean
1ca9191916965f97603b78fa418ac6ad331891e7
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
1,866
lean
axiom eq_refl : ∀ (T : Type) (t : T), t = t axiom eq_subst : ∀ (T : Type) (P : T → Prop) (x y : T) (e : x = y) (px : P x), P y theorem eq_symm : ∀ (T : Type) (x y : T), x = y → y = x := begin assume T, assume x y, assume x_equals_y, apply eq.subst x_equals_y, apply eq.refl, end theorem eq_trans : ∀ (T : Type) (x y z : T), x = y → y = z → x = z := begin assume T, assume x y z, assume x_equals_y, assume y_equals_z, rw x_equals_y, exact y_equals_z, end ----- -- Implies intro rule: -- Implies elim rule: /- (P Q : Prop) (pq : P → Q) (p : P) --------------------------------- → elim q : Q -/ -- Forall intro rule: -- Forall elim rule: /- (T : Type) (P : T → Prop) (a : ∀ (x : T), P x) (t : T) ------------------------------------------------------ ∀ elim pf: P t -/ ----- /- (P Q : Prop) (p : P) (q : Q) ---------------------------- ∧ intro ⟨p, q⟩ : P ∧ Q (P Q : Prop) (pq : P ∧ Q) ------------------------- ∧ elim (left) p : P (P Q : Prop) (pq : P ∧ Q) ------------------------- ∧ elim (right) q : Q and is comm, and is assoc -/ theorem and_commu : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q, assume p_and_q, cases p_and_q with p q, apply and.intro q p, --apply and.intro _ _, --apply and.elim_right p_and_q, --apply and.elim_left p_and_q, end theorem and_associ : ∀ (P Q R : Prop), P ∧ (Q ∧ R) → (P ∧ Q) ∧ R := begin assume P Q R, assume h, cases h with p qandr, cases qandr with q r, apply and.intro (and.intro p q) r, -- have end theorem and_associ2 : ∀ (P Q R : Prop), (P ∧ Q) ∧ R → P ∧ (Q ∧ R) := begin assume P Q R h, cases h with pandq r, cases pandq with p q, apply and.intro p (and.intro q r), end -- why no type arg for and -- right assoc
6f9cf2f77e3c469cb0192010301d943d14ee80d3
4376c25f060c13471bb89cdb12aeac1d53e53876
/src/espaces-metriques/custom/sups.lean
f6f7c185fbb8180c42de5334769feea2eb9af7af
[ "MIT" ]
permissive
RaitoBezarius/projet-maths-lean
8fa7df563d64c256561ab71893c523fc1424b85c
42356e980e021a20c3468f5ca1639fec01bb934f
refs/heads/master
1,613,002,128,339
1,589,289,282,000
1,589,289,282,000
244,431,534
0
1
MIT
1,584,312,574,000
1,583,169,883,000
TeX
UTF-8
Lean
false
false
3,283
lean
import tactic import data.set import .sequences import .topology import .negative_sets noncomputable theory open_locale classical open espace_metrique namespace real lemma Sup_sub_lt_eps {S: set ℝ}: S.nonempty → bdd_above S → ∀ ε > 0, ∃ x ∈ S, Sup S - x < ε := begin intros Hne Hbdd, by_contra, push_neg at a, obtain ⟨ ε, ⟨ hε, hyp ⟩ ⟩ := a, have: ∀ (x: ℝ), x ∈ S → x ≤ Sup S - ε := begin intros x hx, have hyp := hyp x hx, linarith, end, have habsurd := cSup_le Hne this, linarith, end lemma Sup_dist_lt_eps {S: set ℝ}: S.nonempty → bdd_above S → ∀ ε > 0, ∃ x ∈ S, d (Sup S) x < ε := begin intros Hne Hbdd, intros ε hε, obtain ⟨ x, hx, hs_lt ⟩ := Sup_sub_lt_eps Hne Hbdd ε hε, use x, split, exact hx, rw dist_eq, apply abs_lt_of_lt_of_neg_lt, exact hs_lt, calc -(Sup S - x) = x - Sup S : by simp ... ≤ Sup S - Sup S : (sub_le_sub_right (le_cSup Hbdd hx) (Sup S)) ... ≤ 0 : by simp ... < ε : hε end lemma Sup_is_a_cv_seq (S: set ℝ): S.nonempty → bdd_above S → adhere_ens S (Sup S) := begin intros hnn hbdd, have: ∀ (N: ℕ), ∃ x ∈ S, d (Sup S) x ≤ 1/(N + 1) := λ N, let ⟨ x, ha, hb ⟩ := (Sup_dist_lt_eps hnn hbdd (1 / (N + 1)) (nat.one_div_pos_of_nat)) in ⟨ x, ⟨ ha, le_of_lt hb ⟩ ⟩, choose x hrange h using this, use x, split, exact hrange, exact converge_of_dist_lt_one_div_succ h, end -- suffit de prendre une suite qui converge vers Sup S -- puis de prendre la suite opposée, qui converge vers -Sup S = Inf S lemma Inf_is_a_cv_seq (S: set ℝ): S.nonempty → bdd_below S → adhere_ens S (Inf S) := begin intros Hne Hbdd, apply negative_set.adhere_ens_iff.2, rw Inf_def, simp, exact Sup_is_a_cv_seq (negative_set S) (negative_set.nonempty Hne) (negative_set.bdd_above Hbdd) end -- sous hypothèse que le sup ou l'inf ne sont pas dans l'ensemble, ils forment des points limites. lemma Sup_is_a_limit_point (S: set ℝ): (Sup S) ∉ S → S.nonempty → bdd_above S → point_limite S (Sup S) := begin intros hsup hne hbdd, obtain ⟨ x, hrange, hcv ⟩ := Sup_is_a_cv_seq S hne hbdd, use x, split, rw set.diff_singleton_eq_self, exact hrange, exact hsup, exact hcv end lemma Inf_is_a_limit_point (S: set ℝ): (Inf S) ∉ S → S.nonempty → bdd_below S → point_limite S (Inf S) := begin intros hinf hne hbdd, obtain ⟨ x, hrange, hcv ⟩ := real.Inf_is_a_cv_seq S hne hbdd, use x, split, rw set.diff_singleton_eq_self, exact hrange, exact hinf, exact hcv end end real namespace set.finite variables {X: Type} lemma has_greatest_element [decidable_linear_order X] (S: set X): S.finite → S.nonempty → ∃ x ∈ S, is_greatest S x := begin intros Hf Hnn, lift S to (finset X) using Hf, use (finset.max' S Hnn), have Hmem := finset.max'_mem S Hnn, split, exact Hmem, rw is_greatest, split, exact Hmem, rw upper_bounds, simp, exact finset.le_max' S Hnn, end lemma has_a_reached_sup [conditionally_complete_linear_order X] {S: set X}: S.finite → S.nonempty → Sup S ∈ S := begin intros Hf Hnn, obtain ⟨ x, Hmem, Hgt ⟩ := (has_greatest_element S Hf Hnn), rw is_greatest.cSup_eq Hgt, exact Hmem, end end set.finite
f5dc29983d33ce7b626ece180c54bf8e30ca55b7
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world7/level7.lean
c483c736c1745e91b3eb4137354ac9b0dea6549e
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
807
lean
/- # Advanced proposition world. ## Level 7: `or_symm` Proving that $(P\lor Q)\implies(Q\lor P)$ involves an element of danger. `intro h,` is the obvious start. But now, even though the goal is an `∨` statement, both `left` and `right` put you in a situation with an impossible goal. Fortunately, after `intro h,` you can do `cases h with p q`. Then something new happens: because there are two ways to prove `P ∨ Q` (namely, proving `P` or proving `Q`), the `cases` tactic turns one goal into two, one for each case. You should be able to make it home from there. -/ /- Lemma If $P$ and $Q$ are true/false statements, then $$P\lor Q\implies Q\lor P.$$ -/ lemma or_symm (P Q : Prop) : P ∨ Q → Q ∨ P := begin intro h, cases h with p q, right, exact p, left, exact q, end
ceb32a0ef70e6cf84f1ca73f3762b55715a21867
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/list/nodup.lean
15189781d546c19444ee280113d1fc3cd1decc10
[ "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
11,500
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.pairwise import data.list.forall2 universes u v open nat function variables {α : Type u} {β : Type v} namespace list /- no duplicates predicate -/ @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {exact nodup_nil}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n))) (not_le_of_lt $ le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup | l₁ [] h := h | l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] lemma nodup_sublists_len {α : Type*} (n) {l : list α} (nd : nodup l) : (sublists_len n l).nodup := nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd) lemma diff_eq_filter_of_nodup [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁), nodup_erase_eq_filter _ hl₁, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm], congr end lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [diff_eq_filter_of_nodup hl₁, mem_filter] lemma nodup_update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), nodup_update_nth (nodup_cons.1 hl).2 (mt (mem_cons_of_mem _) ha)⟩ end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
a658db71613ef05bc6b1ba5110acc706565ac861
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/instances/nnreal.lean
d8441db3f052d799a7c84972554ca902ce53ac1d
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
7,309
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.algebra.infinite_sum import topology.algebra.group_with_zero /-! # Topology on `ℝ≥0` The natural topology on `ℝ≥0` (the one induced from `ℝ`), and a basic API. ## Main definitions Instances for the following typeclasses are defined: * `topological_space ℝ≥0` * `topological_semiring ℝ≥0` * `second_countable_topology ℝ≥0` * `order_topology ℝ≥0` * `has_continuous_sub ℝ≥0` * `has_continuous_inv' ℝ≥0` (continuity of `x⁻¹` away from `0`) Everything is inherited from the corresponding structures on the reals. ## Main statements Various mathematically trivial lemmas are proved about the compatibility of limits and sums in `ℝ≥0` and `ℝ`. For example * `tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x)` says that the limit of a filter along a map to `ℝ≥0` is the same in `ℝ` and `ℝ≥0`, and * `coe_tsum {f : α → ℝ≥0} : ((∑'a, f a) : ℝ) = (∑'a, (f a : ℝ))` says that says that a sum of elements in `ℝ≥0` is the same in `ℝ` and `ℝ≥0`. Similarly, some mathematically trivial lemmas about infinite sums are proved, a few of which rely on the fact that subtraction is continuous. -/ noncomputable theory open set topological_space metric filter open_locale topological_space namespace nnreal open_locale nnreal big_operators instance : topological_space ℝ≥0 := infer_instance -- short-circuit type class inference instance : topological_semiring ℝ≥0 := { continuous_mul := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).mul (continuous_subtype_val.comp continuous_snd), continuous_add := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).add (continuous_subtype_val.comp continuous_snd) } instance : second_countable_topology ℝ≥0 := topological_space.subtype.second_countable_topology _ _ instance : order_topology ℝ≥0 := @order_topology_of_ord_connected _ _ _ _ (Ici 0) _ section coe variable {α : Type*} open filter finset lemma continuous_of_real : continuous real.to_nnreal := continuous_subtype_mk _ $ continuous_id.max continuous_const lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ) := continuous_subtype_val @[simp, norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x) := tendsto_subtype_rng.symm lemma tendsto_coe' {f : filter α} [ne_bot f] {m : α → ℝ≥0} {x : ℝ} : tendsto (λ a, m a : α → ℝ) f (𝓝 x) ↔ ∃ hx : 0 ≤ x, tendsto m f (𝓝 ⟨x, hx⟩) := ⟨λ h, ⟨ge_of_tendsto' h (λ c, (m c).2), tendsto_coe.1 h⟩, λ ⟨hx, hm⟩, tendsto_coe.2 hm⟩ @[simp] lemma map_coe_at_top : map (coe : ℝ≥0 → ℝ) at_top = at_top := map_coe_Ici_at_top 0 lemma comap_coe_at_top : comap (coe : ℝ≥0 → ℝ) at_top = at_top := (at_top_Ici_eq 0).symm @[simp, norm_cast] lemma tendsto_coe_at_top {f : filter α} {m : α → ℝ≥0} : tendsto (λ a, (m a : ℝ)) f at_top ↔ tendsto m f at_top := tendsto_Ici_at_top.symm lemma tendsto_of_real {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (𝓝 x)) : tendsto (λa, real.to_nnreal (m a)) f (𝓝 (real.to_nnreal x)) := (continuous_of_real.tendsto _).comp h instance : has_continuous_sub ℝ≥0 := ⟨continuous_subtype_mk _ $ ((continuous_coe.comp continuous_fst).sub (continuous_coe.comp continuous_snd)).max continuous_const⟩ instance : has_continuous_inv' ℝ≥0 := ⟨λ x hx, tendsto_coe.1 $ (real.tendsto_inv $ nnreal.coe_ne_zero.2 hx).comp continuous_coe.continuous_at⟩ @[norm_cast] lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ)) (r : ℝ) ↔ has_sum f r := by simp only [has_sum, coe_sum.symm, tendsto_coe] lemma has_sum_of_real_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : has_sum (λ n, real.to_nnreal (f n)) (real.to_nnreal (∑' n, f n)) := begin have h_sum : (λ s, ∑ b in s, real.to_nnreal (f b)) = λ s, real.to_nnreal (∑ b in s, f b), from funext (λ _, (real.to_nnreal_sum_of_nonneg (λ n _, hf_nonneg n)).symm), simp_rw [has_sum, h_sum], exact tendsto_of_real hf.has_sum, end @[norm_cast] lemma summable_coe {f : α → ℝ≥0} : summable (λa, (f a : ℝ)) ↔ summable f := begin split, exact assume ⟨a, ha⟩, ⟨⟨a, has_sum_le (λa, (f a).2) has_sum_zero ha⟩, has_sum_coe.1 ha⟩, exact assume ⟨a, ha⟩, ⟨a.1, has_sum_coe.2 ha⟩ end open_locale classical @[norm_cast] lemma coe_tsum {f : α → ℝ≥0} : ↑∑'a, f a = ∑'a, (f a : ℝ) := if hf : summable f then (eq.symm $ (has_sum_coe.2 $ hf.has_sum).tsum_eq) else by simp [tsum, hf, mt summable_coe.1 hf] lemma tsum_mul_left (a : ℝ≥0) (f : α → ℝ≥0) : ∑' x, a * f x = a * ∑' x, f x := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_left] lemma tsum_mul_right (f : α → ℝ≥0) (a : ℝ≥0) : (∑' x, f x * a) = (∑' x, f x) * a := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_right] lemma summable_comp_injective {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : summable (f ∘ i) := nnreal.summable_coe.1 $ show summable ((coe ∘ f) ∘ i), from (nnreal.summable_coe.2 hf).comp_injective hi lemma summable_nat_add (f : ℕ → ℝ≥0) (hf : summable f) (k : ℕ) : summable (λ i, f (i + k)) := summable_comp_injective hf $ add_left_injective k lemma summable_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) : summable (λ i, f (i + k)) ↔ summable f := begin rw [← summable_coe, ← summable_coe], exact @summable_nat_add_iff ℝ _ _ _ (λ i, (f i : ℝ)) k, end lemma has_sum_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) {a : ℝ≥0} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := by simp [← has_sum_coe, coe_sum, nnreal.coe_add, ← has_sum_nat_add_iff k] lemma sum_add_tsum_nat_add {f : ℕ → ℝ≥0} (k : ℕ) (hf : summable f) : ∑' i, f i = (∑ i in range k, f i) + ∑' i, f (i + k) := by rw [←nnreal.coe_eq, coe_tsum, nnreal.coe_add, coe_sum, coe_tsum, sum_add_tsum_nat_add k (nnreal.summable_coe.2 hf)] lemma infi_real_pos_eq_infi_nnreal_pos [complete_lattice α] {f : ℝ → α} : (⨅ (n : ℝ) (h : 0 < n), f n) = (⨅ (n : ℝ≥0) (h : 0 < n), f n) := le_antisymm (infi_le_infi2 $ assume r, ⟨r, infi_le_infi $ assume hr, le_rfl⟩) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, hr.le⟩ $ infi_le _ hr) end coe lemma tendsto_cofinite_zero_of_summable {α} {f : α → ℝ≥0} (hf : summable f) : tendsto f cofinite (𝓝 0) := begin have h_f_coe : f = λ n, real.to_nnreal (f n : ℝ), from funext (λ n, real.to_nnreal_coe.symm), rw [h_f_coe, ← @real.to_nnreal_coe 0], exact tendsto_of_real ((summable_coe.mpr hf).tendsto_cofinite_zero), end lemma tendsto_at_top_zero_of_summable {f : ℕ → ℝ≥0} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_summable hf } end nnreal
5be39c2ed6d905ad23ce06dc8f3661cf008a0bed
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/multiset/nodup.lean
4ef37e295db88e1bcf7c2ba23f09384d37b7c766
[ "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
9,991
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.bind import data.multiset.powerset import data.multiset.range /-! # The `nodup` predicate for multisets without duplicate elements. -/ namespace multiset open list variables {α β γ : Type*} /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext p.nodup_iff) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a ::ₘ s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup ({a} : multiset α) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a ::ₘ a ::ₘ 0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a ::ₘ a ::ₘ 0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm lemma nodup_iff_ne_cons_cons {s : multiset α} : s.nodup ↔ ∀ a t, s ≠ a ::ₘ a ::ₘ t := nodup_iff_le.trans ⟨λ h a t s_eq, h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))), λ h a le, let ⟨t, s_eq⟩ := le_iff_exists_add.mp le in h a t (by rwa [cons_add, cons_add, zero_add] at s_eq )⟩ theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma nodup_iff_pairwise {α} {s : multiset α} : nodup s ↔ pairwise (≠) s := quotient.induction_on s $ λ l, (pairwise_coe_iff_pairwise (by exact λ a b, ne.symm)).symm lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem inj_on_of_nodup_map {f : α → β} {s : multiset α} : nodup (map f s) → ∀ (x ∈ s) (y ∈ s), f x = f y → x = y := quot.induction_on s $ λ l, inj_on_of_nodup_map theorem nodup_map_iff_inj_on {f : α → β} {s : multiset α} (d : nodup s) : nodup (map f s) ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨inj_on_of_nodup_map, λ h, nodup_map_on h d⟩ theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le tsub_le_self h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, tsub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le le_tsub_add h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (nodup_ext ht (nodup_map (show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy)) (nodup_attach.2 hs))).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr rfl (λ x _, h _ _) end multiset
c723cc17cb8dc6e7cea2f155e42a4c1d52f6ffa5
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/amc12b-2002-p7.lean
ad55cd7113b5cb72c57bba755b5fda1cca0518e0
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
343
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic import data.nat.basic example (a b c : ℕ+) (h₀ : b = a + 1) (h₁ : c = b + 1) (h₂ : a * b * c = 8 * (a + b + c) ) : a ^ 2 + ( b ^ 2 + c ^ 2 ) = 77 := begin sorry end
99cbcfc9add1155565d56e1efa2e3eee5955fca9
66a6486e19b71391cc438afee5f081a4257564ec
/pointed_pi.hlean
05fe709a83dcecc82a84abf079bc88d615ac76cd
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
43,891
hlean
/- Copyright (c) 2016 Ulrik Buchholtz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz, Floris van Doorn -/ import homotopy.connectedness types.pointed2 .move_to_lib .pointed open eq pointed equiv sigma is_equiv trunc option pi function fiber /- In this file we define dependent pointed maps and properties of them. Using this, we give the truncation level of the type of pointed maps, giving the connectivity of the domain and the truncation level of the codomain. This is is_trunc_pmap_of_is_conn at the end. We also prove other properties about pointed (dependent maps), like the fact that (Π*a, F a) → (Π*a, X a) → (Π*a, B a) is a fibration sequence if (F a) → (X a) → B a) is. -/ namespace pointed /- the pointed type of unpointed (nondependent) maps -/ definition pumap [constructor] (A : Type) (B : Type*) : Type* := pointed.MK (A → B) (const A pt) /- the pointed type of unpointed dependent maps -/ definition pupi [constructor] {A : Type} (B : A → Type*) : Type* := pointed.MK (Πa, B a) (λa, pt) notation `Πᵘ*` binders `, ` r:(scoped P, pupi P) := r infix ` →ᵘ* `:30 := pumap /- stuff about the pointed type of unpointed maps (dependent and non-dependent) -/ definition sigma_pumap {A : Type} (B : A → Type) (C : Type*) : ((Σa, B a) →ᵘ* C) ≃* Πᵘ*a, B a →ᵘ* C := pequiv_of_equiv (equiv_sigma_rec _)⁻¹ᵉ idp definition phomotopy_mk_pupi [constructor] {A : Type*} {B : Type} {C : B → Type*} {f g : A →* (Πᵘ*b, C b)} (p : f ~2 g) (q : p pt ⬝hty apd10 (respect_pt g) ~ apd10 (respect_pt f)) : f ~* g := begin apply phomotopy.mk (λa, eq_of_homotopy (p a)), apply eq_of_fn_eq_fn eq_equiv_homotopy, apply eq_of_homotopy, intro b, refine !apd10_con ⬝ _, refine whisker_right _ !pi.apd10_eq_of_homotopy ⬝ q b end definition pupi_functor [constructor] {A A' : Type} {B : A → Type*} {B' : A' → Type*} (f : A' → A) (g : Πa, B (f a) →* B' a) : (Πᵘ*a, B a) →* (Πᵘ*a', B' a') := pmap.mk (pi_functor f g) (eq_of_homotopy (λa, respect_pt (g a))) definition pupi_functor_right [constructor] {A : Type} {B B' : A → Type*} (g : Πa, B a →* B' a) : (Πᵘ*a, B a) →* (Πᵘ*a, B' a) := pupi_functor id g definition pupi_functor_compose {A A' A'' : Type} {B : A → Type*} {B' : A' → Type*} {B'' : A'' → Type*} (f : A'' → A') (f' : A' → A) (g' : Πa, B' (f a) →* B'' a) (g : Πa, B (f' a) →* B' a) : pupi_functor (f' ∘ f) (λa, g' a ∘* g (f a)) ~* pupi_functor f g' ∘* pupi_functor f' g := begin fapply phomotopy_mk_pupi, { intro h a, reflexivity }, { intro a, refine !idp_con ⬝ _, refine !apd10_con ⬝ _ ⬝ !pi.apd10_eq_of_homotopy⁻¹, esimp, refine (!apd10_prepostcompose ⬝ ap02 (g' a) !pi.apd10_eq_of_homotopy) ◾ !pi.apd10_eq_of_homotopy } end definition pupi_functor_pid (A : Type) (B : A → Type*) : pupi_functor id (λa, pid (B a)) ~* pid (Πᵘ*a, B a) := begin fapply phomotopy_mk_pupi, { intro h a, reflexivity }, { intro a, refine !idp_con ⬝ !pi.apd10_eq_of_homotopy⁻¹ } end definition pupi_functor_phomotopy {A A' : Type} {B : A → Type*} {B' : A' → Type*} {f f' : A' → A} {g : Πa, B (f a) →* B' a} {g' : Πa, B (f' a) →* B' a} (p : f ~ f') (q : Πa, g a ~* g' a ∘* ptransport B (p a)) : pupi_functor f g ~* pupi_functor f' g' := begin fapply phomotopy_mk_pupi, { intro h a, exact q a (h (f a)) ⬝ ap (g' a) (apdt h (p a)) }, { intro a, esimp, exact whisker_left _ !pi.apd10_eq_of_homotopy ⬝ !con.assoc ⬝ to_homotopy_pt (q a) ⬝ !pi.apd10_eq_of_homotopy⁻¹ } end definition pupi_pequiv [constructor] {A A' : Type} {B : A → Type*} {B' : A' → Type*} (e : A' ≃ A) (f : Πa, B (e a) ≃* B' a) : (Πᵘ*a, B a) ≃* (Πᵘ*a', B' a') := pequiv.MK (pupi_functor e f) (pupi_functor e⁻¹ᵉ (λa, ptransport B (right_inv e a) ∘* (f (e⁻¹ᵉ a))⁻¹ᵉ*)) abstract begin refine !pupi_functor_compose⁻¹* ⬝* pupi_functor_phomotopy (to_right_inv e) _ ⬝* !pupi_functor_pid, intro a, exact !pinv_pcompose_cancel_right ⬝* !pid_pcompose⁻¹* end end abstract begin refine !pupi_functor_compose⁻¹* ⬝* pupi_functor_phomotopy (to_left_inv e) _ ⬝* !pupi_functor_pid, intro a, refine !passoc⁻¹* ⬝* pinv_right_phomotopy_of_phomotopy _ ⬝* !pid_pcompose⁻¹*, refine pwhisker_left _ _ ⬝* !ptransport_natural, exact ptransport_change_eq _ (adj e a) ⬝* ptransport_ap B e (to_left_inv e a) end end definition pupi_pequiv_right [constructor] {A : Type} {B B' : A → Type*} (f : Πa, B a ≃* B' a) : (Πᵘ*a, B a) ≃* (Πᵘ*a, B' a) := pupi_pequiv erfl f definition loop_pupi [constructor] {A : Type} (B : A → Type*) : Ω (Πᵘ*a, B a) ≃* Πᵘ*a, Ω (B a) := pequiv_of_equiv eq_equiv_homotopy idp -- definition loop_pupi_natural [constructor] {A : Type} {B B' : A → Type*} (f : Πa, B a →* B' a) : -- psquare (Ω→ (pupi_functor_right f)) (pupi_functor_right (λa, Ω→ (f a))) -- (loop_pupi B) (loop_pupi B') := definition ap1_gen_pi {A A' : Type} {B : A → Type} {B' : A' → Type} {h₀ h₁ : Πa, B a} {h₀' h₁' : Πa', B' a'} (f : A' → A) (g : Πa, B (f a) → B' a) (p₀ : pi_functor f g h₀ ~ h₀') (p₁ : pi_functor f g h₁ ~ h₁') (r : h₀ = h₁) (a' : A') : apd10 (ap1_gen (pi_functor f g) (eq_of_homotopy p₀) (eq_of_homotopy p₁) r) a' = ap1_gen (g a') (p₀ a') (p₁ a') (apd10 r (f a')) := begin induction r, induction p₀ using homotopy.rec_idp, induction p₁ using homotopy.rec_idp, esimp, exact apd10 (ap apd10 !ap1_gen_idp) a', -- exact ap (λx, apd10 (ap1_gen _ x x _) _) !eq_of_homotopy_idp end definition ap1_gen_pi_idp {A A' : Type} {B : A → Type} {B' : A' → Type} {h₀ : Πa, B a} (f : A' → A) (g : Πa, B (f a) → B' a) (a' : A') : ap1_gen_pi f g (homotopy.refl (pi_functor f g h₀)) (homotopy.refl (pi_functor f g h₀)) idp a' = apd10 (ap apd10 !ap1_gen_idp) a' := -- apd10 (ap apd10 (ap1_gen_idp (pi_functor id f) (eq_of_homotopy (λ a, idp)))) a' := -- ap (λp, apd10 p a') (ap1_gen_idp (pi_functor f g) (eq_of_homotopy homotopy.rfl)) := begin esimp [ap1_gen_pi], refine !homotopy_rec_idp_refl ⬝ !homotopy_rec_idp_refl, end -- print homotopy.rec_ -- print apd10_ap_postcompose -- print pi_functor -- print ap1_gen_idp -- print ap1_gen_pi definition loop_pupi_natural [constructor] {A : Type} {B B' : A → Type*} (f : Πa, B a →* B' a) : psquare (Ω→ (pupi_functor_right f)) (pupi_functor_right (λa, Ω→ (f a))) (loop_pupi B) (loop_pupi B') := begin fapply phomotopy_mk_pupi, { intro p a, exact ap1_gen_pi id f (λa, respect_pt (f a)) (λa, respect_pt (f a)) p a }, { intro a, revert B' f, refine fiberwise_pointed_map_rec _ _, intro B' f, refine !ap1_gen_pi_idp ◾ (ap (λx, apd10 x _) !idp_con ⬝ !apd10_eq_of_homotopy) } end definition phomotopy_mk_pumap [constructor] {A C : Type*} {B : Type} {f g : A →* (B →ᵘ* C)} (p : f ~2 g) (q : p pt ⬝hty apd10 (respect_pt g) ~ apd10 (respect_pt f)) : f ~* g := phomotopy_mk_pupi p q definition pumap_functor [constructor] {A A' : Type} {B B' : Type*} (f : A' → A) (g : B →* B') : (A →ᵘ* B) →* (A' →ᵘ* B') := pupi_functor f (λa, g) definition pumap_functor_compose {A A' A'' : Type} {B B' B'' : Type*} (f : A'' → A') (f' : A' → A) (g' : B' →* B'') (g : B →* B') : pumap_functor (f' ∘ f) (g' ∘* g) ~* pumap_functor f g' ∘* pumap_functor f' g := pupi_functor_compose f f' (λa, g') (λa, g) definition pumap_functor_pid (A : Type) (B : Type*) : pumap_functor id (pid B) ~* pid (A →ᵘ* B) := pupi_functor_pid A (λa, B) definition pumap_functor_phomotopy {A A' : Type} {B B' : Type*} {f f' : A' → A} {g g' : B →* B'} (p : f ~ f') (q : g ~* g') : pumap_functor f g ~* pumap_functor f' g' := pupi_functor_phomotopy p (λa, q ⬝* !pcompose_pid⁻¹* ⬝* pwhisker_left _ !ptransport_constant⁻¹*) definition pumap_pequiv [constructor] {A A' : Type} {B B' : Type*} (e : A ≃ A') (f : B ≃* B') : (A →ᵘ* B) ≃* (A' →ᵘ* B') := pupi_pequiv e⁻¹ᵉ (λa, f) definition pumap_pequiv_right [constructor] (A : Type) {B B' : Type*} (f : B ≃* B') : (A →ᵘ* B) ≃* (A →ᵘ* B') := pumap_pequiv erfl f definition pumap_pequiv_left [constructor] {A A' : Type} (B : Type*) (f : A ≃ A') : (A →ᵘ* B) ≃* (A' →ᵘ* B) := pumap_pequiv f pequiv.rfl definition loop_pumap [constructor] (A : Type) (B : Type*) : Ω (A →ᵘ* B) ≃* A →ᵘ* Ω B := loop_pupi (λa, B) /- the pointed sigma type -/ definition psigma_gen [constructor] {A : Type*} (P : A → Type) (x : P pt) : Type* := pointed.MK (Σa, P a) ⟨pt, x⟩ definition psigma_gen_functor [constructor] {A A' : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A →* A') (g : Πa, B a → B' (f a)) (p : g pt b =[respect_pt f] b') : psigma_gen B b →* psigma_gen B' b' := pmap.mk (sigma_functor f g) (sigma_eq (respect_pt f) p) definition psigma_gen_functor_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a → B' a) (p : f pt b = b') : psigma_gen B b →* psigma_gen B' b' := proof pmap.mk (sigma_functor id f) (sigma_eq_right p) qed definition psigma_gen_pequiv_psigma_gen [constructor] {A A' : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A ≃* A') (g : Πa, B a ≃ B' (f a)) (p : g pt b =[respect_pt f] b') : psigma_gen B b ≃* psigma_gen B' b' := pequiv_of_equiv (sigma_equiv_sigma f g) (sigma_eq (respect_pt f) p) definition psigma_gen_pequiv_psigma_gen_left [constructor] {A A' : Type*} {B : A' → Type} {b : B pt} (f : A ≃* A') {b' : B (f pt)} (q : b' =[respect_pt f] b) : psigma_gen (B ∘ f) b' ≃* psigma_gen B b := psigma_gen_pequiv_psigma_gen f (λa, erfl) q definition psigma_gen_pequiv_psigma_gen_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a ≃ B' a) (p : f pt b = b') : psigma_gen B b ≃* psigma_gen B' b' := psigma_gen_pequiv_psigma_gen pequiv.rfl f (pathover_idp_of_eq p) definition psigma_gen_pequiv_psigma_gen_basepoint [constructor] {A : Type*} {B : A → Type} {b b' : B pt} (p : b = b') : psigma_gen B b ≃* psigma_gen B b' := psigma_gen_pequiv_psigma_gen_right (λa, erfl) p definition loop_psigma_gen [constructor] {A : Type*} (B : A → Type) (b₀ : B pt) : Ω (psigma_gen B b₀) ≃* @psigma_gen (Ω A) (λp, pathover B b₀ p b₀) idpo := pequiv_of_equiv (sigma_eq_equiv pt pt) idp open sigma.ops definition ap1_gen_sigma {A A' : Type} {B : A → Type} {B' : A' → Type} {x₀ x₁ : Σa, B a} {a₀' a₁' : A'} {b₀' : B' a₀'} {b₁' : B' a₁'} (f : A → A') (p₀ : f x₀.1 = a₀') (p₁ : f x₁.1 = a₁') (g : Πa, B a → B' (f a)) (q₀ : g x₀.1 x₀.2 =[p₀] b₀') (q₁ : g x₁.1 x₁.2 =[p₁] b₁') (r : x₀ = x₁) : (λx, ⟨x..1, x..2⟩) (ap1_gen (sigma_functor f g) (sigma_eq p₀ q₀) (sigma_eq p₁ q₁) r) = ⟨ap1_gen f p₀ p₁ r..1, q₀⁻¹ᵒ ⬝o pathover_ap B' f (apo g r..2) ⬝o q₁⟩ := begin induction r, induction q₀, induction q₁, reflexivity end definition loop_psigma_gen_natural {A A' : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A →* A') (g : Πa, B a → B' (f a)) (p : g pt b =[respect_pt f] b') : psquare (Ω→ (psigma_gen_functor f g p)) (psigma_gen_functor (Ω→ f) (λq r, p⁻¹ᵒ ⬝o pathover_ap _ _ (apo g r) ⬝o p) !cono.left_inv) (loop_psigma_gen B b) (loop_psigma_gen B' b') := begin fapply phomotopy.mk, { exact ap1_gen_sigma f (respect_pt f) (respect_pt f) g p p }, { induction f with f f₀, induction A' with A' a₀', esimp at * ⊢, induction p, reflexivity } end definition psigma_gen_functor_pcompose [constructor] {A₁ A₂ A₃ : Type*} {B₁ : A₁ → Type} {B₂ : A₂ → Type} {B₃ : A₃ → Type} {b₁ : B₁ pt} {b₂ : B₂ pt} {b₃ : B₃ pt} {f₁ : A₁ →* A₂} {f₂ : A₂ →* A₃} (g₁ : Π⦃a⦄, B₁ a → B₂ (f₁ a)) (g₂ : Π⦃a⦄, B₂ a → B₃ (f₂ a)) (p₁ : pathover B₂ (g₁ b₁) (respect_pt f₁) b₂) (p₂ : pathover B₃ (g₂ b₂) (respect_pt f₂) b₃) : psigma_gen_functor (f₂ ∘* f₁) (λa, @g₂ (f₁ a) ∘ @g₁ a) (pathover_ap B₃ f₂ (apo g₂ p₁) ⬝o p₂) ~* psigma_gen_functor f₂ g₂ p₂ ∘* psigma_gen_functor f₁ g₁ p₁ := begin fapply phomotopy.mk, { intro x, reflexivity }, { refine !idp_con ⬝ _, esimp, refine whisker_right _ !ap_sigma_functor_eq_dpair ⬝ _, induction f₁ with f₁ f₁₀, induction f₂ with f₂ f₂₀, induction A₂ with A₂ a₂₀, induction A₃ with A₃ a₃₀, esimp at * ⊢, induction p₁, induction p₂, reflexivity } end definition psigma_gen_functor_phomotopy [constructor] {A₁ A₂ : Type*} {B₁ : A₁ → Type} {B₂ : A₂ → Type} {b₁ : B₁ pt} {b₂ : B₂ pt} {f₁ f₂ : A₁ →* A₂} {g₁ : Π⦃a⦄, B₁ a → B₂ (f₁ a)} {g₂ : Π⦃a⦄, B₁ a → B₂ (f₂ a)} {p₁ : pathover B₂ (g₁ b₁) (respect_pt f₁) b₂} {p₂ : pathover B₂ (g₂ b₁) (respect_pt f₂) b₂} (h₁ : f₁ ~* f₂) (h₂ : Π⦃a⦄ (b : B₁ a), pathover B₂ (g₁ b) (h₁ a) (g₂ b)) (h₃ : squareover B₂ (square_of_eq (to_homotopy_pt h₁)⁻¹) p₁ p₂ (h₂ b₁) idpo) : psigma_gen_functor f₁ g₁ p₁ ~* psigma_gen_functor f₂ g₂ p₂ := begin induction h₁ using phomotopy_rec_idp, fapply phomotopy.mk, { intro x, induction x with a b, exact ap (dpair (f₁ a)) (eq_of_pathover_idp (h₂ b)) }, { induction f₁ with f f₀, induction A₂ with A₂ a₂₀, esimp at * ⊢, induction f₀, esimp, induction p₂ using idp_rec_on, rewrite [to_right_inv !eq_con_inv_equiv_con_eq at h₃], have h₂ b₁ = p₁, from (eq_top_of_squareover h₃)⁻¹, induction this, refine !ap_dpair ⬝ ap (sigma_eq _) _, exact to_left_inv !pathover_idp (h₂ b₁) } end definition psigma_gen_functor_psquare [constructor] {A₀₀ A₀₂ A₂₀ A₂₂ : Type*} {B₀₀ : A₀₀ → Type} {B₀₂ : A₀₂ → Type} {B₂₀ : A₂₀ → Type} {B₂₂ : A₂₂ → Type} {b₀₀ : B₀₀ pt} {b₀₂ : B₀₂ pt} {b₂₀ : B₂₀ pt} {b₂₂ : B₂₂ pt} {f₀₁ : A₀₀ →* A₀₂} {f₁₀ : A₀₀ →* A₂₀} {f₂₁ : A₂₀ →* A₂₂} {f₁₂ : A₀₂ →* A₂₂} {g₀₁ : Π⦃a⦄, B₀₀ a → B₀₂ (f₀₁ a)} {g₁₀ : Π⦃a⦄, B₀₀ a → B₂₀ (f₁₀ a)} {g₂₁ : Π⦃a⦄, B₂₀ a → B₂₂ (f₂₁ a)} {g₁₂ : Π⦃a⦄, B₀₂ a → B₂₂ (f₁₂ a)} {p₀₁ : pathover B₀₂ (g₀₁ b₀₀) (respect_pt f₀₁) b₀₂} {p₁₀ : pathover B₂₀ (g₁₀ b₀₀) (respect_pt f₁₀) b₂₀} {p₂₁ : pathover B₂₂ (g₂₁ b₂₀) (respect_pt f₂₁) b₂₂} {p₁₂ : pathover B₂₂ (g₁₂ b₀₂) (respect_pt f₁₂) b₂₂} (h₁ : psquare f₁₀ f₁₂ f₀₁ f₂₁) (h₂ : Π⦃a⦄ (b : B₀₀ a), pathover B₂₂ (g₂₁ (g₁₀ b)) (h₁ a) (g₁₂ (g₀₁ b))) (h₃ : squareover B₂₂ (square_of_eq (to_homotopy_pt h₁)⁻¹) (pathover_ap B₂₂ f₂₁ (apo g₂₁ p₁₀) ⬝o p₂₁) (pathover_ap B₂₂ f₁₂ (apo g₁₂ p₀₁) ⬝o p₁₂) (h₂ b₀₀) idpo) : psquare (psigma_gen_functor f₁₀ g₁₀ p₁₀) (psigma_gen_functor f₁₂ g₁₂ p₁₂) (psigma_gen_functor f₀₁ g₀₁ p₀₁) (psigma_gen_functor f₂₁ g₂₁ p₂₁) := proof !psigma_gen_functor_pcompose⁻¹* ⬝* psigma_gen_functor_phomotopy h₁ h₂ h₃ ⬝* !psigma_gen_functor_pcompose qed end pointed open pointed namespace pointed definition pointed_respect_pt [instance] [constructor] {A B : Type*} (f : A →* B) : pointed (f pt = pt) := pointed.mk (respect_pt f) definition ppi_of_phomotopy [constructor] {A B : Type*} {f g : A →* B} (h : f ~* g) : ppi (λx, f x = g x) (respect_pt f ⬝ (respect_pt g)⁻¹) := h definition phomotopy {A : Type*} {P : A → Type} {x : P pt} (f g : ppi P x) : Type := ppi (λa, f a = g a) (respect_pt f ⬝ (respect_pt g)⁻¹) variables {A : Type*} {P Q R : A → Type*} {f g h : Π*a, P a} {B C D : A → Type} {b₀ : B pt} {c₀ : C pt} {d₀ : D pt} {k k' l m : ppi B b₀} definition pppi_equiv_pmap [constructor] (A B : Type*) : (Π*(a : A), B) ≃ (A →* B) := by reflexivity definition pppi_pequiv_ppmap [constructor] (A B : Type*) : (Π*(a : A), B) ≃* ppmap A B := by reflexivity definition apd10_to_fun_eq_of_phomotopy (h : f ~* g) : apd10 (ap (λ k, pppi.to_fun k) (eq_of_phomotopy h)) = h := begin induction h using phomotopy_rec_idp, xrewrite [eq_of_phomotopy_refl f] end -- definition phomotopy_of_eq_of_phomotopy definition phomotopy_mk_ppi [constructor] {A : Type*} {B : Type*} {C : B → Type*} {f g : A →* (Π*b, C b)} (p : Πa, f a ~* g a) (q : p pt ⬝* phomotopy_of_eq (respect_pt g) = phomotopy_of_eq (respect_pt f)) : f ~* g := begin apply phomotopy.mk (λa, eq_of_phomotopy (p a)), apply eq_of_fn_eq_fn !ppi_eq_equiv, refine !phomotopy_of_eq_con ⬝ _, esimp, refine ap (λx, x ⬝* _) !phomotopy_of_eq_of_phomotopy ⬝ q end -- definition phomotopy_mk_ppmap [constructor] -- {A : Type*} {X : A → Type*} {Y : Π (a : A), X a → Type*} -- {f g : Π* (a : A), Π*(x : (X a)), (Y a x)} -- (p : Πa, f a ~* g a) -- (q : p pt ⬝* phomotopy_of_eq (ppi_resp_pt g) = phomotopy_of_eq (ppi_resp_pt f)) -- : f ~* g := -- begin -- apply phomotopy.mk (λa, eq_of_phomotopy (p a)), -- apply eq_of_fn_eq_fn (ppi_eq_equiv _ _), -- refine !phomotopy_of_eq_con ⬝ _, -- -- refine !phomotopy_of_eq_of_phomotopy ◾** idp ⬝ q, -- end variable {k} variables (k l) definition ppi_loop_equiv : (k = k) ≃ Π*(a : A), Ω (pType.mk (B a) (k a)) := begin induction k with k p, induction p, exact ppi_eq_equiv (ppi.mk k idp) (ppi.mk k idp) end variables {k l} -- definition eq_of_phomotopy (h : k ~* l) : k = l := -- (ppi_eq_equiv k l)⁻¹ᵉ h definition ppi_functor_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a → B' a) (p : f pt b = b') (g : ppi B b) : ppi B' b' := ppi.mk (λa, f a (g a)) (ap (f pt) (respect_pt g) ⬝ p) definition ppi_functor_right_compose [constructor] {A : Type*} {B₁ B₂ B₃ : A → Type} {b₁ : B₁ pt} {b₂ : B₂ pt} {b₃ : B₃ pt} (f₂ : Πa, B₂ a → B₃ a) (p₂ : f₂ pt b₂ = b₃) (f₁ : Πa, B₁ a → B₂ a) (p₁ : f₁ pt b₁ = b₂) (g : ppi B₁ b₁) : ppi_functor_right (λa, f₂ a ∘ f₁ a) (ap (f₂ pt) p₁ ⬝ p₂) g ~* ppi_functor_right f₂ p₂ (ppi_functor_right f₁ p₁ g) := begin fapply phomotopy.mk, { reflexivity }, { induction p₁, induction p₂, exact !idp_con ⬝ !ap_compose⁻¹ } end definition ppi_functor_right_id [constructor] {A : Type*} {B : A → Type} {b : B pt} (g : ppi B b) : ppi_functor_right (λa, id) idp g ~* g := begin fapply phomotopy.mk, { reflexivity }, { reflexivity } end definition ppi_functor_right_phomotopy [constructor] {g g' : Π(a : A), B a → C a} {g₀ : g pt b₀ = c₀} {g₀' : g' pt b₀ = c₀} {f f' : ppi B b₀} (p : g ~2 g') (q : f ~* f') (r : p pt b₀ ⬝ g₀' = g₀) : ppi_functor_right g g₀ f ~* ppi_functor_right g' g₀' f' := phomotopy.mk (λa, p a (f a) ⬝ ap (g' a) (q a)) abstract begin induction q using phomotopy_rec_idp, induction r, revert g p, refine rec_idp_of_equiv _ homotopy2.rfl _ _ _, { intro h h', exact !eq_equiv_eq_symm ⬝e !eq_equiv_homotopy2 }, { reflexivity }, induction g₀', induction f with f f₀, induction f₀, reflexivity end end definition ppi_functor_right_phomotopy_refl [constructor] (g : Π(a : A), B a → C a) (g₀ : g pt b₀ = c₀) (f : ppi B b₀) : ppi_functor_right_phomotopy (homotopy2.refl g) (phomotopy.refl f) !idp_con = phomotopy.refl (ppi_functor_right g g₀ f) := begin induction g₀, apply ap (phomotopy.mk homotopy.rfl), refine !phomotopy_rec_idp_refl ⬝ _, esimp, refine !rec_idp_of_equiv_idp ⬝ _, induction f with f f₀, induction f₀, reflexivity end definition ppi_equiv_ppi_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a ≃ B' a) (p : f pt b = b') : ppi B b ≃ ppi B' b' := equiv.MK (ppi_functor_right f p) (ppi_functor_right (λa, (f a)⁻¹ᵉ) (inv_eq_of_eq p⁻¹)) abstract begin intro g, apply eq_of_phomotopy, refine !ppi_functor_right_compose⁻¹* ⬝* _, refine ppi_functor_right_phomotopy (λa, to_right_inv (f a)) (phomotopy.refl g) _ ⬝* !ppi_functor_right_id, induction p, exact adj (f pt) b ⬝ ap02 (f pt) !idp_con⁻¹ end end abstract begin intro g, apply eq_of_phomotopy, refine !ppi_functor_right_compose⁻¹* ⬝* _, refine ppi_functor_right_phomotopy (λa, to_left_inv (f a)) (phomotopy.refl g) _ ⬝* !ppi_functor_right_id, induction p, exact (!idp_con ⬝ !idp_con)⁻¹, end end definition ppi_equiv_ppi_basepoint [constructor] {A : Type*} {B : A → Type} {b b' : B pt} (p : b = b') : ppi B b ≃ ppi B b' := ppi_equiv_ppi_right (λa, erfl) p definition pmap_compose_ppi [constructor] (g : Π(a : A), ppmap (P a) (Q a)) (f : Π*(a : A), P a) : Π*(a : A), Q a := ppi_functor_right g (respect_pt (g pt)) f definition pmap_compose_ppi_ppi_const [constructor] (g : Π(a : A), ppmap (P a) (Q a)) : pmap_compose_ppi g (ppi_const P) ~* ppi_const Q := proof phomotopy.mk (λa, respect_pt (g a)) !idp_con⁻¹ qed definition pmap_compose_ppi_pconst [constructor] (f : Π*(a : A), P a) : pmap_compose_ppi (λa, pconst (P a) (Q a)) f ~* ppi_const Q := phomotopy.mk homotopy.rfl !ap_constant⁻¹ definition pmap_compose_ppi2 [constructor] {g g' : Π(a : A), ppmap (P a) (Q a)} {f f' : Π*(a : A), P a} (p : Πa, g a ~* g' a) (q : f ~* f') : pmap_compose_ppi g f ~* pmap_compose_ppi g' f' := ppi_functor_right_phomotopy p q (to_homotopy_pt (p pt)) definition pmap_compose_ppi2_refl [constructor] (g : Π(a : A), P a →* Q a) (f : Π*(a : A), P a) : pmap_compose_ppi2 (λa, phomotopy.refl (g a)) (phomotopy.refl f) = phomotopy.rfl := begin refine _ ⬝ ppi_functor_right_phomotopy_refl g (respect_pt (g pt)) f, exact ap (ppi_functor_right_phomotopy _ _) (to_right_inv !eq_con_inv_equiv_con_eq _) end definition pmap_compose_ppi_phomotopy_left [constructor] {g g' : Π(a : A), ppmap (P a) (Q a)} (f : Π*(a : A), P a) (p : Πa, g a ~* g' a) : pmap_compose_ppi g f ~* pmap_compose_ppi g' f := pmap_compose_ppi2 p phomotopy.rfl definition pmap_compose_ppi_phomotopy_right [constructor] (g : Π(a : A), ppmap (P a) (Q a)) {f f' : Π*(a : A), P a} (p : f ~* f') : pmap_compose_ppi g f ~* pmap_compose_ppi g f' := pmap_compose_ppi2 (λa, phomotopy.rfl) p definition pmap_compose_ppi_pid_left [constructor] (f : Π*(a : A), P a) : pmap_compose_ppi (λa, pid (P a)) f ~* f := phomotopy.mk homotopy.rfl idp definition pmap_compose_ppi_pcompose [constructor] (h : Π(a : A), ppmap (Q a) (R a)) (g : Π(a : A), ppmap (P a) (Q a)) : pmap_compose_ppi (λa, h a ∘* g a) f ~* pmap_compose_ppi h (pmap_compose_ppi g f) := phomotopy.mk homotopy.rfl abstract !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose'⁻¹) ⬝ !con.assoc end definition ppi_assoc [constructor] (h : Π (a : A), Q a →* R a) (g : Π (a : A), P a →* Q a) (f : Π*a, P a) : pmap_compose_ppi (λa, h a ∘* g a) f ~* pmap_compose_ppi h (pmap_compose_ppi g f) := begin fapply phomotopy.mk, { intro a, reflexivity }, exact !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose⁻¹) ⬝ !con.assoc end definition pmap_compose_ppi_eq_of_phomotopy (g : Πa, P a →* Q a) {f f' : Π*a, P a} (p : f ~* f') : ap (pmap_compose_ppi g) (eq_of_phomotopy p) = eq_of_phomotopy (pmap_compose_ppi_phomotopy_right g p) := begin induction p using phomotopy_rec_idp, refine ap02 _ !eq_of_phomotopy_refl ⬝ !eq_of_phomotopy_refl⁻¹ ⬝ ap eq_of_phomotopy _, exact !pmap_compose_ppi2_refl⁻¹ end definition ppi_assoc_ppi_const_right (g : Πa, Q a →* R a) (f : Πa, P a →* Q a) : ppi_assoc g f (ppi_const P) ⬝* (pmap_compose_ppi_phomotopy_right _ (pmap_compose_ppi_ppi_const f) ⬝* pmap_compose_ppi_ppi_const g) = pmap_compose_ppi_ppi_const (λa, g a ∘* f a) := begin revert R g, refine fiberwise_pointed_map_rec _ _, revert Q f, refine fiberwise_pointed_map_rec _ _, intro Q f R g, refine ap (λx, _ ⬝* (x ⬝* _)) !pmap_compose_ppi2_refl ⬝ _, reflexivity end definition pppi_compose_left [constructor] (g : Π(a : A), ppmap (P a) (Q a)) : (Π*(a : A), P a) →* Π*(a : A), Q a := pmap.mk (pmap_compose_ppi g) (eq_of_phomotopy (pmap_compose_ppi_ppi_const g)) -- pppi_compose_left is a functor in the following sense definition pppi_compose_left_pcompose (g : Π (a : A), Q a →* R a) (f : Π (a : A), P a →* Q a) : pppi_compose_left (λ a, g a ∘* f a) ~* (pppi_compose_left g ∘* pppi_compose_left f) := begin fapply phomotopy_mk_ppi, { exact ppi_assoc g f }, { refine idp ◾** (!phomotopy_of_eq_con ⬝ (ap phomotopy_of_eq !pmap_compose_ppi_eq_of_phomotopy ⬝ !phomotopy_of_eq_of_phomotopy) ◾** !phomotopy_of_eq_of_phomotopy) ⬝ _ ⬝ !phomotopy_of_eq_of_phomotopy⁻¹, apply ppi_assoc_ppi_const_right }, end definition pppi_compose_left_phomotopy [constructor] {g g' : Π(a : A), ppmap (P a) (Q a)} (p : Πa, g a ~* g' a) : pppi_compose_left g ~* pppi_compose_left g' := begin apply phomotopy_of_eq, apply ap pppi_compose_left, apply eq_of_homotopy, intro a, apply eq_of_phomotopy, exact p a end definition psquare_pppi_compose_left {A : Type*} {B C D E : A → Type*} {ftop : Π (a : A), B a →* C a} {fbot : Π (a : A), D a →* E a} {fleft : Π (a : A), B a →* D a} {fright : Π (a : A), C a →* E a} (psq : Π (a :A), psquare (ftop a) (fbot a) (fleft a) (fright a)) : psquare (pppi_compose_left ftop) (pppi_compose_left fbot) (pppi_compose_left fleft) (pppi_compose_left fright) := begin refine (pppi_compose_left_pcompose fright ftop)⁻¹* ⬝* _ ⬝* (pppi_compose_left_pcompose fbot fleft), exact pppi_compose_left_phomotopy psq end definition ppi_pequiv_right [constructor] (g : Π(a : A), P a ≃* Q a) : (Π*(a : A), P a) ≃* Π*(a : A), Q a := begin apply pequiv_of_pmap (pppi_compose_left g), apply adjointify _ (pppi_compose_left (λa, (g a)⁻¹ᵉ*)), { intro f, apply eq_of_phomotopy, refine !pmap_compose_ppi_pcompose⁻¹* ⬝* _, refine pmap_compose_ppi_phomotopy_left _ (λa, !pright_inv) ⬝* _, apply pmap_compose_ppi_pid_left }, { intro f, apply eq_of_phomotopy, refine !pmap_compose_ppi_pcompose⁻¹* ⬝* _, refine pmap_compose_ppi_phomotopy_left _ (λa, !pleft_inv) ⬝* _, apply pmap_compose_ppi_pid_left } end end pointed namespace pointed variables {A B C : Type*} -- TODO: replace in types.fiber definition pfiber.sigma_char' (f : A →* B) : pfiber f ≃* psigma_gen (λa, f a = pt) (respect_pt f) := pequiv_of_equiv (fiber.sigma_char f pt) idp definition ppmap.sigma_char [constructor] (A B : Type*) : ppmap A B ≃* @psigma_gen (A →ᵘ* B) (λf, f pt = pt) idp := pequiv_of_equiv pmap.sigma_char idp definition pppi.sigma_char [constructor] (B : A → Type*) : (Π*(a : A), B a) ≃* @psigma_gen (Πᵘ*a, B a) (λf, f pt = pt) idp := proof pequiv_of_equiv !ppi.sigma_char idp qed definition pppi_sigma_char_natural_bottom [constructor] {B B' : A → Type*} (f : Πa, B a →* B' a) : @psigma_gen (Πᵘ*a, B a) (λg, g pt = pt) idp →* @psigma_gen (Πᵘ*a, B' a) (λg, g pt = pt) idp := psigma_gen_functor (pupi_functor_right f) (λg p, ap (f pt) p ⬝ respect_pt (f pt)) begin apply eq_pathover_constant_right, apply square_of_eq, esimp, exact !idp_con ⬝ !apd10_eq_of_homotopy⁻¹ ⬝ !ap_eq_apd10⁻¹, end definition pppi_sigma_char_natural {B B' : A → Type*} (f : Πa, B a →* B' a) : psquare (pppi_compose_left f) (pppi_sigma_char_natural_bottom f) (pppi.sigma_char B) (pppi.sigma_char B') := begin fapply phomotopy.mk, { intro g, reflexivity }, { refine !idp_con ⬝ !idp_con ⬝ _, fapply sigma_eq2, { refine !sigma_eq_pr1 ⬝ _ ⬝ !ap_sigma_pr1⁻¹, apply eq_of_fn_eq_fn eq_equiv_homotopy, refine !apd10_eq_of_homotopy ⬝ _ ⬝ !apd10_to_fun_eq_of_phomotopy⁻¹, apply eq_of_homotopy, intro a, reflexivity }, { exact sorry } } end open sigma.ops definition psigma_gen_pi_pequiv_pupi_psigma_gen [constructor] {A : Type*} {B : A → Type*} (C : Πa, B a → Type) (c : Πa, C a pt) : @psigma_gen (Πᵘ*a, B a) (λf, Πa, C a (f a)) c ≃* Πᵘ*a, psigma_gen (C a) (c a) := pequiv_of_equiv sigma_pi_equiv_pi_sigma idp definition pupi_psigma_gen_pequiv_psigma_gen_pi [constructor] {A : Type*} {B : A → Type*} (C : Πa, B a → Type) (c : Πa, C a pt) : (Πᵘ*a, psigma_gen (C a) (c a)) ≃* @psigma_gen (Πᵘ*a, B a) (λf, Πa, C a (f a)) c := pequiv_of_equiv sigma_pi_equiv_pi_sigma⁻¹ᵉ idp definition psigma_gen_assoc [constructor] {A : Type*} {B : A → Type} (C : Πa, B a → Type) (b₀ : B pt) (c₀ : C pt b₀) : psigma_gen (λa, Σb, C a b) ⟨b₀, c₀⟩ ≃* @psigma_gen (psigma_gen B b₀) (λv, C v.1 v.2) c₀ := pequiv_of_equiv !sigma_assoc_equiv idp definition psigma_gen_swap [constructor] {A : Type*} {B B' : A → Type} (C : Π⦃a⦄, B a → B' a → Type) (b₀ : B pt) (b₀' : B' pt) (c₀ : C b₀ b₀') : @psigma_gen (psigma_gen B b₀ ) (λv, Σb', C v.2 b') ⟨b₀', c₀⟩ ≃* @psigma_gen (psigma_gen B' b₀') (λv, Σb , C b v.2) ⟨b₀ , c₀⟩ := !psigma_gen_assoc⁻¹ᵉ* ⬝e* psigma_gen_pequiv_psigma_gen_right (λa, !sigma_comm_equiv) idp ⬝e* !psigma_gen_assoc definition ppi_psigma.{u v w} {A : pType.{u}} {B : A → pType.{v}} (C : Πa, B a → Type.{w}) (c : Πa, C a pt) : (Π*(a : A), (psigma_gen (C a) (c a))) ≃* psigma_gen (λ(f : Π*(a : A), B a), ppi (λa, C a (f a)) (transport (C pt) (respect_pt f)⁻¹ (c pt))) (ppi_const _) := proof calc (Π*(a : A), psigma_gen (C a) (c a)) ≃* @psigma_gen (Πᵘ*a, psigma_gen (C a) (c a)) (λf, f pt = pt) idp : pppi.sigma_char ... ≃* @psigma_gen (@psigma_gen (Πᵘ*a, B a) (λf, Πa, C a (f a)) c) (λv, Σ(p : v.1 pt = pt), v.2 pt =[p] c pt) ⟨idp, idpo⟩ : by exact psigma_gen_pequiv_psigma_gen (pupi_psigma_gen_pequiv_psigma_gen_pi C c) (λf, sigma_eq_equiv _ _) idpo ... ≃* @psigma_gen (@psigma_gen (Πᵘ*a, B a) (λf, f pt = pt) idp) (λv, Σ(g : Πa, C a (v.1 a)), g pt =[v.2] c pt) ⟨c, idpo⟩ : by apply psigma_gen_swap ... ≃* psigma_gen (λ(f : Π*(a : A), B a), ppi (λa, C a (f a)) (transport (C pt) (respect_pt f)⁻¹ (c pt))) (ppi_const _) : by exact (psigma_gen_pequiv_psigma_gen (pppi.sigma_char B) (λf, !ppi.sigma_char ⬝e sigma_equiv_sigma_right (λg, !pathover_equiv_eq_tr⁻¹ᵉ)) idpo)⁻¹ᵉ* qed definition ppmap_psigma {A B : Type*} (C : B → Type) (c : C pt) : ppmap A (psigma_gen C c) ≃* psigma_gen (λ(f : ppmap A B), ppi (C ∘ f) (transport C (respect_pt f)⁻¹ c)) (ppi_const _) := !pppi_pequiv_ppmap⁻¹ᵉ* ⬝e* !ppi_psigma ⬝e* sorry -- psigma_gen_pequiv_psigma_gen (pppi_pequiv_ppmap A B) (λf, begin esimp, exact ppi_equiv_ppi_right (λa, _) _ end) _ definition pfiber_pppi_compose_left {B C : A → Type*} (f : Πa, B a →* C a) : pfiber (pppi_compose_left f) ≃* Π*(a : A), pfiber (f a) := calc pfiber (pppi_compose_left f) ≃* psigma_gen (λ(g : Π*(a : A), B a), pmap_compose_ppi f g = ppi_const C) proof (eq_of_phomotopy (pmap_compose_ppi_ppi_const f)) qed : by exact !pfiber.sigma_char' ... ≃* psigma_gen (λ(g : Π*(a : A), B a), pmap_compose_ppi f g ~* ppi_const C) proof (pmap_compose_ppi_ppi_const f) qed : by exact psigma_gen_pequiv_psigma_gen_right (λa, !ppi_eq_equiv) !phomotopy_of_eq_of_phomotopy ... ≃* @psigma_gen (Π*(a : A), B a) (λ(g : Π*(a : A), B a), ppi (λa, f a (g a) = pt) (transport (λb, f pt b = pt) (respect_pt g)⁻¹ (respect_pt (f pt)))) (ppi_const _) : begin refine psigma_gen_pequiv_psigma_gen_right (λg, ppi_equiv_ppi_basepoint (_ ⬝ !eq_transport_Fl⁻¹)) _, intro g, refine !con_idp ⬝ _, apply whisker_right, exact ap02 (f pt) !inv_inv⁻¹ ⬝ !ap_inv, apply eq_of_phomotopy, fapply phomotopy.mk, intro x, reflexivity, refine !idp_con ⬝ _, symmetry, refine !ap_id ◾ !idp_con ⬝ _, apply con.right_inv end ... ≃* Π*(a : A), (psigma_gen (λb, f a b = pt) (respect_pt (f a))) : by exact (ppi_psigma _ _)⁻¹ᵉ* ... ≃* Π*(a : A), pfiber (f a) : by exact ppi_pequiv_right (λa, !pfiber.sigma_char'⁻¹ᵉ*) /- TODO: proof the following as a special case of pfiber_pppi_compose_left -/ definition pfiber_ppcompose_left (f : B →* C) : pfiber (@ppcompose_left A B C f) ≃* ppmap A (pfiber f) := calc pfiber (@ppcompose_left A B C f) ≃* psigma_gen (λ(g : ppmap A B), f ∘* g = pconst A C) proof (eq_of_phomotopy (pcompose_pconst f)) qed : by exact !pfiber.sigma_char' ... ≃* psigma_gen (λ(g : ppmap A B), f ∘* g ~* pconst A C) proof (pcompose_pconst f) qed : by exact psigma_gen_pequiv_psigma_gen_right (λa, !pmap_eq_equiv) !phomotopy_of_eq_of_phomotopy ... ≃* psigma_gen (λ(g : ppmap A B), ppi (λa, f (g a) = pt) (transport (λb, f b = pt) (respect_pt g)⁻¹ (respect_pt f))) (ppi_const _) : begin refine psigma_gen_pequiv_psigma_gen_right (λg, ppi_equiv_ppi_basepoint (_ ⬝ !eq_transport_Fl⁻¹)) _, intro g, refine !con_idp ⬝ _, apply whisker_right, exact ap02 f !inv_inv⁻¹ ⬝ !ap_inv, apply eq_of_phomotopy, fapply phomotopy.mk, intro x, reflexivity, refine !idp_con ⬝ _, symmetry, refine !ap_id ◾ !idp_con ⬝ _, apply con.right_inv end ... ≃* ppmap A (psigma_gen (λb, f b = pt) (respect_pt f)) : by exact (ppmap_psigma _ _)⁻¹ᵉ* ... ≃* ppmap A (pfiber f) : by exact pequiv_ppcompose_left !pfiber.sigma_char'⁻¹ᵉ* -- definition pppi_ppmap {A C : Type*} {B : A → Type*} : -- ppmap (/- dependent smash of B -/) C ≃* Π*(a : A), ppmap (B a) C := definition ppi_add_point_over {A : Type} (B : A → Type*) : (Π*a, add_point_over B a) ≃ Πa, B a := begin fapply equiv.MK, { intro f a, exact f (some a) }, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity }, { intro f, reflexivity }, { intro f, cases f with f p, apply eq_of_phomotopy, fapply phomotopy.mk, { intro a, cases a, exact p⁻¹, reflexivity }, { exact con.left_inv p }}, end definition pppi_add_point_over {A : Type} (B : A → Type*) : (Π*a, add_point_over B a) ≃* Πᵘ*a, B a := pequiv_of_equiv (ppi_add_point_over B) idp definition ppmap_add_point {A : Type} (B : Type*) : ppmap A₊ B ≃* A →ᵘ* B := pequiv_of_equiv (pmap_equiv_left A B) idp /- There are some lemma's needed to prove the naturality of the equivalence Ω (Π*a, B a) ≃* Π*(a : A), Ω (B a) -/ definition ppi_eq_equiv_natural_gen_lem {B C : A → Type} {b₀ : B pt} {c₀ : C pt} {f : Π(a : A), B a → C a} {f₀ : f pt b₀ = c₀} {k : ppi B b₀} {k' : ppi C c₀} (p : ppi_functor_right f f₀ k ~* k') : ap1_gen (f pt) (p pt) f₀ (respect_pt k) = respect_pt k' := begin symmetry, refine _ ⬝ !con.assoc⁻¹, exact eq_inv_con_of_con_eq (to_homotopy_pt p), end definition ppi_eq_equiv_natural_gen_lem2 {B C : A → Type} {b₀ : B pt} {c₀ : C pt} {f : Π(a : A), B a → C a} {f₀ : f pt b₀ = c₀} {k l : ppi B b₀} {k' l' : ppi C c₀} (p : ppi_functor_right f f₀ k ~* k') (q : ppi_functor_right f f₀ l ~* l') : ap1_gen (f pt) (p pt) (q pt) (respect_pt k ⬝ (respect_pt l)⁻¹) = respect_pt k' ⬝ (respect_pt l')⁻¹ := (ap1_gen_con (f pt) _ f₀ _ _ _ ⬝ (ppi_eq_equiv_natural_gen_lem p) ◾ (!ap1_gen_inv ⬝ (ppi_eq_equiv_natural_gen_lem q)⁻²)) definition ppi_eq_equiv_natural_gen {B C : A → Type} {b₀ : B pt} {c₀ : C pt} {f : Π(a : A), B a → C a} {f₀ : f pt b₀ = c₀} {k l : ppi B b₀} {k' l' : ppi C c₀} (p : ppi_functor_right f f₀ k ~* k') (q : ppi_functor_right f f₀ l ~* l') : hsquare (ap1_gen (ppi_functor_right f f₀) (eq_of_phomotopy p) (eq_of_phomotopy q)) (ppi_functor_right (λa, ap1_gen (f a) (p a) (q a)) (ppi_eq_equiv_natural_gen_lem2 p q)) phomotopy_of_eq phomotopy_of_eq := begin intro r, induction r, induction f₀, induction k with k k₀, induction k₀, refine idp ⬝ _, revert l' q, refine phomotopy_rec_idp' _ _, revert k' p, refine phomotopy_rec_idp' _ _, reflexivity end definition ppi_eq_equiv_natural_gen_refl {B C : A → Type} {f : Π(a : A), B a → C a} {k : Πa, B a} : ppi_eq_equiv_natural_gen (phomotopy.refl (ppi_functor_right f idp (ppi.mk k idp))) (phomotopy.refl (ppi_functor_right f idp (ppi.mk k idp))) idp = ap phomotopy_of_eq !ap1_gen_idp := begin refine !idp_con ⬝ _, refine !phomotopy_rec_idp'_refl ⬝ _, refine ap (transport _ _) !phomotopy_rec_idp'_refl ⬝ _, refine !tr_diag_eq_tr_tr⁻¹ ⬝ _, refine !eq_transport_Fl ⬝ _, refine !ap_inv⁻² ⬝ !inv_inv ⬝ !ap_compose ⬝ ap02 _ _, exact !ap1_gen_idp_eq⁻¹ end definition loop_pppi_pequiv [constructor] {A : Type*} (B : A → Type*) : Ω (Π*a, B a) ≃* Π*(a : A), Ω (B a) := pequiv_of_equiv !ppi_eq_equiv idp definition loop_pppi_pequiv_natural {A : Type*} {X Y : A → Type*} (f : Π (a : A), X a →* Y a) : psquare (Ω→ (pppi_compose_left f)) (pppi_compose_left (λ a, Ω→ (f a))) (loop_pppi_pequiv X) (loop_pppi_pequiv Y) := begin revert Y f, refine fiberwise_pointed_map_rec _ _, intro Y f, fapply phomotopy.mk, { exact ppi_eq_equiv_natural_gen (pmap_compose_ppi_ppi_const (λa, pmap_of_map (f a) pt)) (pmap_compose_ppi_ppi_const (λa, pmap_of_map (f a) pt)) }, { exact !ppi_eq_equiv_natural_gen_refl ◾ (!idp_con ⬝ !eq_of_phomotopy_refl) } end /- below is an alternate proof strategy for the naturality of loop_pppi_pequiv_natural, where we define loop_pppi_pequiv as composite of pointed equivalences, and proved the naturality individually. That turned out to be harder. -/ /- definition loop_pppi_pequiv2 {A : Type*} (B : A → Type*) : Ω (Π*a, B a) ≃* Π*(a : A), Ω (B a) := begin refine loop_pequiv_loop (pppi.sigma_char B) ⬝e* _, refine !loop_psigma_gen ⬝e* _, transitivity @psigma_gen (Πᵘ*a, Ω (B a)) (λf, f pt = idp) idp, exact psigma_gen_pequiv_psigma_gen (loop_pupi B) (λp, eq_pathover_equiv_Fl p idp idp ⬝e equiv_eq_closed_right _ (whisker_right _ (ap_eq_apd10 p _)) ⬝e !eq_equiv_eq_symm) idpo, exact (pppi.sigma_char (Ω ∘ B))⁻¹ᵉ* end definition loop_pppi_pequiv_natural2 {A : Type*} {X Y : A → Type*} (f : Π (a : A), X a →* Y a) : psquare (Ω→ (pppi_compose_left f)) (pppi_compose_left (λ a, Ω→ (f a))) (loop_pppi_pequiv2 X) (loop_pppi_pequiv2 Y) := begin refine ap1_psquare (pppi_sigma_char_natural f) ⬝v* _, refine !loop_psigma_gen_natural ⬝v* _, refine _ ⬝v* (pppi_sigma_char_natural (λ a, Ω→ (f a)))⁻¹ᵛ*, fapply psigma_gen_functor_psquare, { apply loop_pupi_natural }, { intro p q, exact sorry }, { exact sorry } end-/ end pointed open pointed open is_trunc is_conn namespace is_conn section variables (A : Type*) (n : ℕ₋₂) [H : is_conn (n.+1) A] include H definition is_contr_ppi_match (P : A → Type*) (H : Πa, is_trunc (n.+1) (P a)) : is_contr (Π*(a : A), P a) := begin apply is_contr.mk pt, intro f, induction f with f p, apply eq_of_phomotopy, fapply phomotopy.mk, { apply is_conn.elim n, exact p⁻¹ }, { krewrite (is_conn.elim_β n), apply con.left_inv } end -- definition is_trunc_ppi_of_is_conn (k : ℕ₋₂) (P : A → Type*) -- : is_trunc k.+1 (Π*(a : A), P a) := definition is_trunc_ppi_of_is_conn (k l : ℕ₋₂) (H2 : l ≤ n.+1+2+k) (P : A → Type*) (H3 : Πa, is_trunc l (P a)) : is_trunc k.+1 (Π*(a : A), P a) := begin have H4 : Πa, is_trunc (n.+1+2+k) (P a), from λa, is_trunc_of_le (P a) H2, clear H2 H3, revert P H4, induction k with k IH: intro P H4, { apply is_prop_of_imp_is_contr, intro f, apply is_contr_ppi_match A n P H4 }, { apply is_trunc_succ_of_is_trunc_loop (trunc_index.succ_le_succ (trunc_index.minus_two_le k)), intro f, apply @is_trunc_equiv_closed_rev _ _ k.+1 (ppi_loop_equiv f), apply IH, intro a, apply is_trunc_loop, apply H4 } end definition is_trunc_pmap_of_is_conn (k l : ℕ₋₂) (B : Type*) (H2 : l ≤ n.+1+2+k) (H3 : is_trunc l B) : is_trunc k.+1 (A →* B) := @is_trunc_equiv_closed _ _ k.+1 (pppi_equiv_pmap A B) (is_trunc_ppi_of_is_conn A n k l H2 (λ a, B) _) end -- this is probably much easier to prove directly definition is_trunc_ppi (A : Type*) (n k : ℕ₋₂) (H : n ≤ k) (P : A → Type*) (H2 : Πa, is_trunc n (P a)) : is_trunc k (Π*(a : A), P a) := begin cases k with k, { apply is_contr_of_merely_prop, { exact @is_trunc_ppi_of_is_conn A -2 (is_conn_minus_one A (tr pt)) -2 _ (trunc_index.le.step H) P H2 }, { exact tr pt } }, { assert K : n ≤ -1 +2+ k, { rewrite (trunc_index.add_plus_two_comm -1 k), exact H }, { exact @is_trunc_ppi_of_is_conn A -2 (is_conn_minus_one A (tr pt)) k _ K P H2 } } end end is_conn
4d4fa03621e662f4314e81c708636aaac1e2c645
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/inductions.lean
abc02313996b3af4b1162c5cc0da2a140062c56b
[ "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
6,547
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Damiano Testa, Jens Wagemaker -/ import algebra.monoid_algebra.division import data.nat.interval import data.polynomial.degree.definitions import data.polynomial.induction /-! # Induction on polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains lemmas dealing with different flavours of induction on polynomials. -/ noncomputable theory open_locale classical big_operators polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section semiring variables [semiring R] {p q : R[X]} /-- `div_X p` returns a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : R[X]) : R[X] := ⟨add_monoid_algebra.div_of p.to_finsupp 1⟩ @[simp] lemma coeff_div_X : (div_X p).coeff n = p.coeff (n+1) := by { rw [add_comm], cases p, refl } lemma div_X_mul_X_add (p : R[X]) : div_X p * X + C (p.coeff 0) = p := ext $ by rintro ⟨_|_⟩; simp [coeff_C, nat.succ_ne_zero, coeff_mul_X] @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by simp [coeff_div_X, coeff_C, finsupp.single_eq_of_ne _] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by haveI := nontrivial.of_polynomial_ne hp0; calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : R[X]) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul' this]; exact add_le_add (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) le_rfl, by rw [degree_add_eq_left_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : congr_arg _ (div_X_mul_X_add _) /-- An induction principle for polynomials, valued in Sort* instead of Prop. -/ @[elab_as_eliminator] noncomputable def rec_on_horner {M : R[X] → Sort*} : Π (p : R[X]), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} /-- A property holds for all polynomials of positive `degree` with coefficients in a semiring `R` if it holds for * `a * X`, with `a ∈ R`, * `p * X`, with `p ∈ R[X]`, * `p + a`, with `a ∈ R`, `p ∈ R[X]`, with appropriate restrictions on each term. See `nat_degree_ne_zero_induction_on` for a similar statement involving no explicit multiplication. -/ @[elab_as_eliminator] lemma degree_pos_induction_on {P : R[X] → Prop} (p : R[X]) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 /-- A property holds for all polynomials of non-zero `nat_degree` with coefficients in a semiring `R` if it holds for * `p + a`, with `a ∈ R`, `p ∈ R[X]`, * `p + q`, with `p, q ∈ R[X]`, * monomials with nonzero coefficient and non-zero exponent, with appropriate restrictions on each term. Note that multiplication is "hidden" in the assumption on monomials, so there is no explicit multiplication in the statement. See `degree_pos_induction_on` for a similar statement involving more explicit multiplications. -/ @[elab_as_eliminator] lemma nat_degree_ne_zero_induction_on {M : R[X] → Prop} {f : R[X]} (f0 : f.nat_degree ≠ 0) (h_C_add : ∀ {a p}, M p → M (C a + p)) (h_add : ∀ {p q}, M p → M q → M (p + q)) (h_monomial : ∀ {n : ℕ} {a : R}, a ≠ 0 → n ≠ 0 → M (monomial n a)) : M f := suffices f.nat_degree = 0 ∨ M f, from or.dcases_on this (λ h, (f0 h).elim) id, begin apply f.induction_on, { exact λ a, or.inl (nat_degree_C _) }, { rintros p q (hp | hp) (hq | hq), { refine or.inl _, rw [eq_C_of_nat_degree_eq_zero hp, eq_C_of_nat_degree_eq_zero hq, ← C_add, nat_degree_C] }, { refine or.inr _, rw [eq_C_of_nat_degree_eq_zero hp], exact h_C_add hq }, { refine or.inr _, rw [eq_C_of_nat_degree_eq_zero hq, add_comm], exact h_C_add hp }, { exact or.inr (h_add hp hq) } }, { intros n a hi, by_cases a0 : a = 0, { exact or.inl (by rw [a0, C_0, zero_mul, nat_degree_zero]) }, { refine or.inr _, rw C_mul_X_pow_eq_monomial, exact h_monomial a0 n.succ_ne_zero } } end end semiring end polynomial
8ae31f40289a28e0f0a129a1f2e3e24f80ad5bfb
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_467.lean
85359895c5f8bf7c0be438d377e9adc8cd97054c
[]
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
194
lean
variables p q r : Prop -- BEGIN example (h : p ∧ (q ∧ r)) : (p ∧ q) ∧ r := begin cases h with h₂ h₃, split, { split, { sorry, }, { sorry, }, }, { sorry, }, end -- END
a3a2aaa717699e69d23a57dd7464106767db5c28
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/data/finset.lean
cee0d51fc26967371e2ded14ca89a84c7c597220
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
92,086
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding algebra.order_functions data.multiset data.sigma.basic data.set.lattice open multiset subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /- set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl /- extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[extensionality] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /- subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /- empty -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem exists_mem_iff_ne_empty {s : finset α} : (∃ a : α, a ∈ s) ↔ ¬s = ∅ := ⟨λ ⟨a, ha⟩, ne_empty_of_mem ha, exists_mem_of_ne_empty⟩ @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl lemma nonempty_iff_ne_empty (s : finset α) : nonempty (↑s : set α) ↔ s ≠ ∅ := begin rw [set.coe_nonempty_iff_ne_empty, ←coe_empty], apply not_congr, apply function.injective.eq_iff, exact to_set_injective end /-- `singleton a` is the set `{a}` containing `a` and nothing else. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl /- insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ @[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl @[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ /- union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] @[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] /- inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /- lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.lattice.semilattice_inf_bot, ..finset.lattice.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /- erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /- sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) @[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff end decidable_eq /- attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /- filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) := by {ext, simp [and_assoc], rw [and.left_comm] } theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter(eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, insert_empty_eq_singleton, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end end filter /- range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩, ⟨max (a + 1) n, insert_subset.2 ⟨by simpa only [mem_range] using le_max_left (a+1) n, subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩ end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /- erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset section map open function def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 @[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] @[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] @[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm] protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff [decidable_eq α] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi] end end image /- card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on [decidable_eq β] {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt}) lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from function.injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)⟩, subtype.ext.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a := show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _ theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := by { ext x, simp, exact ⟨λ ⟨xt, y, ys, xf⟩, ⟨y, ys, xt, xf⟩, λ ⟨y, ys, xt, xf⟩, ⟨xt, y, ys, xf⟩⟩ } theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma section pi variables {δ : α → Type*} [decidable_eq α] def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end end pi section powerset def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) end powerset section powerset_len def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] end fold section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := calc _ = f b ⊔ (∅:finset β).sup f : sup_insert ... = f b : sup_bot_eq lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := calc _ = f b ⊓ (∅:finset β).inf f : inf_insert ... = f b : inf_top_eq lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /- max and min of finite sets -/ section max_min variables [decidable_linear_order α] protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption lemma exists_min (s : finset β) (f : β → α) (h : nonempty ↥(↑s : set β)) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := begin have : s.image f ≠ ∅, rwa [ne, image_eq_empty, ← ne.def, ← nonempty_iff_ne_empty], cases min_of_ne_empty this with y hy, rcases mem_image.mp (mem_of_min hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', min_le_of_mem (mem_image_of_mem f hx') hy⟩ end end max_min section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} [decidable_eq ι] (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} end disjoint theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] def min' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.min $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] def max' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.max $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (S : finset α) (H : S ≠ ∅) theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le S H i H1, have H6 := le_max' S H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le S H j H2, have H6 := le_max' S H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end decidable_linear_order /- Ico (a closed open interval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty (n : ℕ) : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff theorem subset_iff {m₁ n₁ m₂ n₂ : ℕ} (hmn : m₁ < n₁) : Ico m₁ n₁ ⊆ Ico m₂ n₂ ↔ (m₂ ≤ m₁ ∧ n₁ ≤ n₂) := begin simp only [subset_iff, mem], refine ⟨λ h, ⟨_, _⟩, _⟩, { exact (h ⟨le_refl _, hmn⟩).1 }, { refine le_of_pred_lt (@h (pred n₁) ⟨le_pred_of_lt hmn, pred_lt _⟩).2, exact ne_of_gt (lt_of_le_of_lt (nat.zero_le m₁) hmn) }, { rintros ⟨hm, hn⟩ k ⟨hmk, hkn⟩, exact ⟨le_trans hm hmk, lt_of_lt_of_le hkn hn⟩ } end lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end lemma disjoint_consecutive (n m l : ℕ) : disjoint (Ico n m) (Ico m l) := le_of_eq $ inter_consecutive n m l @[simp] theorem succ_singleton (n : ℕ) : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = insert n (Ico (n + 1) m) := by rw [← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := eq_of_veq $ multiset.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := eq_of_veq $ multiset.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := eq_of_veq $ multiset.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_le n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico -- TODO We don't yet attempt to reproduce the entire interface for `Ico` for `Ico_ℤ`. /-- `Ico_ℤ l u` is the set of integers `l ≤ k < u`. -/ def Ico_ℤ (l u : ℤ) : finset ℤ := (finset.range (u - l).to_nat).map { to_fun := λ n, n + l, inj := λ n m h, by simpa using h } namespace Ico_ℤ @[simp] lemma mem {n m l : ℤ} : l ∈ Ico_ℤ n m ↔ n ≤ l ∧ l < m := begin dsimp [Ico_ℤ], simp only [int.lt_to_nat, exists_prop, mem_range, add_comm, function.embedding.coe_fn_mk, mem_map], split, { rintro ⟨a, ⟨h, rfl⟩⟩, exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ }, { rintro ⟨h₁, h₂⟩, use (l - n).to_nat, split; simp [h₁, h₂], } end end Ico_ℤ end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace lattice variables {ι : Sort*} [complete_lattice α] [decidable_eq ι] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end lattice namespace set variables {ι : Sort*} [decidable_eq ι] lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := lattice.supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := lattice.infi_eq_infi_finset s end set namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := (multiset.nat.antidiagonal n).to_finset /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, multiset.mem_to_finset, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simpa using list.to_finset_card_of_nodup (list.nat.nodup_antidiagonal n) /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, multiset.nat.antidiagonal_zero], refl } end nat end finset
7af53e1d2d96ecee9ce92a9f7eb2a5c8612bf10e
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/topology/algebra/uniform_group.lean
4b38cfc1886f4bbd136f25816020c83a38ce67cd
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
19,567
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Uniform structure on topological groups: * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ import topology.uniform_space.uniform_embedding topology.uniform_space.complete_separated import topology.algebra.group tactic.abel noncomputable theory open_locale classical uniformity topological_space section uniform_add_group open filter set variables {α : Type*} {β : Type*} /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub α lemma uniform_continuous.sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := uniform_continuous_sub.comp (hf.prod_mk hg) lemma uniform_continuous.neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_const.sub hf, by simp * at * lemma uniform_continuous_neg : uniform_continuous (λx:α, - x) := uniform_continuous_id.neg lemma uniform_continuous.add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from hf.sub hg.neg, by simp [*, sub_eq_add_neg] at * lemma uniform_continuous_add : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_fst.add uniform_continuous_snd @[priority 10] instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add.continuous, continuous_neg := uniform_continuous_neg.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨((uniform_continuous_fst.comp uniform_continuous_fst).sub (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).sub (uniform_continuous_snd.comp uniform_continuous_snd))⟩ lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α := le_antisymm (uniform_continuous_id.add uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_id.add uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := { comap_uniformity := begin rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end, inj := assume x y, eq_of_add_eq_add_right } section variables (α) lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (𝓝 (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap_comp], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_sub hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_sets_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_add hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_nonempty, sub_eq_add_neg] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (𝓝 0) (𝓝 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [is_add_group_hom.map_sub f] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp h tendsto_comap end lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (𝓝 0) (𝓝 (f 0)), by rwa [is_add_group_hom.map_zero f] at this, h.tendsto 0 end uniform_add_group section topological_add_comm_group universes u v w x open filter variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (𝓝 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (𝓝 0)) (𝓝 (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp (tendsto.neg tendsto_id) tendsto_comap end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa [sub_eq_add_neg, add_comm, add_left_comm] using V_sum _ _ Hz1 Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)), rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation a, mem_comap_sets, mem_comap_sets], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : 𝓤 G = comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((𝓝 0).prod (𝓝 0))) (𝓝 (0 - 0)) := (tendsto_fst.sub tendsto_snd).comp tendsto_comap, begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘), sub_eq_add_neg, add_comm, add_left_comm] using this end end lemma to_uniform_space_eq {α : Type*} [u : uniform_space α] [add_comm_group α] [uniform_add_group α]: topological_add_group.to_uniform_space α = u := begin ext : 1, show @uniformity α (topological_add_group.to_uniform_space α) = 𝓤 α, rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α] end end topological_add_comm_group namespace add_comm_group section Z_bilin variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [add_comm_group α] [add_comm_group β] [add_comm_group γ] /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ class is_Z_bilin (f : α × β → γ) : Prop := (add_left : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b)) (add_right : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b')) variables (f : α × β → γ) [is_Z_bilin f] lemma is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_hom.map_add g] instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) := ⟨λ a a' b, is_Z_bilin.add_right f b a a', λ a b b', is_Z_bilin.add_left f b b' a⟩ lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 := begin intro b, apply add_self_iff_eq_zero.1, rw ←is_Z_bilin.add_left f, simp end lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) lemma is_Z_bilin.zero : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) := begin intros a b, apply eq_of_sub_eq_zero, rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f] end lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) := assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) := begin intros, simp [sub_eq_add_neg], rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f] end lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') := assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end Z_bilin end add_comm_group open add_comm_group filter set function section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} -- α, β and G are abelian topological groups, G is a uniform space variables [topological_space α] [add_comm_group α] variables [topological_space β] [add_comm_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (𝓝 (x₁, 0)) (𝓝 0) := begin have := hψ.tendsto (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (𝓝 (0, y₁)) (𝓝 0) := begin have := hψ.tendsto (0, y₁), rwa [is_Z_bilin.zero_left ψ] at this end end section variables {α : Type*} {β : Type*} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← is_add_group_hom.map_sub e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (𝓝 (x₀, x₀)) (𝓝 (e 0)), { have := (continuous_sub.comp continuous_swap).tendsto (x₀, x₀), simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.map_zero e)] using this }, have := de.tendsto_comap_nhds_nhds lim comm, simp [-sub_eq_add_neg, this] end end namespace dense_inducing variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated G] [complete_space G] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_inducing f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := 𝓝 x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (𝓝 (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp (is_Z_bilin.tendsto_zero_right hφ y₁) lim1, rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := 𝓝 x₀, let Ny := 𝓝 y₀, let dp := dense_inducing.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto φ (𝓝 (0, 0)) (𝓝 0), { have := hφ.tendsto (0, 0), rwa [is_Z_bilin.zero φ] at this }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee $ 𝓝 (x₀, x₀)) (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (𝓝 (x₀, x₀))) (comap ff (𝓝 (y₀, y₀)))) (filter.prod (𝓝 0) (𝓝 0)), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_φ lim_sub_sub }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, obtain ⟨x₁, x₁_in⟩ : U₁.nonempty := (forall_sets_nonempty_iff_ne_bot.2 de.comap_nhds_ne_bot U₁ U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := (forall_sets_nonempty_iff_ne_bot.2 df.comap_nhds_ne_bot V₁ V₁_nhd), rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (hφ.comp continuous_swap) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y), { repeat { rw is_Z_bilin.sub_left φ }, repeat { rw is_Z_bilin.sub_right φ }, apply eq_of_sub_eq_zero, simp [sub_eq_add_neg], abel }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (de.prod df) φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_ne_bot, intros U h, rcases mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (filter.prod (𝓝 (x₀, y₀)) (𝓝 (x₀, y₀)))) ≤ 𝓝 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap_sets at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap_sets at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap_sets, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ 𝓝 x₀ at U'_nhd, change V' ∈ 𝓝 y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
9df80b106fad6948edcb7e28a4d9f3e1faeed875
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world1/level2.lean
2d6539b696603e3c1648395624ab2f557f1f69b6
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
200
lean
import mynat.definition import mynat.add import mynat.mul namespace mynat lemma example2 (x y : mynat) (h : y = x + 7) : 2 * y = 2 * (x + 7) := begin [nat_num_game] rw h, refl end end mynat
cee4c1228c7e8d81af91b2e4b379d4ad12d97873
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/cache.lean
a2149447fbc6c5e351549f2893d8705e325b2f51
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
2,116
lean
import tactic.basic open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types /-- Unfreeze local instances, which allows us to revert instances in the context. -/ meta def unfreezeI := tactic.unfreeze_local_instances /-- Reset the instance cache. This allows any new instances added to the context to be used in typeclass inference. -/ meta def resetI := reset_instance_cache /-- Like `intro`, but uses the introduced variable in typeclass inference. -/ meta def introI (p : parse ident_?) : tactic unit := intro p >> reset_instance_cache /-- Like `intros`, but uses the introduced variable(s) in typeclass inference. -/ meta def introsI (p : parse ident_*) : tactic unit := intros p >> reset_instance_cache /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `have`, but the proof-omitted version is not supported. For this one must write `have : t, { <proof> }, resetI, <proof>`. -/ meta def haveI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse (tk ":=" *> texpr)) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «have» (some h) q₁ (some q₂), match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `let`. -/ meta def letI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «let» (some h) q₁ q₂, match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Like `exact`, but uses all variables in the context for typeclass inference. -/ meta def exactI (q : parse texpr) : tactic unit := reset_instance_cache >> exact q end interactive end tactic
d584f8c66c94806faa57cafe988907d3825cb413
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/box_integral/integrability.lean
99f0439fc7155afb6502039c41867b0f7fd543bf
[ "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
17,862
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.basic import measure_theory.measure.regular /-! # McShane integrability vs Bochner integrability In this file we prove that any Bochner integrable function is McShane integrable (hence, it is Henstock and `⊥` integrable) with the same integral. The proof is based on [Russel A. Gordon, *The integrals of Lebesgue, Denjoy, Perron, and Henstock*][Gordon55]. ## Tags integral, McShane integral, Bochner integral -/ open_locale classical nnreal ennreal topological_space big_operators universes u v variables {ι : Type u} {E : Type v} [fintype ι] [normed_add_comm_group E] [normed_space ℝ E] open measure_theory metric set finset filter box_integral namespace box_integral /-- The indicator function of a measurable set is McShane integrable with respect to any locally-finite measure. -/ lemma has_integral_indicator_const (l : integration_params) (hl : l.bRiemann = ff) {s : set (ι → ℝ)} (hs : measurable_set s) (I : box ι) (y : E) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] : has_integral.{u v v} I l (s.indicator (λ _, y)) μ.to_box_additive.to_smul ((μ (s ∩ I)).to_real • y) := begin refine has_integral_of_mul (∥y∥) (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, rw nnreal.coe_pos at ε0, /- First we choose a closed set `F ⊆ s ∩ I.Icc` and an open set `U ⊇ s` such that both `(s ∩ I.Icc) \ F` and `U \ s` have measuer less than `ε`. -/ have A : μ (s ∩ I.Icc) ≠ ∞, from ((measure_mono $ set.inter_subset_right _ _).trans_lt (I.measure_Icc_lt_top μ)).ne, have B : μ (s ∩ I) ≠ ∞, from ((measure_mono $ set.inter_subset_right _ _).trans_lt (I.measure_coe_lt_top μ)).ne, obtain ⟨F, hFs, hFc, hμF⟩ : ∃ F ⊆ s ∩ I.Icc, is_closed F ∧ μ ((s ∩ I.Icc) \ F) < ε, from (hs.inter I.measurable_set_Icc).exists_is_closed_diff_lt A (ennreal.coe_pos.2 ε0).ne', obtain ⟨U, hsU, hUo, hUt, hμU⟩ : ∃ U ⊇ s ∩ I.Icc, is_open U ∧ μ U < ∞ ∧ μ (U \ (s ∩ I.Icc)) < ε, from (hs.inter I.measurable_set_Icc).exists_is_open_diff_lt A (ennreal.coe_pos.2 ε0).ne', /- Then we choose `r` so that `closed_ball x (r x) ⊆ U` whenever `x ∈ s ∩ I.Icc` and `closed_ball x (r x)` is disjoint with `F` otherwise. -/ have : ∀ x ∈ s ∩ I.Icc, ∃ r : Ioi (0 : ℝ), closed_ball x r ⊆ U, from λ x hx, subtype.exists'.1 (nhds_basis_closed_ball.mem_iff.1 (hUo.mem_nhds $ hsU hx)), choose! rs hrsU, have : ∀ x ∈ I.Icc \ s, ∃ r : Ioi (0 : ℝ), closed_ball x r ⊆ Fᶜ, from λ x hx, subtype.exists'.1 (nhds_basis_closed_ball.mem_iff.1 (hFc.is_open_compl.mem_nhds $ λ hx', hx.2 (hFs hx').1)), choose! rs' hrs'F, set r : (ι → ℝ) → Ioi (0 : ℝ) := s.piecewise rs rs', refine ⟨λ c, r, λ c, l.r_cond_of_bRiemann_eq_ff hl, λ c π hπ hπp, _⟩, rw mul_comm, /- Then the union of boxes `J ∈ π` such that `π.tag ∈ s` includes `F` and is included by `U`, hence its measure is `ε`-close to the measure of `s`. -/ dsimp [integral_sum], simp only [mem_closed_ball, dist_eq_norm, ← indicator_const_smul_apply, sum_indicator_eq_sum_filter, ← sum_smul, ← sub_smul, norm_smul, real.norm_eq_abs, ← prepartition.filter_boxes, ← prepartition.measure_Union_to_real], refine mul_le_mul_of_nonneg_right _ (norm_nonneg y), set t := (π.to_prepartition.filter (λ J, π.tag J ∈ s)).Union, change abs ((μ t).to_real - (μ (s ∩ I)).to_real) ≤ ε, have htU : t ⊆ U ∩ I, { simp only [t, prepartition.Union_def, Union_subset_iff, prepartition.mem_filter, and_imp], refine λ J hJ hJs x hx, ⟨hrsU _ ⟨hJs, π.tag_mem_Icc J⟩ _, π.le_of_mem' J hJ hx⟩, simpa only [r, s.piecewise_eq_of_mem _ _ hJs] using hπ.1 J hJ (box.coe_subset_Icc hx) }, refine abs_sub_le_iff.2 ⟨_, _⟩, { refine (ennreal.le_to_real_sub B).trans (ennreal.to_real_le_coe_of_le_coe _), refine (tsub_le_tsub (measure_mono htU) le_rfl).trans (le_measure_diff.trans _), refine (measure_mono $ λ x hx, _).trans hμU.le, exact ⟨hx.1.1, λ hx', hx.2 ⟨hx'.1, hx.1.2⟩⟩ }, { have hμt : μ t ≠ ∞ := ((measure_mono (htU.trans (inter_subset_left _ _))).trans_lt hUt).ne, refine (ennreal.le_to_real_sub hμt).trans (ennreal.to_real_le_coe_of_le_coe _), refine le_measure_diff.trans ((measure_mono _).trans hμF.le), rintro x ⟨⟨hxs, hxI⟩, hxt⟩, refine ⟨⟨hxs, box.coe_subset_Icc hxI⟩, λ hxF, hxt _⟩, simp only [t, prepartition.Union_def, prepartition.mem_filter, set.mem_Union, exists_prop], rcases hπp x hxI with ⟨J, hJπ, hxJ⟩, refine ⟨J, ⟨hJπ, _⟩, hxJ⟩, contrapose hxF, refine hrs'F _ ⟨π.tag_mem_Icc J, hxF⟩ _, simpa only [r, s.piecewise_eq_of_not_mem _ _ hxF] using hπ.1 J hJπ (box.coe_subset_Icc hxJ) } end /-- If `f` is a.e. equal to zero on a rectangular box, then it has McShane integral zero on this box. -/ lemma has_integral_zero_of_ae_eq_zero {l : integration_params} {I : box ι} {f : (ι → ℝ) → E} {μ : measure (ι → ℝ)} [is_locally_finite_measure μ] (hf : f =ᵐ[μ.restrict I] 0) (hl : l.bRiemann = ff) : has_integral.{u v v} I l f μ.to_box_additive.to_smul 0 := begin /- Each set `{x | n < ∥f x∥ ≤ n + 1}`, `n : ℕ`, has measure zero. We cover it by an open set of measure less than `ε / 2 ^ n / (n + 1)`. Then the norm of the integral sum is less than `ε`. -/ refine has_integral_iff.2 (λ ε ε0, _), lift ε to ℝ≥0 using ε0.lt.le, rw [gt_iff_lt, nnreal.coe_pos] at ε0, rcases nnreal.exists_pos_sum_of_countable ε0.ne' ℕ with ⟨δ, δ0, c, hδc, hcε⟩, haveI := fact.mk (I.measure_coe_lt_top μ), change μ.restrict I {x | f x ≠ 0} = 0 at hf, set N : (ι → ℝ) → ℕ := λ x, ⌈∥f x∥⌉₊, have N0 : ∀ {x}, N x = 0 ↔ f x = 0, by { intro x, simp [N] }, have : ∀ n, ∃ U ⊇ N ⁻¹' {n}, is_open U ∧ μ.restrict I U < δ n / n, { refine λ n, (N ⁻¹' {n}).exists_is_open_lt_of_lt _ _, cases n, { simpa [ennreal.div_zero (ennreal.coe_pos.2 (δ0 _)).ne'] using measure_lt_top (μ.restrict I) _ }, { refine (measure_mono_null _ hf).le.trans_lt _, { exact λ x hxN hxf, n.succ_ne_zero ((eq.symm hxN).trans $ N0.2 hxf) }, { simp [(δ0 _).ne'] } } }, choose U hNU hUo hμU, have : ∀ x, ∃ r : Ioi (0 : ℝ), closed_ball x r ⊆ U (N x), from λ x, subtype.exists'.1 (nhds_basis_closed_ball.mem_iff.1 ((hUo _).mem_nhds (hNU _ rfl))), choose r hrU, refine ⟨λ _, r, λ c, l.r_cond_of_bRiemann_eq_ff hl, λ c π hπ hπp, _⟩, rw [dist_eq_norm, sub_zero, ← integral_sum_fiberwise (λ J, N (π.tag J))], refine le_trans _ (nnreal.coe_lt_coe.2 hcε).le, refine (norm_sum_le_of_le _ _).trans (sum_le_has_sum _ (λ n _, (δ n).2) (nnreal.has_sum_coe.2 hδc)), rintro n -, dsimp [integral_sum], have : ∀ J ∈ π.filter (λ J, N (π.tag J) = n), ∥(μ ↑J).to_real • f (π.tag J)∥ ≤ (μ J).to_real * n, { intros J hJ, rw tagged_prepartition.mem_filter at hJ, rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact mul_le_mul_of_nonneg_left (hJ.2 ▸ nat.le_ceil _) ennreal.to_real_nonneg }, refine (norm_sum_le_of_le _ this).trans _, clear this, rw [← sum_mul, ← prepartition.measure_Union_to_real], generalize hm : μ (π.filter (λ J, N (π.tag J) = n)).Union = m, have : m < δ n / n, { simp only [measure.restrict_apply (hUo _).measurable_set] at hμU, refine hm ▸ (measure_mono _).trans_lt (hμU _), simp only [set.subset_def, tagged_prepartition.mem_Union, exists_prop, tagged_prepartition.mem_filter], rintro x ⟨J, ⟨hJ, rfl⟩, hx⟩, exact ⟨hrU _ (hπ.1 _ hJ (box.coe_subset_Icc hx)), π.le_of_mem' J hJ hx⟩ }, lift m to ℝ≥0 using ne_top_of_lt this, rw [ennreal.coe_to_real, ← nnreal.coe_nat_cast, ← nnreal.coe_mul, nnreal.coe_le_coe, ← ennreal.coe_le_coe, ennreal.coe_mul, ennreal.coe_nat, mul_comm], exact (mul_le_mul_left' this.le _).trans ennreal.mul_div_le end /-- If `f` has integral `y` on a box `I` with respect to a locally finite measure `μ` and `g` is a.e. equal to `f` on `I`, then `g` has the same integral on `I`. -/ lemma has_integral.congr_ae {l : integration_params} {I : box ι} {y : E} {f g : (ι → ℝ) → E} {μ : measure (ι → ℝ)} [is_locally_finite_measure μ] (hf : has_integral.{u v v} I l f μ.to_box_additive.to_smul y) (hfg : f =ᵐ[μ.restrict I] g) (hl : l.bRiemann = ff) : has_integral.{u v v} I l g μ.to_box_additive.to_smul y := begin have : (g - f) =ᵐ[μ.restrict I] 0, from hfg.mono (λ x hx, sub_eq_zero.2 hx.symm), simpa using hf.add (has_integral_zero_of_ae_eq_zero this hl) end end box_integral namespace measure_theory namespace simple_func /-- A simple function is McShane integrable w.r.t. any locally finite measure. -/ lemma has_box_integral (f : simple_func (ι → ℝ) E) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] (I : box ι) (l : integration_params) (hl : l.bRiemann = ff) : has_integral.{u v v} I l f μ.to_box_additive.to_smul (f.integral (μ.restrict I)) := begin induction f using measure_theory.simple_func.induction with y s hs f g hd hfi hgi, { simpa [function.const, measure.restrict_apply hs] using box_integral.has_integral_indicator_const l hl hs I y μ }, { borelize E, haveI := fact.mk (I.measure_coe_lt_top μ), rw integral_add, exacts [hfi.add hgi, integrable_iff.2 $ λ _ _, measure_lt_top _ _, integrable_iff.2 $ λ _ _, measure_lt_top _ _] } end /-- For a simple function, its McShane (or Henstock, or `⊥`) box integral is equal to its integral in the sense of `measure_theory.simple_func.integral`. -/ lemma box_integral_eq_integral (f : simple_func (ι → ℝ) E) (μ : measure (ι → ℝ)) [is_locally_finite_measure μ] (I : box ι) (l : integration_params) (hl : l.bRiemann = ff) : box_integral.integral.{u v v} I l f μ.to_box_additive.to_smul = f.integral (μ.restrict I) := (f.has_box_integral μ I l hl).integral_eq end simple_func open topological_space /-- If `f : ℝⁿ → E` is Bochner integrable w.r.t. a locally finite measure `μ` on a rectangular box `I`, then it is McShane integrable on `I` with the same integral. -/ lemma integrable_on.has_box_integral [complete_space E] {f : (ι → ℝ) → E} {μ : measure (ι → ℝ)} [is_locally_finite_measure μ] {I : box ι} (hf : integrable_on f I μ) (l : integration_params) (hl : l.bRiemann = ff) : has_integral.{u v v} I l f μ.to_box_additive.to_smul (∫ x in I, f x ∂ μ) := begin borelize E, /- First we replace an `ae_strongly_measurable` function by a measurable one. -/ rcases hf.ae_strongly_measurable with ⟨g, hg, hfg⟩, haveI : separable_space (range g ∪ {0} : set E) := hg.separable_space_range_union_singleton, rw integral_congr_ae hfg, have hgi : integrable_on g I μ := (integrable_congr hfg).1 hf, refine box_integral.has_integral.congr_ae _ hfg.symm hl, clear_dependent f, /- Now consider the sequence of simple functions `simple_func.approx_on g hg.measurable (range g ∪ {0}) 0 (by simp)` approximating `g`. Recall some properties of this sequence. -/ set f : ℕ → simple_func (ι → ℝ) E := simple_func.approx_on g hg.measurable (range g ∪ {0}) 0 (by simp), have hfi : ∀ n, integrable_on (f n) I μ, from simple_func.integrable_approx_on_range hg.measurable hgi, have hfi' := λ n, ((f n).has_box_integral μ I l hl).integrable, have hfgi : tendsto (λ n, (f n).integral (μ.restrict I)) at_top (𝓝 $ ∫ x in I, g x ∂μ), from tendsto_integral_approx_on_of_measurable_of_range_subset hg.measurable hgi _ subset.rfl, have hfg_mono : ∀ x {m n}, m ≤ n → ∥f n x - g x∥ ≤ ∥f m x - g x∥, { intros x m n hmn, rw [← dist_eq_norm, ← dist_eq_norm, dist_nndist, dist_nndist, nnreal.coe_le_coe, ← ennreal.coe_le_coe, ← edist_nndist, ← edist_nndist], exact simple_func.edist_approx_on_mono hg.measurable _ x hmn }, /- Now consider `ε > 0`. We need to find `r` such that for any tagged partition subordinate to `r`, the integral sum is `(μ I + 1 + 1) * ε`-close to the Bochner integral. -/ refine has_integral_of_mul ((μ I).to_real + 1 + 1) (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, rw nnreal.coe_pos at ε0, have ε0' := ennreal.coe_pos.2 ε0, /- Choose `N` such that the integral of `∥f N x - g x∥` is less than or equal to `ε`. -/ obtain ⟨N₀, hN₀⟩ : ∃ N : ℕ, ∫ x in I, ∥f N x - g x∥ ∂μ ≤ ε, { have : tendsto (λ n, ∫⁻ x in I, ∥f n x - g x∥₊ ∂μ) at_top (𝓝 0), from simple_func.tendsto_approx_on_range_L1_nnnorm hg.measurable hgi, refine (this.eventually (ge_mem_nhds ε0')).exists.imp (λ N hN, _), exact integral_coe_le_of_lintegral_coe_le hN }, /- For each `x`, we choose `Nx x ≥ N₀` such that `dist (f Nx x) (g x) ≤ ε`. -/ have : ∀ x, ∃ N₁, N₀ ≤ N₁ ∧ dist (f N₁ x) (g x) ≤ ε, { intro x, have : tendsto (λ n, f n x) at_top (𝓝 $ g x), from simple_func.tendsto_approx_on hg.measurable _ (subset_closure (by simp)), exact ((eventually_ge_at_top N₀).and $ this $ closed_ball_mem_nhds _ ε0).exists }, choose Nx hNx hNxε, /- We also choose a convergent series with `∑' i : ℕ, δ i < ε`. -/ rcases nnreal.exists_pos_sum_of_countable ε0.ne' ℕ with ⟨δ, δ0, c, hδc, hcε⟩, /- Since each simple function `fᵢ` is integrable, there exists `rᵢ : ℝⁿ → (0, ∞)` such that the integral sum of `f` over any tagged prepartition is `δᵢ`-close to the sum of integrals of `fᵢ` over the boxes of this prepartition. For each `x`, we choose `r (Nx x)` as the radius at `x`. -/ set r : ℝ≥0 → (ι → ℝ) → Ioi (0 : ℝ) := λ c x, (hfi' $ Nx x).convergence_r (δ $ Nx x) c x, refine ⟨r, λ c, l.r_cond_of_bRiemann_eq_ff hl, λ c π hπ hπp, _⟩, /- Now we prove the estimate in 3 "jumps": first we replace `g x` in the formula for the integral sum by `f (Nx x)`; then we replace each `μ J • f (Nx (π.tag J)) (π.tag J)` by the Bochner integral of `f (Nx (π.tag J)) x` over `J`, then we jump to the Bochner integral of `g`. -/ refine (dist_triangle4 _ (∑ J in π.boxes, (μ J).to_real • f (Nx $ π.tag J) (π.tag J)) (∑ J in π.boxes, ∫ x in J, f (Nx $ π.tag J) x ∂μ) _).trans _, rw [add_mul, add_mul, one_mul], refine add_le_add_three _ _ _, { /- Since each `f (Nx $ π.tag J)` is `ε`-close to `g (π.tag J)`, replacing the latter with the former in the formula for the integral sum changes the sum at most by `μ I * ε`. -/ rw [← hπp.Union_eq, π.to_prepartition.measure_Union_to_real, sum_mul, integral_sum], refine dist_sum_sum_le_of_le _ (λ J hJ, _), dsimp, rw [dist_eq_norm, ← smul_sub, norm_smul, real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], refine mul_le_mul_of_nonneg_left _ ennreal.to_real_nonneg, rw [← dist_eq_norm'], exact hNxε _ }, { /- We group the terms of both sums by the values of `Nx (π.tag J)`. For each `N`, the sum of Bochner integrals over the boxes is equal to the sum of box integrals, and the sum of box integrals is `δᵢ`-close to the corresponding integral sum due to the Henstock-Sacks inequality. -/ rw [← π.to_prepartition.sum_fiberwise (λ J, Nx (π.tag J)), ← π.to_prepartition.sum_fiberwise (λ J, Nx (π.tag J))], refine le_trans _ (nnreal.coe_lt_coe.2 hcε).le, refine (dist_sum_sum_le_of_le _ (λ n hn, _)).trans (sum_le_has_sum _ (λ n _, (δ n).2) (nnreal.has_sum_coe.2 hδc)), have hNxn : ∀ J ∈ π.filter (λ J, Nx (π.tag J) = n), Nx (π.tag J) = n, from λ J hJ, (π.mem_filter.1 hJ).2, have hrn : ∀ J ∈ π.filter (λ J, Nx (π.tag J) = n), r c (π.tag J) = (hfi' n).convergence_r (δ n) c (π.tag J), { intros J hJ, obtain rfl := hNxn J hJ, refl }, have : l.mem_base_set I c ((hfi' n).convergence_r (δ n) c) (π.filter (λ J, Nx (π.tag J) = n)), from (hπ.filter _).mono' _ le_rfl le_rfl (λ J hJ, (hrn J hJ).le), convert (hfi' n).dist_integral_sum_sum_integral_le_of_mem_base_set (δ0 _) this using 2, { refine sum_congr rfl (λ J hJ, _), simp [hNxn J hJ] }, { refine sum_congr rfl (λ J hJ, _), rw [← simple_func.integral_eq_integral, simple_func.box_integral_eq_integral _ _ _ _ hl, hNxn J hJ], exact (hfi _).mono_set (prepartition.le_of_mem _ hJ) } }, { /- For the last jump, we use the fact that the distance between `f (Nx x) x` and `g x` is less than or equal to the distance between `f N₀ x` and `g x` and the integral of `∥f N₀ x - g x∥` is less than or equal to `ε`. -/ refine le_trans _ hN₀, have hfi : ∀ n (J ∈ π), integrable_on (f n) ↑J μ, from λ n J hJ, (hfi n).mono_set (π.le_of_mem' J hJ), have hgi : ∀ J ∈ π, integrable_on g ↑J μ, from λ J hJ, hgi.mono_set (π.le_of_mem' J hJ), have hfgi : ∀ n (J ∈ π), integrable_on (λ x, ∥f n x - g x∥) J μ, from λ n J hJ, ((hfi n J hJ).sub (hgi J hJ)).norm, rw [← hπp.Union_eq, prepartition.Union_def', integral_finset_bUnion π.boxes (λ J hJ, J.measurable_set_coe) π.pairwise_disjoint hgi, integral_finset_bUnion π.boxes (λ J hJ, J.measurable_set_coe) π.pairwise_disjoint (hfgi _)], refine dist_sum_sum_le_of_le _ (λ J hJ, _), rw [dist_eq_norm, ← integral_sub (hfi _ J hJ) (hgi J hJ)], refine norm_integral_le_of_norm_le (hfgi _ J hJ) (eventually_of_forall $ λ x, _), exact hfg_mono x (hNx (π.tag J)) } end end measure_theory
d9fed6a9bbc34949bf034bdf51305ce3dd215b17
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/partrec_code.lean
a395650237ab9089048672bb016ca6fd65d72586
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,499
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Godel numbering for partial recursive functions. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.computability.partrec import Mathlib.PostPort universes l u_1 u_2 namespace Mathlib namespace nat.partrec theorem rfind' {f : ℕ →. ℕ} (hf : partrec f) : partrec (unpaired fun (a m : ℕ) => roption.map (fun (_x : ℕ) => _x + m) (rfind fun (n : ℕ) => (fun (m : ℕ) => to_bool (m = 0)) <$> f (mkpair a (n + m)))) := sorry inductive code where | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code protected instance inhabited : Inhabited code := { default := zero } protected def const : ℕ → code := sorry theorem const_inj {n₁ : ℕ} {n₂ : ℕ} : code.const n₁ = code.const n₂ → n₁ = n₂ := sorry protected def id : code := pair left right def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) def encode_code : code → ℕ := sorry def of_nat_code : ℕ → code := sorry protected instance denumerable : denumerable code := denumerable.mk' (equiv.mk encode_code of_nat_code sorry encode_of_nat_code) theorem encode_code_eq : encodable.encode = encode_code := rfl theorem of_nat_code_eq : denumerable.of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf : code) (cg : code) : encodable.encode cf < encodable.encode (pair cf cg) ∧ encodable.encode cg < encodable.encode (pair cf cg) := sorry theorem encode_lt_comp (cf : code) (cg : code) : encodable.encode cf < encodable.encode (comp cf cg) ∧ encodable.encode cg < encodable.encode (comp cf cg) := sorry theorem encode_lt_prec (cf : code) (cg : code) : encodable.encode cf < encodable.encode (prec cf cg) ∧ encodable.encode cg < encodable.encode (prec cf cg) := sorry theorem encode_lt_rfind' (cf : code) : encodable.encode cf < encodable.encode (rfind' cf) := sorry theorem pair_prim : primrec₂ pair := sorry theorem comp_prim : primrec₂ comp := sorry theorem prec_prim : primrec₂ prec := sorry theorem rfind_prim : primrec rfind' := sorry theorem rec_prim' {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR : α → code → code → σ → σ → σ := fun (a : α) (cf cg : code) (hf hg : σ) => pr a (cf, cg, hf, hg); let CO : α → code → code → σ → σ → σ := fun (a : α) (cf cg : code) (hf hg : σ) => co a (cf, cg, hf, hg); let PC : α → code → code → σ → σ → σ := fun (a : α) (cf cg : code) (hf hg : σ) => pc a (cf, cg, hf, hg); let RF : α → code → σ → σ := fun (a : α) (cf : code) (hf : σ) => rf a (cf, hf); let F : α → code → σ := fun (a : α) (c : code) => code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a); primrec fun (a : α) => F a (c a) := sorry theorem rec_prim {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec fun (a : α × code × code × σ × σ) => pr (prod.fst a) (prod.fst (prod.snd a)) (prod.fst (prod.snd (prod.snd a))) (prod.fst (prod.snd (prod.snd (prod.snd a)))) (prod.snd (prod.snd (prod.snd (prod.snd a))))) {co : α → code → code → σ → σ → σ} (hco : primrec fun (a : α × code × code × σ × σ) => co (prod.fst a) (prod.fst (prod.snd a)) (prod.fst (prod.snd (prod.snd a))) (prod.fst (prod.snd (prod.snd (prod.snd a)))) (prod.snd (prod.snd (prod.snd (prod.snd a))))) {pc : α → code → code → σ → σ → σ} (hpc : primrec fun (a : α × code × code × σ × σ) => pc (prod.fst a) (prod.fst (prod.snd a)) (prod.fst (prod.snd (prod.snd a))) (prod.fst (prod.snd (prod.snd (prod.snd a)))) (prod.snd (prod.snd (prod.snd (prod.snd a))))) {rf : α → code → σ → σ} (hrf : primrec fun (a : α × code × σ) => rf (prod.fst a) (prod.fst (prod.snd a)) (prod.snd (prod.snd a))) : let F : α → code → σ := fun (a : α) (c : code) => code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a); primrec fun (a : α) => F a (c a) := sorry /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR : α → code → code → σ → σ → σ := fun (a : α) (cf cg : code) (hf hg : σ) => pr a (cf, cg, hf, hg); let CO : α → code → code → σ → σ → σ := fun (a : α) (cf cg : code) (hf hg : σ) => co a (cf, cg, hf, hg); let PC : α → code → code → σ → σ → σ := fun (a : α) (cf cg : code) (hf hg : σ) => pc a (cf, cg, hf, hg); let RF : α → code → σ → σ := fun (a : α) (cf : code) (hf : σ) => rf a (cf, hf); let F : α → code → σ := fun (a : α) (c : code) => code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a); computable fun (a : α) => F a (c a) := sorry def eval : code → ℕ →. ℕ := sorry protected instance has_mem : has_mem (ℕ →. ℕ) code := has_mem.mk fun (f : ℕ →. ℕ) (c : code) => eval c = f @[simp] theorem eval_const (n : ℕ) (m : ℕ) : eval (code.const n) m = roption.some n := sorry @[simp] theorem eval_id (n : ℕ) : eval code.id n = roption.some n := sorry @[simp] theorem eval_curry (c : code) (n : ℕ) (x : ℕ) : eval (curry c n) x = eval c (mkpair n x) := sorry theorem const_prim : primrec code.const := sorry theorem curry_prim : primrec₂ curry := primrec₂.comp comp_prim primrec.fst (primrec₂.comp pair_prim (primrec.comp const_prim primrec.snd) (primrec.const code.id)) theorem curry_inj {c₁ : code} {c₂ : code} {n₁ : ℕ} {n₂ : ℕ} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := sorry theorem smn : ∃ (f : code → ℕ → code), computable₂ f ∧ ∀ (c : code) (n x : ℕ), eval (f c n) x = eval c (mkpair n x) := Exists.intro curry { left := primrec₂.to_comp curry_prim, right := eval_curry } theorem exists_code {f : ℕ →. ℕ} : partrec f ↔ ∃ (c : code), eval c = f := sorry def evaln (k : ℕ) : code → ℕ → Option ℕ := sorry theorem evaln_bound {k : ℕ} {c : code} {n : ℕ} {x : ℕ} : x ∈ evaln k c n → n < k := sorry theorem evaln_mono {k₁ : ℕ} {k₂ : ℕ} {c : code} {n : ℕ} {x : ℕ} : k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n := sorry theorem evaln_sound {k : ℕ} {c : code} {n : ℕ} {x : ℕ} : x ∈ evaln k c n → x ∈ eval c n := sorry theorem evaln_complete {c : code} {n : ℕ} {x : ℕ} : x ∈ eval c n ↔ ∃ (k : ℕ), x ∈ evaln k c n := sorry theorem evaln_prim : primrec fun (a : (ℕ × code) × ℕ) => evaln (prod.fst (prod.fst a)) (prod.snd (prod.fst a)) (prod.snd a) := sorry theorem eval_eq_rfind_opt (c : code) (n : ℕ) : eval c n = rfind_opt fun (k : ℕ) => evaln k c n := roption.ext fun (x : ℕ) => iff.trans evaln_complete (iff.symm (rfind_opt_mono fun (a m n_1 : ℕ) (hl : m ≤ n_1) => evaln_mono hl)) theorem eval_part : partrec₂ eval := sorry theorem fixed_point {f : code → code} (hf : computable f) : ∃ (c : code), eval (f c) = eval c := sorry theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ (c : code), eval c = f c := sorry
e4fb5cc4e574d461716abd86eba94f7cef3e5840
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/subobject/limits.lean
0785df513c8cd0d3a3219ede9e38c2409ce979d9
[ "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
13,952
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.subobject.lattice /-! # Specific subobjects We define `equalizer_subobject`, `kernel_subobject` and `image_subobject`, which are the subobjects represented by the equalizer, kernel and image of (a pair of) morphism(s) and provide conditions for `P.factors f`, where `P` is one of these special subobjects. TODO: Add conditions for when `P` is a pullback subobject. TODO: an iff characterisation of `(image_subobject f).factors h` -/ universes v u noncomputable theory open category_theory category_theory.category category_theory.limits category_theory.subobject variables {C : Type u} [category.{v} C] {X Y Z : C} namespace category_theory namespace limits section equalizer variables (f g : X ⟶ Y) [has_equalizer f g] /-- The equalizer of morphisms `f g : X ⟶ Y` as a `subobject X`. -/ abbreviation equalizer_subobject : subobject X := subobject.mk (equalizer.ι f g) /-- The underlying object of `equalizer_subobject f g` is (up to isomorphism!) the same as the chosen object `equalizer f g`. -/ def equalizer_subobject_iso : (equalizer_subobject f g : C) ≅ equalizer f g := subobject.underlying_iso (equalizer.ι f g) @[simp, reassoc] lemma equalizer_subobject_arrow : (equalizer_subobject_iso f g).hom ≫ equalizer.ι f g = (equalizer_subobject f g).arrow := by simp [equalizer_subobject_iso] @[simp, reassoc] lemma equalizer_subobject_arrow' : (equalizer_subobject_iso f g).inv ≫ (equalizer_subobject f g).arrow = equalizer.ι f g := by simp [equalizer_subobject_iso] @[reassoc] lemma equalizer_subobject_arrow_comp : (equalizer_subobject f g).arrow ≫ f = (equalizer_subobject f g).arrow ≫ g := by rw [←equalizer_subobject_arrow, category.assoc, category.assoc, equalizer.condition] lemma equalizer_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = h ≫ g) : (equalizer_subobject f g).factors h := ⟨equalizer.lift h w, by simp⟩ lemma equalizer_subobject_factors_iff {W : C} (h : W ⟶ X) : (equalizer_subobject f g).factors h ↔ h ≫ f = h ≫ g := ⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc, equalizer_subobject_arrow_comp, category.assoc], equalizer_subobject_factors f g h⟩ end equalizer section kernel variables [has_zero_morphisms C] (f : X ⟶ Y) [has_kernel f] /-- The kernel of a morphism `f : X ⟶ Y` as a `subobject X`. -/ abbreviation kernel_subobject : subobject X := subobject.mk (kernel.ι f) /-- The underlying object of `kernel_subobject f` is (up to isomorphism!) the same as the chosen object `kernel f`. -/ def kernel_subobject_iso : (kernel_subobject f : C) ≅ kernel f := subobject.underlying_iso (kernel.ι f) @[simp, reassoc] lemma kernel_subobject_arrow : (kernel_subobject_iso f).hom ≫ kernel.ι f = (kernel_subobject f).arrow := by simp [kernel_subobject_iso] @[simp, reassoc] lemma kernel_subobject_arrow' : (kernel_subobject_iso f).inv ≫ (kernel_subobject f).arrow = kernel.ι f := by simp [kernel_subobject_iso] @[simp, reassoc] lemma kernel_subobject_arrow_comp : (kernel_subobject f).arrow ≫ f = 0 := by { rw [←kernel_subobject_arrow], simp only [category.assoc, kernel.condition, comp_zero], } lemma kernel_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : (kernel_subobject f).factors h := ⟨kernel.lift _ h w, by simp⟩ lemma kernel_subobject_factors_iff {W : C} (h : W ⟶ X) : (kernel_subobject f).factors h ↔ h ≫ f = 0 := ⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc, kernel_subobject_arrow_comp, comp_zero], kernel_subobject_factors f h⟩ /-- A factorisation of `h : W ⟶ X` through `kernel_subobject f`, assuming `h ≫ f = 0`. -/ def factor_thru_kernel_subobject {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : W ⟶ kernel_subobject f := (kernel_subobject f).factor_thru h (kernel_subobject_factors f h w) @[simp] lemma factor_thru_kernel_subobject_comp_arrow {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : factor_thru_kernel_subobject f h w ≫ (kernel_subobject f).arrow = h := by { dsimp [factor_thru_kernel_subobject], simp, } @[simp] lemma factor_thru_kernel_subobject_comp_kernel_subobject_iso {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : factor_thru_kernel_subobject f h w ≫ (kernel_subobject_iso f).hom = kernel.lift f h w := (cancel_mono (kernel.ι f)).1 $ by simp section variables {f} {X' Y' : C} {f' : X' ⟶ Y'} [has_kernel f'] /-- A commuting square induces a morphism between the kernel subobjects. -/ def kernel_subobject_map (sq : arrow.mk f ⟶ arrow.mk f') : (kernel_subobject f : C) ⟶ (kernel_subobject f' : C) := subobject.factor_thru _ ((kernel_subobject f).arrow ≫ sq.left) (kernel_subobject_factors _ _ (by simp [sq.w])) @[simp, reassoc] lemma kernel_subobject_map_arrow (sq : arrow.mk f ⟶ arrow.mk f') : kernel_subobject_map sq ≫ (kernel_subobject f').arrow = (kernel_subobject f).arrow ≫ sq.left := by simp [kernel_subobject_map] @[simp] lemma kernel_subobject_map_id : kernel_subobject_map (𝟙 (arrow.mk f)) = 𝟙 _ := by { ext, simp, dsimp, simp, } -- See library note [dsimp, simp]. @[simp] lemma kernel_subobject_map_comp {X'' Y'' : C} {f'' : X'' ⟶ Y''} [has_kernel f''] (sq : arrow.mk f ⟶ arrow.mk f') (sq' : arrow.mk f' ⟶ arrow.mk f'') : kernel_subobject_map (sq ≫ sq') = kernel_subobject_map sq ≫ kernel_subobject_map sq' := by { ext, simp, } end @[simp] lemma kernel_subobject_zero {A B : C} : kernel_subobject (0 : A ⟶ B) = ⊤ := (is_iso_iff_mk_eq_top _).mp (by apply_instance) instance is_iso_kernel_subobject_zero_arrow : is_iso (kernel_subobject (0 : X ⟶ Y)).arrow := (is_iso_arrow_iff_eq_top _).mpr kernel_subobject_zero lemma le_kernel_subobject (A : subobject X) (h : A.arrow ≫ f = 0) : A ≤ kernel_subobject f := subobject.le_mk_of_comm (kernel.lift f A.arrow h) (by simp) /-- The isomorphism between the kernel of `f ≫ g` and the kernel of `g`, when `f` is an isomorphism. -/ def kernel_subobject_iso_comp {X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] : (kernel_subobject (f ≫ g) : C) ≅ (kernel_subobject g : C) := (kernel_subobject_iso _) ≪≫ (kernel_is_iso_comp f g) ≪≫ (kernel_subobject_iso _).symm @[simp] lemma kernel_subobject_iso_comp_hom_arrow {X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] : (kernel_subobject_iso_comp f g).hom ≫ (kernel_subobject g).arrow = (kernel_subobject (f ≫ g)).arrow ≫ f := by { simp [kernel_subobject_iso_comp], } @[simp] lemma kernel_subobject_iso_comp_inv_arrow {X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] : (kernel_subobject_iso_comp f g).inv ≫ (kernel_subobject (f ≫ g)).arrow = (kernel_subobject g).arrow ≫ inv f := by { simp [kernel_subobject_iso_comp], } /-- The kernel of `f` is always a smaller subobject than the kernel of `f ≫ h`. -/ lemma kernel_subobject_comp_le (f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [has_kernel (f ≫ h)]: kernel_subobject f ≤ kernel_subobject (f ≫ h) := le_kernel_subobject _ _ (by simp) /-- Postcomposing by an monomorphism does not change the kernel subobject. -/ @[simp] lemma kernel_subobject_comp_mono (f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] : kernel_subobject (f ≫ h) = kernel_subobject f := le_antisymm (le_kernel_subobject _ _ ((cancel_mono h).mp (by simp))) (kernel_subobject_comp_le f h) instance kernel_subobject_comp_mono_is_iso (f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] : is_iso (subobject.of_le _ _ (kernel_subobject_comp_le f h)) := begin rw of_le_mk_le_mk_of_comm (kernel_comp_mono f h).inv, { apply_instance, }, { simp, }, end end kernel section image variables (f : X ⟶ Y) [has_image f] /-- The image of a morphism `f g : X ⟶ Y` as a `subobject Y`. -/ abbreviation image_subobject : subobject Y := subobject.mk (image.ι f) /-- The underlying object of `image_subobject f` is (up to isomorphism!) the same as the chosen object `image f`. -/ def image_subobject_iso : (image_subobject f : C) ≅ image f := subobject.underlying_iso (image.ι f) @[simp, reassoc] lemma image_subobject_arrow : (image_subobject_iso f).hom ≫ image.ι f = (image_subobject f).arrow := by simp [image_subobject_iso] @[simp, reassoc] lemma image_subobject_arrow' : (image_subobject_iso f).inv ≫ (image_subobject f).arrow = image.ι f := by simp [image_subobject_iso] /-- A factorisation of `f : X ⟶ Y` through `image_subobject f`. -/ def factor_thru_image_subobject : X ⟶ image_subobject f := factor_thru_image f ≫ (image_subobject_iso f).inv instance [has_equalizers C] : epi (factor_thru_image_subobject f) := by { dsimp [factor_thru_image_subobject], apply epi_comp, } @[simp, reassoc] lemma image_subobject_arrow_comp : factor_thru_image_subobject f ≫ (image_subobject f).arrow = f := by simp [factor_thru_image_subobject, image_subobject_arrow] lemma image_subobject_arrow_comp_eq_zero [has_zero_morphisms C] {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f] [epi (factor_thru_image_subobject f)] (h : f ≫ g = 0) : (image_subobject f).arrow ≫ g = 0 := zero_of_epi_comp (factor_thru_image_subobject f) $ by simp [h] lemma image_subobject_factors_comp_self {W : C} (k : W ⟶ X) : (image_subobject f).factors (k ≫ f) := ⟨k ≫ factor_thru_image f, by simp⟩ @[simp] lemma factor_thru_image_subobject_comp_self {W : C} (k : W ⟶ X) (h) : (image_subobject f).factor_thru (k ≫ f) h = k ≫ factor_thru_image_subobject f := by { ext, simp, } @[simp] lemma factor_thru_image_subobject_comp_self_assoc {W W' : C} (k : W ⟶ W') (k' : W' ⟶ X) (h) : (image_subobject f).factor_thru (k ≫ k' ≫ f) h = k ≫ k' ≫ factor_thru_image_subobject f := by { ext, simp, } /-- The image of `h ≫ f` is always a smaller subobject than the image of `f`. -/ lemma image_subobject_comp_le {X' : C} (h : X' ⟶ X) (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] : image_subobject (h ≫ f) ≤ image_subobject f := subobject.mk_le_mk_of_comm (image.pre_comp h f) (by simp) section open_locale zero_object variables [has_zero_morphisms C] [has_zero_object C] @[simp] lemma image_subobject_zero_arrow : (image_subobject (0 : X ⟶ Y)).arrow = 0 := by { rw ←image_subobject_arrow, simp, } @[simp] lemma image_subobject_zero {A B : C} : image_subobject (0 : A ⟶ B) = ⊥ := subobject.eq_of_comm (image_subobject_iso _ ≪≫ image_zero ≪≫ subobject.bot_coe_iso_zero.symm) (by simp) end section variables [has_equalizers C] local attribute [instance] epi_comp /-- The morphism `image_subobject (h ≫ f) ⟶ image_subobject f` is an epimorphism when `h` is an epimorphism. In general this does not imply that `image_subobject (h ≫ f) = image_subobject f`, although it will when the ambient category is abelian. -/ instance image_subobject_comp_le_epi_of_epi {X' : C} (h : X' ⟶ X) [epi h] (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] : epi (subobject.of_le _ _ (image_subobject_comp_le h f)) := begin rw of_le_mk_le_mk_of_comm (image.pre_comp h f), { apply_instance, }, { simp, }, end end section variables [has_equalizers C] /-- Postcomposing by an isomorphism gives an isomorphism between image subobjects. -/ def image_subobject_comp_iso (f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] : (image_subobject (f ≫ h) : C) ≅ (image_subobject f : C) := (image_subobject_iso _) ≪≫ (image.comp_iso _ _).symm ≪≫ (image_subobject_iso _).symm @[simp, reassoc] lemma image_subobject_comp_iso_hom_arrow (f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] : (image_subobject_comp_iso f h).hom ≫ (image_subobject f).arrow = (image_subobject (f ≫ h)).arrow ≫ inv h := by simp [image_subobject_comp_iso] @[simp, reassoc] lemma image_subobject_comp_iso_inv_arrow (f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] : (image_subobject_comp_iso f h).inv ≫ (image_subobject (f ≫ h)).arrow = (image_subobject f).arrow ≫ h := by simp [image_subobject_comp_iso] end /-- Precomposing by an isomorphism does not change the image subobject. -/ lemma image_subobject_iso_comp [has_equalizers C] {X' : C} (h : X' ⟶ X) [is_iso h] (f : X ⟶ Y) [has_image f] : image_subobject (h ≫ f) = image_subobject f := le_antisymm (image_subobject_comp_le h f) (subobject.mk_le_mk_of_comm (inv (image.pre_comp h f)) (by simp)) lemma image_subobject_le {A B : C} {X : subobject B} (f : A ⟶ B) [has_image f] (h : A ⟶ X) (w : h ≫ X.arrow = f) : image_subobject f ≤ X := subobject.le_of_comm ((image_subobject_iso f).hom ≫ image.lift { I := (X : C), e := h, m := X.arrow, }) (by simp) lemma image_subobject_le_mk {A B : C} {X : C} (g : X ⟶ B) [mono g] (f : A ⟶ B) [has_image f] (h : A ⟶ X) (w : h ≫ g = f) : image_subobject f ≤ subobject.mk g := image_subobject_le f (h ≫ (subobject.underlying_iso g).inv) (by simp [w]) /-- Given a commutative square between morphisms `f` and `g`, we have a morphism in the category from `image_subobject f` to `image_subobject g`. -/ def image_subobject_map {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g] (sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] : (image_subobject f : C) ⟶ (image_subobject g : C) := (image_subobject_iso f).hom ≫ image.map sq ≫ (image_subobject_iso g).inv @[simp, reassoc] lemma image_subobject_map_arrow {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g] (sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] : image_subobject_map sq ≫ (image_subobject g).arrow = (image_subobject f).arrow ≫ sq.right := begin simp only [image_subobject_map, category.assoc, image_subobject_arrow'], erw [image.map_ι, ←category.assoc, image_subobject_arrow], end end image end limits end category_theory
605f504ffad8f5f6f4a2f35085d17fa962adea34
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/SimpLemmas.lean
78c5fbcee1e337680bcbd366e3849ca4704ec7e4
[ "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
7,101
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Core @[simp] theorem eq_self (a : α) : (a = a) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => rfl) theorem of_eq_true (h : p = True) : p := h ▸ trivial theorem eq_true (h : p) : p = True := propext <| Iff.intro (fun _ => trivial) (fun _ => h) theorem eq_false (h : ¬ p) : p = False := propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h') theorem eq_false' (h : p → False) : p = False := propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h') theorem eq_true_of_decide {p : Prop} {s : Decidable p} (h : decide p = true) : p = True := propext <| Iff.intro (fun h => trivial) (fun _ => of_decide_eq_true h) theorem eq_false_of_decide {p : Prop} {s : Decidable p} (h : decide p = false) : p = False := propext <| Iff.intro (fun h' => absurd h' (of_decide_eq_false h)) (fun h => False.elim h) theorem implies_congr {p₁ p₂ : Sort u} {q₁ q₂ : Sort v} (h₁ : p₁ = p₂) (h₂ : q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) := h₁ ▸ h₂ ▸ rfl theorem implies_congr_ctx {p₁ p₂ q₁ q₂ : Prop} (h₁ : p₁ = p₂) (h₂ : p₂ → q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) := propext <| Iff.intro (fun h hp₂ => have : p₁ := h₁ ▸ hp₂ have : q₁ := h this h₂ hp₂ ▸ this) (fun h hp₁ => have hp₂ : p₂ := h₁ ▸ hp₁ have : q₂ := h hp₂ h₂ hp₂ ▸ this) theorem forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a = q a)) : (∀ a, p a) = (∀ a, q a) := have : p = q := funext h this ▸ rfl theorem let_congr {α : Sort u} {β : Sort v} {a a' : α} {b b' : α → β} (h₁ : a = a') (h₂ : ∀ x, b x = b' x) : (let x := a; b x) = (let x := a'; b' x) := by subst h₁ have : b = b' := funext h₂ subst this rfl theorem let_val_congr {α : Sort u} {β : Sort v} {a a' : α} (b : α → β) (h : a = a') : (let x := a; b x) = (let x := a'; b x) := by subst h rfl theorem let_body_congr {α : Sort u} {β : α → Sort v} {b b' : (a : α) → β a} (a : α) (h : ∀ x, b x = b' x) : (let x := a; b x) = (let x := a; b' x) := by have : b = b' := funext h subst this rfl @[congr] theorem ite_congr {x y u v : α} {s : Decidable b} [Decidable c] (h₁ : b = c) (h₂ : c → x = u) (h₃ : ¬ c → y = v) : ite b x y = ite c u v := by cases Decidable.em c with | inl h => rw [if_pos h]; subst b; rw[if_pos h]; exact h₂ h | inr h => rw [if_neg h]; subst b; rw[if_neg h]; exact h₃ h theorem Eq.mpr_prop {p q : Prop} (h₁ : p = q) (h₂ : q) : p := h₁ ▸ h₂ theorem Eq.mpr_not {p q : Prop} (h₁ : p = q) (h₂ : ¬q) : ¬p := h₁ ▸ h₂ @[congr] theorem dite_congr {s : Decidable b} [Decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h₁ : b = c) (h₂ : (h : c) → x (Eq.mpr_prop h₁ h) = u h) (h₃ : (h : ¬c) → y (Eq.mpr_not h₁ h) = v h) : dite b x y = dite c u v := by cases Decidable.em c with | inl h => rw [dif_pos h]; subst b; rw [dif_pos h]; exact h₂ h | inr h => rw [dif_neg h]; subst b; rw [dif_neg h]; exact h₃ h @[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl @[simp] theorem ite_true (a b : α) : (if True then a else b) = a := rfl @[simp] theorem ite_false (a b : α) : (if False then a else b) = b := rfl @[simp] theorem dite_true {α : Sort u} {t : True → α} {e : ¬ True → α} : (dite True t e) = t True.intro := rfl @[simp] theorem dite_false {α : Sort u} {t : False → α} {e : ¬ False → α} : (dite False t e) = e not_false := rfl @[simp] theorem and_self (p : Prop) : (p ∧ p) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, h⟩) @[simp] theorem and_true (p : Prop) : (p ∧ True) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, trivial⟩) @[simp] theorem true_and (p : Prop) : (True ∧ p) = p := propext <| Iff.intro (fun h => h.2) (fun h => ⟨trivial, h⟩) @[simp] theorem and_false (p : Prop) : (p ∧ False) = False := propext <| Iff.intro (fun h => h.2) (fun h => False.elim h) @[simp] theorem false_and (p : Prop) : (False ∧ p) = False := propext <| Iff.intro (fun h => h.1) (fun h => False.elim h) @[simp] theorem or_self (p : Prop) : (p ∨ p) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => h) (fun h => Or.inl h) @[simp] theorem or_true (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inr trivial) @[simp] theorem true_or (p : Prop) : (True ∨ p) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inl trivial) @[simp] theorem or_false (p : Prop) : (p ∨ False) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => False.elim h) (fun h => Or.inl h) @[simp] theorem false_or (p : Prop) : (False ∨ p) = p := propext <| Iff.intro (fun | Or.inr h => h | Or.inl h => False.elim h) (fun h => Or.inr h) @[simp] theorem iff_self (p : Prop) : (p ↔ p) = True := propext <| Iff.intro (fun h => trivial) (fun _ => Iff.intro id id) @[simp] theorem iff_true (p : Prop) : (p ↔ True) = p := propext <| Iff.intro (fun h => h.mpr trivial) (fun h => Iff.intro (fun _ => trivial) (fun _ => h)) @[simp] theorem true_iff (p : Prop) : (True ↔ p) = p := propext <| Iff.intro (fun h => h.mp trivial) (fun h => Iff.intro (fun _ => h) (fun _ => trivial)) @[simp] theorem iff_false (p : Prop) : (p ↔ False) = ¬p := propext <| Iff.intro (fun h hp => h.mp hp) (fun h => Iff.intro h False.elim) @[simp] theorem false_iff (p : Prop) : (False ↔ p) = ¬p := propext <| Iff.intro (fun h hp => h.mpr hp) (fun h => Iff.intro False.elim h) @[simp] theorem false_implies (p : Prop) : (False → p) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial) @[simp] theorem implies_true (α : Sort u) : (α → True) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial) @[simp] theorem true_implies (p : Prop) : (True → p) = p := propext <| Iff.intro (fun h => h trivial) (by intros; trivial) @[simp] theorem Bool.or_false (b : Bool) : (b || false) = b := by cases b <;> rfl @[simp] theorem Bool.or_true (b : Bool) : (b || true) = true := by cases b <;> rfl @[simp] theorem Bool.false_or (b : Bool) : (false || b) = b := by cases b <;> rfl @[simp] theorem Bool.true_or (b : Bool) : (true || b) = true := by cases b <;> rfl @[simp] theorem Bool.or_self (b : Bool) : (b || b) = b := by cases b <;> rfl @[simp] theorem Bool.and_false (b : Bool) : (b && false) = false := by cases b <;> rfl @[simp] theorem Bool.and_true (b : Bool) : (b && true) = b := by cases b <;> rfl @[simp] theorem Bool.false_and (b : Bool) : (false && b) = false := by cases b <;> rfl @[simp] theorem Bool.true_and (b : Bool) : (true && b) = b := by cases b <;> rfl @[simp] theorem Bool.and_self (b : Bool) : (b && b) = b := by cases b <;> rfl
0872e6e35de002dd3fd17dcbdd86364f6a27cbc9
4727251e0cd73359b15b664c3170e5d754078599
/test/lift.lean
2ff6db4df82ead034d600647f46f9364706804e4
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,773
lean
import data.int.basic import tactic.lift /-! Some tests of the `lift` tactic. -/ example (n m k x z u : ℤ) (hn : 0 < n) (hk : 0 ≤ k + n) (hu : 0 ≤ u) (h : k + n = 2 + x) (f : false) : k + n = m + x := begin lift n to ℕ using le_of_lt hn, guard_target (k + ↑n = m + x), guard_hyp hn : (0 : ℤ) < ↑n, lift m to ℕ, guard_target (k + ↑n = ↑m + x), tactic.swap, guard_target (0 ≤ m), tactic.swap, tactic.num_goals >>= λ n, guard (n = 2), lift (k + n) to ℕ using hk with l hl, guard_hyp l : ℕ, guard_hyp hl : ↑l = k + ↑n, guard_target (↑l = ↑m + x), tactic.success_if_fail (tactic.get_local `hk), lift x to ℕ with y hy, guard_hyp y : ℕ, guard_hyp hy : ↑y = x, guard_target (↑l = ↑m + x), lift z to ℕ with w, guard_hyp w : ℕ, tactic.success_if_fail (tactic.get_local `z), lift u to ℕ using hu with u rfl hu, guard_hyp hu : (0 : ℤ) ≤ ↑u, all_goals { exfalso, assumption }, end -- test lift of functions example (α : Type*) (f : α → ℤ) (hf : ∀ a, 0 ≤ f a) (hf' : ∀ a, f a < 1) (a : α) : 0 ≤ 2 * f a := begin lift f to α → ℕ using hf, guard_target ((0:ℤ) ≤ 2 * (λ i : α, (f i : ℤ)) a), guard_hyp hf' : ∀ a, ((λ i : α, (f i:ℤ)) a) < 1, exact int.coe_nat_nonneg _ end -- fail gracefully when the lifted variable is a local definition example : let n : ℤ := 3 in n = n := begin intro n, success_if_fail_with_msg { lift n to ℕ } ("Cannot substitute variable n, it is a local definition. " ++ "If you really want to do this, use `clear_value` first."), refl end instance can_lift_unit : can_lift unit unit := ⟨id, λ x, true, λ x _, ⟨x, rfl⟩⟩ /- test whether new instances of `can_lift` are added as simp lemmas -/ run_cmd do l ← can_lift_attr.get_cache, guard (`can_lift_unit ∈ l) /- test error messages -/ example (n : ℤ) (hn : 0 < n) : true := begin success_if_fail_with_msg {lift n to ℕ using hn} "lift tactic failed. invalid type ascription, term has type\n 0 < n\nbut is expected to have type\n 0 ≤ n", success_if_fail_with_msg {lift (n : option ℤ) to ℕ} "Failed to find a lift from option ℤ to ℕ. Provide an instance of\n can_lift (option ℤ) ℕ", trivial end example (n : ℤ) : ℕ := begin success_if_fail_with_msg {lift n to ℕ} "lift tactic failed. Tactic is only applicable when the target is a proposition.", exact 0 end instance can_lift_subtype (R : Type*) (P : R → Prop) : can_lift R {x // P x} := { coe := coe, cond := λ x, P x, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } instance can_lift_set (R : Type*) (s : set R) : can_lift R s := { coe := coe, cond := λ x, x ∈ s, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } example {R : Type*} {P : R → Prop} (x : R) (hx : P x) : true := by { lift x to {x // P x} using hx with y, trivial } /-! Test that `lift` elaborates `s` as a type, not as a set. -/ example {R : Type*} {s : set R} (x : R) (hx : x ∈ s) : true := by { lift x to s using hx with y, trivial } example (n : ℤ) (hn : 0 ≤ n) : true := by { lift n to ℕ, trivial, exact hn } example (n : ℤ) (hn : 0 ≤ n) : true := by { lift n to ℕ using hn, trivial } example (n : ℤ) (hn : n ≥ 0) : true := by { lift n to ℕ using ge.le _, trivial, guard_target (n ≥ 0), exact hn } example (n : ℤ) (hn : 0 ≤ 1 * n) : true := begin lift n to ℕ using by { simpa [int.one_mul] using hn } with k, -- the above braces are optional, but it would be bad style to remove them (see next example) guard_hyp hn : 0 ≤ 1 * ((k : ℕ) : ℤ), trivial end example (n : ℤ) (hn : 0 ≤ n ↔ true) : true := begin lift n to ℕ using by { simp [hn] } with k, -- the braces are not optional here trivial end
23ece496da8dd525e32ad6e37529bdc0b323fd02
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/polynomial/symmetric.lean
9c8fd8cf78e89eada05dd81bdf299bfa3cd8a7f9
[ "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
8,170
lean
/- Copyright (c) 2020 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang, Johan Commelin -/ import data.fintype.card import data.mv_polynomial.rename import data.mv_polynomial.comm_ring import algebra.algebra.subalgebra /-! # Symmetric Polynomials and Elementary Symmetric Polynomials This file defines symmetric `mv_polynomial`s and elementary symmetric `mv_polynomial`s. We also prove some basic facts about them. ## Main declarations * `mv_polynomial.is_symmetric` * `mv_polynomial.symmetric_subalgebra` * `mv_polynomial.esymm` ## Notation + `esymm σ R n`, is the `n`th elementary symmetric polynomial in `mv_polynomial σ R`. As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients) + `r : R` elements of the coefficient ring + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `φ ψ : mv_polynomial σ R` -/ open equiv (perm) open_locale big_operators noncomputable theory namespace mv_polynomial variables {σ : Type*} {R : Type*} variables {τ : Type*} {S : Type*} /-- A `mv_polynomial φ` is symmetric if it is invariant under permutations of its variables by the `rename` operation -/ def is_symmetric [comm_semiring R] (φ : mv_polynomial σ R) : Prop := ∀ e : perm σ, rename e φ = φ variables (σ R) /-- The subalgebra of symmetric `mv_polynomial`s. -/ def symmetric_subalgebra [comm_semiring R] : subalgebra R (mv_polynomial σ R) := { carrier := set_of is_symmetric, algebra_map_mem' := λ r e, rename_C e r, mul_mem' := λ a b ha hb e, by rw [alg_hom.map_mul, ha, hb], add_mem' := λ a b ha hb e, by rw [alg_hom.map_add, ha, hb] } variables {σ R} @[simp] lemma mem_symmetric_subalgebra [comm_semiring R] (p : mv_polynomial σ R) : p ∈ symmetric_subalgebra σ R ↔ p.is_symmetric := iff.rfl namespace is_symmetric section comm_semiring variables [comm_semiring R] [comm_semiring S] {φ ψ : mv_polynomial σ R} @[simp] lemma C (r : R) : is_symmetric (C r : mv_polynomial σ R) := (symmetric_subalgebra σ R).algebra_map_mem r @[simp] lemma zero : is_symmetric (0 : mv_polynomial σ R) := (symmetric_subalgebra σ R).zero_mem @[simp] lemma one : is_symmetric (1 : mv_polynomial σ R) := (symmetric_subalgebra σ R).one_mem lemma add (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ + ψ) := (symmetric_subalgebra σ R).add_mem hφ hψ lemma mul (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ * ψ) := (symmetric_subalgebra σ R).mul_mem hφ hψ lemma smul (r : R) (hφ : is_symmetric φ) : is_symmetric (r • φ) := (symmetric_subalgebra σ R).smul_mem hφ r @[simp] lemma map (hφ : is_symmetric φ) (f : R →+* S) : is_symmetric (map f φ) := λ e, by rw [← map_rename, hφ] end comm_semiring section comm_ring variables [comm_ring R] {φ ψ : mv_polynomial σ R} lemma neg (hφ : is_symmetric φ) : is_symmetric (-φ) := (symmetric_subalgebra σ R).neg_mem hφ lemma sub (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ - ψ) := (symmetric_subalgebra σ R).sub_mem hφ hψ end comm_ring end is_symmetric section elementary_symmetric open finset variables (σ R) [comm_semiring R] [comm_semiring S] [fintype σ] [fintype τ] /-- The `n`th elementary symmetric `mv_polynomial σ R`. -/ def esymm (n : ℕ) : mv_polynomial σ R := ∑ t in powerset_len n univ, ∏ i in t, X i /-- We can define `esymm σ R n` by summing over a subtype instead of over `powerset_len`. -/ lemma esymm_eq_sum_subtype (n : ℕ) : esymm σ R n = ∑ t : {s : finset σ // s.card = n}, ∏ i in (t : finset σ), X i := begin rw esymm, let i : Π (a : finset σ), a ∈ powerset_len n univ → {s : finset σ // s.card = n} := λ a ha, ⟨_, (mem_powerset_len.mp ha).2⟩, refine sum_bij i (λ a ha, mem_univ (i a ha)) _ (λ _ _ _ _ hi, subtype.ext_iff_val.mp hi) _, { intros, apply prod_congr, simp only [subtype.coe_mk], intros, refl,}, { refine (λ b H, ⟨b.val, mem_powerset_len.mpr ⟨subset_univ b.val, b.property⟩, _⟩), simp [i] }, end /-- We can define `esymm σ R n` as a sum over explicit monomials -/ lemma esymm_eq_sum_monomial (n : ℕ) : esymm σ R n = ∑ t in powerset_len n univ, monomial (∑ i in t, finsupp.single i 1) 1 := begin refine sum_congr rfl (λ x hx, _), rw monic_monomial_eq, rw finsupp.prod_pow, rw ← prod_subset (λ y _, finset.mem_univ y : x ⊆ univ) (λ y _ hy, _), { refine prod_congr rfl (λ x' hx', _), convert (pow_one _).symm, convert (finsupp.apply_add_hom x' : (σ →₀ ℕ) →+ ℕ).map_sum _ x, classical, simp [finsupp.single_apply, finset.filter_eq', apply_ite, apply_ite finset.card], rw if_pos hx', }, { convert pow_zero _, convert (finsupp.apply_add_hom y : (σ →₀ ℕ) →+ ℕ).map_sum _ x, classical, simp [finsupp.single_apply, finset.filter_eq', apply_ite, apply_ite finset.card], rw if_neg hy, } end @[simp] lemma esymm_zero : esymm σ R 0 = 1 := by simp only [esymm, powerset_len_zero, sum_singleton, prod_empty] lemma map_esymm (n : ℕ) (f : R →+* S) : map f (esymm σ R n) = esymm σ S n := begin rw [esymm, (map f).map_sum], refine sum_congr rfl (λ x hx, _), rw (map f).map_prod, simp, end lemma rename_esymm (n : ℕ) (e : σ ≃ τ) : rename e (esymm σ R n) = esymm τ R n := begin rw [esymm_eq_sum_subtype, esymm_eq_sum_subtype, (rename ⇑e).map_sum], let e' : {s : finset σ // s.card = n} ≃ {s : finset τ // s.card = n} := equiv.subtype_equiv (equiv.finset_congr e) (by simp), rw ← equiv.sum_comp e'.symm, apply fintype.sum_congr, intro, calc _ = (∏ i in (e'.symm a : finset σ), (rename e) (X i)) : (rename e).map_prod _ _ ... = (∏ i in (a : finset τ), (rename e) (X (e.symm i))) : prod_map (a : finset τ) _ _ ... = _ : _, apply finset.prod_congr rfl, intros, simp, end lemma esymm_is_symmetric (n : ℕ) : is_symmetric (esymm σ R n) := by { intro, rw rename_esymm } lemma support_esymm'' (n : ℕ) [decidable_eq σ] [nontrivial R] : (esymm σ R n).support = (powerset_len n (univ : finset σ)).bUnion (λ t, (finsupp.single (∑ (i : σ) in t, finsupp.single i 1) (1:R)).support) := begin rw esymm_eq_sum_monomial, simp only [← single_eq_monomial], convert finsupp.support_sum_eq_bUnion (powerset_len n (univ : finset σ)) _, intros s t hst d, simp only [finsupp.support_single_ne_zero one_ne_zero, and_imp, inf_eq_inter, mem_inter, mem_singleton], rintro h rfl, have := congr_arg finsupp.support h, rw [finsupp.support_sum_eq_bUnion, finsupp.support_sum_eq_bUnion] at this, { simp only [finsupp.support_single_ne_zero one_ne_zero, bUnion_singleton_eq_self] at this, exact absurd this hst.symm }, all_goals { intros x y, simp [finsupp.support_single_disjoint] } end lemma support_esymm' (n : ℕ) [decidable_eq σ] [nontrivial R] : (esymm σ R n).support = (powerset_len n (univ : finset σ)).bUnion (λ t, {∑ (i : σ) in t, finsupp.single i 1}) := begin rw support_esymm'', congr, funext, exact finsupp.support_single_ne_zero one_ne_zero end lemma support_esymm (n : ℕ) [decidable_eq σ] [nontrivial R] : (esymm σ R n).support = (powerset_len n (univ : finset σ)).image (λ t, ∑ (i : σ) in t, finsupp.single i 1) := by { rw support_esymm', exact bUnion_singleton } lemma degrees_esymm [nontrivial R] (n : ℕ) (hpos : 0 < n) (hn : n ≤ fintype.card σ) : (esymm σ R n).degrees = (univ : finset σ).val := begin classical, have : (finsupp.to_multiset ∘ λ (t : finset σ), ∑ (i : σ) in t, finsupp.single i 1) = finset.val, { funext, simp [finsupp.to_multiset_sum_single] }, rw [degrees, support_esymm, sup_finset_image, this, ←comp_sup_eq_sup_comp], { obtain ⟨k, rfl⟩ := nat.exists_eq_succ_of_ne_zero hpos.ne', simpa using powerset_len_sup _ _ (nat.lt_of_succ_le hn) }, { intros, simp only [union_val, sup_eq_union], congr }, { refl } end end elementary_symmetric end mv_polynomial
4e4d63a5140e9549f7662e0e4ccecdf8b3ce9c29
26ac254ecb57ffcb886ff709cf018390161a9225
/src/category_theory/preadditive/default.lean
7ab251c4d75aa281badef5d11e394ed141191ee4
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
7,841
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.group.hom import category_theory.limits.shapes.kernels import algebra.big_operators /-! # Preadditive categories A preadditive category is a category in which `X ⟶ Y` is an abelian group in such a way that composition of morphisms is linear in both variables. This file contains a definition of preadditive category that directly encodes the definition given above. The definition could also be phrased as follows: A preadditive category is a category enriched over the category of Abelian groups. Once the general framework to state this in Lean is available, the contents of this file should become obsolete. ## Main results * Definition of preadditive categories and basic properties * In a preadditive category, `f : Q ⟶ R` is mono if and only if `g ≫ f = 0 → g = 0` for all composable `g`. * A preadditive category with kernels has equalizers. ## Implementation notes The simp normal form for negation and composition is to push negations as far as possible to the outside. For example, `f ≫ (-g)` and `(-f) ≫ g` both become `-(f ≫ g)`, and `(-f) ≫ (-g)` is simplified to `f ≫ g`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] ## Tags additive, preadditive, Hom group, Ab-category, Ab-enriched -/ universes v u open category_theory.limits open add_monoid_hom namespace category_theory variables (C : Type u) [category.{v} C] /-- A category is called preadditive if `P ⟶ Q` is an abelian group such that composition is linear in both variables. -/ class preadditive := (hom_group : Π P Q : C, add_comm_group (P ⟶ Q) . tactic.apply_instance) (add_comp' : ∀ (P Q R : C) (f f' : P ⟶ Q) (g : Q ⟶ R), (f + f') ≫ g = f ≫ g + f' ≫ g . obviously) (comp_add' : ∀ (P Q R : C) (f : P ⟶ Q) (g g' : Q ⟶ R), f ≫ (g + g') = f ≫ g + f ≫ g' . obviously) attribute [instance] preadditive.hom_group restate_axiom preadditive.add_comp' restate_axiom preadditive.comp_add' attribute [simp,reassoc] preadditive.add_comp attribute [reassoc] preadditive.comp_add -- (the linter doesn't like `simp` on this lemma) attribute [simp] preadditive.comp_add end category_theory open category_theory namespace category_theory.preadditive section preadditive variables {C : Type u} [category.{v} C] [preadditive C] /-- Composition by a fixed left argument as a group homomorphism -/ def left_comp {P Q : C} (R : C) (f : P ⟶ Q) : (Q ⟶ R) →+ (P ⟶ R) := mk' (λ g, f ≫ g) $ λ g g', by simp /-- Composition by a fixed right argument as a group homomorphism -/ def right_comp (P : C) {Q R : C} (g : Q ⟶ R) : (P ⟶ Q) →+ (P ⟶ R) := mk' (λ f, f ≫ g) $ λ f f', by simp @[simp, reassoc] lemma sub_comp {P Q R : C} (f f' : P ⟶ Q) (g : Q ⟶ R) : (f - f') ≫ g = f ≫ g - f' ≫ g := map_sub (right_comp P g) f f' -- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma comp_sub {P Q R : C} (f : P ⟶ Q) (g g' : Q ⟶ R) : f ≫ (g - g') = f ≫ g - f ≫ g' := map_sub (left_comp R f) g g' @[simp, reassoc] lemma neg_comp {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (-f) ≫ g = -(f ≫ g) := map_neg (right_comp _ _) _ /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma comp_neg {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : f ≫ (-g) = -(f ≫ g) := map_neg (left_comp _ _) _ @[reassoc] lemma neg_comp_neg {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (-f) ≫ (-g) = f ≫ g := by simp section big_operators open_locale big_operators @[reassoc] lemma comp_sum {P Q R : C} {J : Type*} {s : finset J} (f : P ⟶ Q) (g : J → (Q ⟶ R)) : f ≫ ∑ j in s, g j = ∑ j in s, f ≫ g j := begin change left_comp R f _ = _, rw [add_monoid_hom.map_sum], refl, end @[reassoc] lemma sum_comp {P Q R : C} {J : Type*} {s : finset J} (f : J → (P ⟶ Q)) (g : Q ⟶ R) : (∑ j in s, f j) ≫ g = ∑ j in s, f j ≫ g := begin change right_comp P g _ = _, rw [add_monoid_hom.map_sum], refl, end end big_operators instance {P Q : C} {f : P ⟶ Q} [epi f] : epi (-f) := ⟨λ R g g' H, by rwa [neg_comp, neg_comp, ←comp_neg, ←comp_neg, cancel_epi, neg_inj] at H⟩ instance {P Q : C} {f : P ⟶ Q} [mono f] : mono (-f) := ⟨λ R g g' H, by rwa [comp_neg, comp_neg, ←neg_comp, ←neg_comp, cancel_mono, neg_inj] at H⟩ @[priority 100] instance preadditive_has_zero_morphisms : has_zero_morphisms C := { has_zero := infer_instance, comp_zero' := λ P Q f R, map_zero $ left_comp R f, zero_comp' := λ P Q R f, map_zero $ right_comp P f } lemma mono_of_cancel_zero {Q R : C} (f : Q ⟶ R) (h : ∀ {P : C} (g : P ⟶ Q), g ≫ f = 0 → g = 0) : mono f := ⟨λ P g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (right_comp P f) g g').trans $ sub_eq_zero.2 hg⟩ lemma mono_iff_cancel_zero {Q R : C} (f : Q ⟶ R) : mono f ↔ ∀ (P : C) (g : P ⟶ Q), g ≫ f = 0 → g = 0 := ⟨λ m P g, by exactI zero_of_comp_mono _, mono_of_cancel_zero f⟩ lemma mono_of_kernel_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel.ι f = 0) : mono f := mono_of_cancel_zero f (λ P g h, by rw [←kernel.lift_ι f g h, w, has_zero_morphisms.comp_zero]) lemma epi_of_cancel_zero {P Q : C} (f : P ⟶ Q) (h : ∀ {R : C} (g : Q ⟶ R), f ≫ g = 0 → g = 0) : epi f := ⟨λ R g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (left_comp R f) g g').trans $ sub_eq_zero.2 hg⟩ lemma epi_iff_cancel_zero {P Q : C} (f : P ⟶ Q) : epi f ↔ ∀ (R : C) (g : Q ⟶ R), f ≫ g = 0 → g = 0 := ⟨λ e R g, by exactI zero_of_epi_comp _, epi_of_cancel_zero f⟩ lemma epi_of_cokernel_zero {X Y : C} (f : X ⟶ Y) [has_colimit (parallel_pair f 0 )] (w : cokernel.π f = 0) : epi f := epi_of_cancel_zero f (λ P g h, by rw [←cokernel.π_desc f g h, w, has_zero_morphisms.zero_comp]) end preadditive section equalizers variables {C : Type u} [category.{v} C] [preadditive C] section variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y) /-- A kernel of `f - g` is an equalizer of `f` and `g`. -/ def has_limit_parallel_pair [has_kernel (f - g)] : has_limit (parallel_pair f g) := { cone := fork.of_ι (kernel.ι (f - g)) (sub_eq_zero.1 $ by { rw ←comp_sub, exact kernel.condition _ }), is_limit := fork.is_limit.mk _ (λ s, kernel.lift (f - g) (fork.ι s) $ by { rw comp_sub, apply sub_eq_zero.2, exact fork.condition _ }) (λ s, by simp) (λ s m h, by { ext, simpa using h walking_parallel_pair.zero }) } end section /-- If a preadditive category has all kernels, then it also has all equalizers. -/ def has_equalizers_of_has_kernels [has_kernels C] : has_equalizers C := @has_equalizers_of_has_limit_parallel_pair _ _ (λ _ _ f g, has_limit_parallel_pair f g) end section variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y) /-- A cokernel of `f - g` is a coequalizer of `f` and `g`. -/ def has_colimit_parallel_pair [has_cokernel (f - g)] : has_colimit (parallel_pair f g) := { cocone := cofork.of_π (cokernel.π (f - g)) (sub_eq_zero.1 $ by { rw ←sub_comp, exact cokernel.condition _ }), is_colimit := cofork.is_colimit.mk _ (λ s, cokernel.desc (f - g) (cofork.π s) $ by { rw sub_comp, apply sub_eq_zero.2, exact cofork.condition _ }) (λ s, by simp) (λ s m h, by { ext, simpa using h walking_parallel_pair.one }) } end section /-- If a preadditive category has all cokernels, then it also has all coequalizers. -/ def has_coequalizers_of_has_cokernels [has_cokernels C] : has_coequalizers C := @has_coequalizers_of_has_colimit_parallel_pair _ _ (λ _ _ f g, has_colimit_parallel_pair f g) end end equalizers end category_theory.preadditive
cfe0df8978cab775d22c30311555e0c4b5c8309d
c062f1c97fdef9ac746f08754e7d766fd6789aa9
/data/list/set.lean
89a64faddf42dc1ebc66b9e4ede203268ab60444
[]
no_license
emberian/library_dev
00c7a985b21bdebe912f4127a363f2874e1e7555
f3abd7db0238edc18a397540e361a1da2f51503c
refs/heads/master
1,624,153,474,804
1,490,147,180,000
1,490,147,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,506
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad Set-like operations on lists. -/ import data.list.basic data.list.comb .basic .comb open nat function decidable universe variables uu vv variables {α : Type uu} {β : Type vv} namespace list section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else concat l a := rfl @[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by rw [insert.def, if_pos h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = concat l a := by rw [insert.def, if_neg h] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := if h : a ∈ l then by simp [h] else by simp [h] @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := if h' : b ∈ l then by simp [h, h'] else by simp [h, h'] theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := if h' : b ∈ l then begin simp [h'] at h, simp [h] end else begin simp [h'] at h, assumption end @[simp] theorem mem_insert_iff (a b : α) (l : list α) : a ∈ insert b l ↔ a = b ∨ a ∈ l := iff.intro eq_or_mem_of_mem_insert (λ h, or.elim h (begin intro h', simp [h'] end) mem_insert_of_mem) @[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by simp [h] @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by simp [h] theorem forall_mem_insert_of_forall_mem {p : α → Prop} {a : α} {l : list α} (h₁ : p a) (h₂ : ∀ x ∈ l, p x) : ∀ x ∈ insert a l, p x := if h : a ∈ l then begin simp [h], exact h₂ end else begin simp [h], intros b hb, cases hb with h₃ h₃, {rw h₃, assumption}, exact h₂ _ h₃ end end insert section erase variable [decidable_eq α] def erase (a : α) : list α → list α | [] := [] | (b::l) := if a = b then l else b :: erase l @[simp] lemma erase_nil (a : α) : erase a [] = [] := rfl lemma erase_cons (a b : α) (l : list α) : erase a (b :: l) = if a = b then l else b :: erase a l := rfl @[simp] lemma erase_cons_head (a : α) (l : list α) : erase a (a :: l) = l := by simp [erase_cons, if_pos] @[simp] lemma erase_cons_tail {a b : α} (l : list α) (h : a ≠ b) : erase a (b::l) = b :: erase a l := by simp [erase_cons, if_neg, h] @[simp] lemma length_erase_of_mem {a : α} : ∀ {l}, a ∈ l → length (erase a l) = pred (length l) | [] h := rfl | [x] h := begin simp at h, simp [h] end | (x::y::xs) h := if h' : a = x then begin simp [h'] end else have ainyxs : a ∈ y::xs, from or_resolve_right h h', begin simp [h', length_erase_of_mem ainyxs] end @[simp] lemma length_erase_of_not_mem {a : α} : ∀ {l}, a ∉ l → length (erase a l) = length l | [] h := rfl | (x::xs) h := have anex : a ≠ x, from λ aeqx : a = x, absurd (or.inl aeqx) h, have aninxs : a ∉ xs, from λ ainxs : a ∈ xs, absurd (or.inr ainxs) h, by simp [anex, length_erase_of_not_mem aninxs] lemma erase_append_left {a : α} : ∀ {l₁} (l₂), a ∈ l₁ → erase a (l₁++l₂) = erase a l₁ ++ l₂ | [] l₂ h := absurd h (not_mem_nil a) | (x::xs) l₂ h := if h' : a = x then by simp [h'] else have a ∈ xs, from mem_of_ne_of_mem h' h, by simp [erase_append_left l₂ this, h'] lemma erase_append_right {a : α} : ∀ {l₁} (l₂), a ∉ l₁ → erase a (l₁++l₂) = l₁ ++ erase a l₂ | [] l₂ h := rfl | (x::xs) l₂ h := if h' : a = x then begin simp [h'] at h, contradiction end else have a ∉ xs, from not_mem_of_not_mem_cons h, by simp [erase_append_right l₂ this, h'] lemma erase_subset (a : α) : ∀ l, erase a l ⊆ l | [] := subset.refl nil | (x :: xs) := if h : a = x then begin simp [h] end else begin simp [h], apply cons_subset_cons, apply erase_subset xs end theorem mem_erase_of_ne_of_mem {a b : α} : ∀ {l : list α}, a ≠ b → a ∈ l → a ∈ erase b l | [] aneb anil := begin simp at anil, contradiction end | (c :: l) aneb acl := if h : b = c then begin simp [h^.symm, aneb] at acl, simp [h, acl] end else begin simp [h], simp at acl, cases acl with h' h', { simp [h'] }, simp [mem_erase_of_ne_of_mem aneb h'] end theorem mem_of_mem_erase {a b : α} : ∀ {l}, a ∈ erase b l → a ∈ l | [] h := begin simp at h, contradiction end | (c :: l) h := if h' : b = c then begin simp [h'] at h, simp [h] end else begin simp [h'] at h, cases h with h'' h'', { simp [h''] }, simp [mem_of_mem_erase h''] end end erase /- disjoint -/ section disjoint def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, (a ∈ l₁ → a ∈ l₂ → false) lemma disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₁ → a ∉ l₂ := λ d, d lemma disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₂ → a ∉ l₁ := λ d a i₂ i₁, d i₁ i₂ lemma disjoint.comm {l₁ l₂ : list α} : disjoint l₁ l₂ → disjoint l₂ l₁ := λ d a i₂ i₁, d i₁ i₂ lemma disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := λ d x xinl₁, disjoint_left d (or.inr xinl₁) lemma disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := λ d, disjoint.comm (disjoint_of_disjoint_cons_left (disjoint.comm d)) lemma disjoint_nil_left (l : list α) : disjoint [] l := λ a ab, absurd ab (not_mem_nil a) lemma disjoint_nil_right (l : list α) : disjoint l [] := disjoint.comm (disjoint_nil_left l) lemma disjoint_cons_of_not_mem_of_disjoint {a : α} {l₁ l₂ : list α} : a ∉ l₂ → disjoint l₁ l₂ → disjoint (a::l₁) l₂ := λ nainl₂ d x (xinal₁ : x ∈ a::l₁), or.elim (eq_or_mem_of_mem_cons xinal₁) (λ xeqa : x = a, eq.symm xeqa ▸ nainl₂) (λ xinl₁ : x ∈ l₁, disjoint_left d xinl₁) lemma disjoint_of_disjoint_append_left_left : ∀ {l₁ l₂ l : list α}, disjoint (l₁++l₂) l → disjoint l₁ l | [] l₂ l d := disjoint_nil_left l | (x::xs) l₂ l d := have nxinl : x ∉ l, from disjoint_left d (mem_cons_self x _), have d₁ : disjoint (xs++l₂) l, from disjoint_of_disjoint_cons_left d, have d₂ : disjoint xs l, from disjoint_of_disjoint_append_left_left d₁, disjoint_cons_of_not_mem_of_disjoint nxinl d₂ lemma disjoint_of_disjoint_append_left_right : ∀ {l₁ l₂ l : list α}, disjoint (l₁++l₂) l → disjoint l₂ l | [] l₂ l d := d | (x::xs) l₂ l d := have d₁ : disjoint (xs++l₂) l, from disjoint_of_disjoint_cons_left d, disjoint_of_disjoint_append_left_right d₁ lemma disjoint_of_disjoint_append_right_left : ∀ {l₁ l₂ l : list α}, disjoint l (l₁++l₂) → disjoint l l₁ := λ l₁ l₂ l d, disjoint.comm (disjoint_of_disjoint_append_left_left (disjoint.comm d)) lemma disjoint_of_disjoint_append_right_right : ∀ {l₁ l₂ l : list α}, disjoint l (l₁++l₂) → disjoint l l₂ := λ l₁ l₂ l d, disjoint.comm (disjoint_of_disjoint_append_left_right (disjoint.comm d)) end disjoint /- upto -/ def upto : nat → list nat | 0 := [] | (n+1) := n :: upto n @[simp] theorem upto_nil : upto 0 = nil := rfl @[simp] theorem upto_succ (n : nat) : upto (succ n) = n :: upto n := rfl @[simp] theorem length_upto : ∀ n, length (upto n) = n | 0 := rfl | (succ n) := begin rw [upto_succ, length_cons, length_upto] end theorem upto_ne_nil_of_ne_zero {n : ℕ} (h : n ≠ 0) : upto n ≠ nil := suppose upto n = nil, have upto n = upto 0, from upto_nil ▸ this, have n = 0, from calc n = length (upto n) : by rw length_upto ... = length (upto 0) : by rw this ... = 0 : by rw length_upto, h this theorem lt_of_mem_upto : ∀ ⦃n i⦄, i ∈ upto n → i < n | 0 := take i imem, absurd imem (not_mem_nil _) | (succ n) := take i imem, or.elim (eq_or_mem_of_mem_cons imem) (λ h, begin rw h, apply lt_succ_self end) (λ h, lt.trans (lt_of_mem_upto h) (lt_succ_self n)) theorem mem_upto_succ_of_mem_upto {n i : nat} : i ∈ upto n → i ∈ upto (succ n) := assume i, mem_cons_of_mem _ i theorem mem_upto_of_lt : ∀ ⦃n i : nat⦄, i < n → i ∈ upto n | 0 := λ i h, absurd h (not_lt_zero i) | (succ n) := λ i h, begin cases nat.lt_or_eq_of_le (le_of_lt_succ h) with ilt ieq, { apply mem_upto_succ_of_mem_upto, apply mem_upto_of_lt ilt }, simp [ieq] end lemma upto_step : ∀ (n : nat), upto (succ n) = (map succ (upto n)) ++ [0] | 0 := rfl | (succ n) := by simp [(upto_step n)^.symm] /- union -/ section union variable [decidable_eq α] @[simp] theorem union_nil (l : list α) : l ∪ [] = l := rfl @[simp] theorem union_cons (l₁ l₂ : list α) (a : α) : l₁ ∪ (a :: l₂) = insert a l₁ ∪ l₂ := rfl theorem mem_or_mem_of_mem_union : ∀ {l₁ l₂ : list α} {a : α}, a ∈ l₁ ∪ l₂ → a ∈ l₁ ∨ a ∈ l₂ | l₁ [] a h := begin simp at h, simp [h] end | l₁ (b :: l₂) a h := if h' : b ∈ l₂ then begin simp at h, cases mem_or_mem_of_mem_union h with h₀ h₀, { simp at h₀, cases h₀ with h₁ h₁, simp [h₁], simp [h₁] }, simp [h₀] end else begin simp [union_cons] at h, cases mem_or_mem_of_mem_union h with h₀ h₀, { simp at h₀, cases h₀ with h₁ h₁, repeat { simp [h₁] } }, simp [h₀] end theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := begin revert h, generalize l₁ l, induction l₂ with b l₂ ih, { simp, intros, assumption }, intros, apply ih, simp [h] end theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := begin generalize l₁ l, induction l₂ with b l₂ ih, { simp at h, contradiction }, intro l, simp, simp at h, cases h with h₀ h₀, { simp [h₀], apply mem_union_left, simp }, apply ih h₀ end @[simp] theorem mem_union_iff (a : α) (l₁ l₂ : list α) : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := iff.intro mem_or_mem_of_mem_union (λ h, or.elim h (λ h', mem_union_left h' l₂) (mem_union_right l₁)) theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} (h₁ : ∀ x ∈ l₁, p x) (h₂ : ∀ x ∈ l₂, p x) : ∀ x ∈ l₁ ∪ l₂, p x := begin intro x, simp, intro h, cases h, { apply h₁, assumption }, apply h₂, assumption end theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := begin intros x xl₁, apply h, apply mem_union_left xl₁ end theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := begin intros x xl₂, apply h, apply mem_union_right l₁ xl₂ end end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : inter [] l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : inter (a::l₁) l₂ = inter l₁ l₂ := if_neg h theorem mem_of_mem_inter_left : ∀ {l₁ l₂ : list α} {a : α}, a ∈ inter l₁ l₂ → a ∈ l₁ | [] l₂ a i := absurd i (not_mem_nil a) | (b::l₁) l₂ a i := by_cases (λ binl₂ : b ∈ l₂, have aux : a ∈ b :: inter l₁ l₂, begin rw [inter_cons_of_mem _ binl₂] at i, exact i end, or.elim (eq_or_mem_of_mem_cons aux) (λ aeqb : a = b, begin rw [aeqb], apply mem_cons_self end) (λ aini, mem_cons_of_mem _ (mem_of_mem_inter_left aini))) (λ nbinl₂ : b ∉ l₂, have ainl₁ : a ∈ l₁, begin rw [inter_cons_of_not_mem _ nbinl₂] at i, exact (mem_of_mem_inter_left i) end, mem_cons_of_mem _ ainl₁) theorem mem_of_mem_inter_right : ∀ {l₁ l₂ : list α} {a : α}, a ∈ inter l₁ l₂ → a ∈ l₂ | [] l₂ a i := absurd i (not_mem_nil _) | (b::l₁) l₂ a i := by_cases (λ binl₂ : b ∈ l₂, have aux : a ∈ b :: inter l₁ l₂, begin rw [inter_cons_of_mem _ binl₂] at i, exact i end, or.elim (eq_or_mem_of_mem_cons aux) (λ aeqb : a = b, begin rw [aeqb], exact binl₂ end) (λ aini : a ∈ inter l₁ l₂, mem_of_mem_inter_right aini)) (λ nbinl₂ : b ∉ l₂, begin rw [inter_cons_of_not_mem _ nbinl₂] at i, exact (mem_of_mem_inter_right i) end) theorem mem_inter_of_mem_of_mem : ∀ {l₁ l₂ : list α} {a : α}, a ∈ l₁ → a ∈ l₂ → a ∈ inter l₁ l₂ | [] l₂ a i₁ i₂ := absurd i₁ (not_mem_nil _) | (b::l₁) l₂ a i₁ i₂ := by_cases (λ binl₂ : b ∈ l₂, or.elim (eq_or_mem_of_mem_cons i₁) (λ aeqb : a = b, begin rw [inter_cons_of_mem _ binl₂, aeqb], apply mem_cons_self end) (λ ainl₁ : a ∈ l₁, begin rw [inter_cons_of_mem _ binl₂], apply mem_cons_of_mem, exact (mem_inter_of_mem_of_mem ainl₁ i₂) end)) (λ nbinl₂ : b ∉ l₂, or.elim (eq_or_mem_of_mem_cons i₁) (λ aeqb : a = b, begin rw aeqb at i₂, exact absurd i₂ nbinl₂ end) (λ ainl₁ : a ∈ l₁, begin rw [inter_cons_of_not_mem _ nbinl₂], exact (mem_inter_of_mem_of_mem ainl₁ i₂) end)) @[simp] theorem mem_inter_iff (a : α) (l₁ l₂ : list α) : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter_of_mem_of_mem h^.left h^.right) theorem inter_eq_nil_of_disjoint : ∀ {l₁ l₂ : list α}, disjoint l₁ l₂ → inter l₁ l₂ = [] | [] l₂ d := rfl | (a::l₁) l₂ d := have aux_eq : inter l₁ l₂ = [], from inter_eq_nil_of_disjoint (disjoint_of_disjoint_cons_left d), have nainl₂ : a ∉ l₂, from disjoint_left d (mem_cons_self _ _), by rw [inter_cons_of_not_mem _ nainl₂, aux_eq] theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := λ x xl₁l₂, h x (mem_of_mem_inter_left xl₁l₂) theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := λ x xl₁l₂, h x (mem_of_mem_inter_right xl₁l₂) end inter /- no duplicates predicate -/ inductive nodup {α : Type uu} : list α → Prop | ndnil : nodup [] | ndcons : ∀ {a : α} {l : list α}, a ∉ l → nodup l → nodup (a::l) section nodup open nodup theorem nodup_nil : @nodup α [] := ndnil theorem nodup_cons {a : α} {l : list α} : a ∉ l → nodup l → nodup (a::l) := λ i n, ndcons i n theorem nodup_singleton (a : α) : nodup [a] := nodup_cons (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons : ∀ {a : α} {l : list α}, nodup (a::l) → nodup l | a xs (ndcons i n) := n theorem not_mem_of_nodup_cons : ∀ {a : α} {l : list α}, nodup (a::l) → a ∉ l | a xs (ndcons i n) := i theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := λ ainl d, absurd ainl (not_mem_of_nodup_cons d) theorem not_nodup_cons_of_not_nodup {a : α} {l : list α} : ¬ nodup l → ¬ nodup (a :: l) := λ nd d, absurd (nodup_of_nodup_cons d) nd theorem nodup_of_nodup_append_left : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → nodup l₁ | [] l₂ n := nodup_nil | (x::xs) l₂ n := have ndxs : nodup xs, from nodup_of_nodup_append_left (nodup_of_nodup_cons n), have nxinxsl₂ : x ∉ xs++l₂, from not_mem_of_nodup_cons n, have nxinxs : x ∉ xs, from not_mem_of_not_mem_append_left nxinxsl₂, nodup_cons nxinxs ndxs theorem nodup_of_nodup_append_right : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → nodup l₂ | [] l₂ n := n | (x::xs) l₂ n := nodup_of_nodup_append_right (nodup_of_nodup_cons n) theorem disjoint_of_nodup_append : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → disjoint l₁ l₂ | [] l₂ d := disjoint_nil_left l₂ | (x::xs) l₂ d := have nodup (x::(xs++l₂)), from d, have x ∉ xs++l₂, from not_mem_of_nodup_cons this, have nxinl₂ : x ∉ l₂, from not_mem_of_not_mem_append_right this, take a, suppose a ∈ x::xs, or.elim (eq_or_mem_of_mem_cons this) (suppose a = x, eq.symm this ▸ nxinl₂) (suppose ainxs : a ∈ xs, have nodup (x::(xs++l₂)), from d, have nodup (xs++l₂), from nodup_of_nodup_cons this, have disjoint xs l₂, from disjoint_of_nodup_append this, disjoint_left this ainxs) theorem nodup_append_of_nodup_of_nodup_of_disjoint : ∀ {l₁ l₂ : list α}, nodup l₁ → nodup l₂ → disjoint l₁ l₂ → nodup (l₁++l₂) | [] l₂ d₁ d₂ dsj := begin rw [nil_append], exact d₂ end | (x::xs) l₂ d₁ d₂ dsj := have ndxs : nodup xs, from nodup_of_nodup_cons d₁, have disjoint xs l₂, from disjoint_of_disjoint_cons_left dsj, have ndxsl₂ : nodup (xs++l₂), from nodup_append_of_nodup_of_nodup_of_disjoint ndxs d₂ this, have nxinxs : x ∉ xs, from not_mem_of_nodup_cons d₁, have x ∉ l₂, from disjoint_left dsj (mem_cons_self x xs), have x ∉ xs++l₂, from not_mem_append nxinxs this, nodup_cons this ndxsl₂ theorem nodup_app_comm {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : nodup (l₂++l₁) := have d₁ : nodup l₁, from nodup_of_nodup_append_left d, have d₂ : nodup l₂, from nodup_of_nodup_append_right d, have dsj : disjoint l₁ l₂, from disjoint_of_nodup_append d, nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₁ (disjoint.comm dsj) theorem nodup_head {a : α} {l₁ l₂ : list α} (d : nodup (l₁++(a::l₂))) : nodup (a::(l₁++l₂)) := have d₁ : nodup (a::(l₂++l₁)), from nodup_app_comm d, have d₂ : nodup (l₂++l₁), from nodup_of_nodup_cons d₁, have d₃ : nodup (l₁++l₂), from nodup_app_comm d₂, have nain : a ∉ l₂++l₁, from not_mem_of_nodup_cons d₁, have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_left nain, have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_right nain, nodup_cons (not_mem_append nain₁ nain₂) d₃ theorem nodup_middle {a : α} {l₁ l₂ : list α} (d : nodup (a::(l₁++l₂))) : nodup (l₁++(a::l₂)) := have d₁ : nodup (l₁++l₂), from nodup_of_nodup_cons d, have nain : a ∉ l₁++l₂, from not_mem_of_nodup_cons d, have disj : disjoint l₁ l₂, from disjoint_of_nodup_append d₁, have d₂ : nodup l₁, from nodup_of_nodup_append_left d₁, have d₃ : nodup l₂, from nodup_of_nodup_append_right d₁, have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_right nain, have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_left nain, have d₄ : nodup (a::l₂), from nodup_cons nain₂ d₃, have disj₂ : disjoint l₁ (a::l₂), from disjoint.comm (disjoint_cons_of_not_mem_of_disjoint nain₁ (disjoint.comm disj)), nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₄ disj₂ theorem nodup_map {f : α → β} (inj : injective f) : ∀ {l : list α}, nodup l → nodup (map f l) | [] n := begin apply nodup_nil end | (x::xs) n := have nxinxs : x ∉ xs, from not_mem_of_nodup_cons n, have ndxs : nodup xs, from nodup_of_nodup_cons n, have ndmfxs : nodup (map f xs), from nodup_map ndxs, have nfxinm : f x ∉ map f xs, from λ ab : f x ∈ map f xs, match (exists_of_mem_map ab) with | ⟨(y : α), (yinxs : y ∈ xs), (fyfx : f y = f x)⟩ := have yeqx : y = x, from inj fyfx, begin subst y, contradiction end end, nodup_cons nfxinm ndmfxs theorem nodup_erase_of_nodup [decidable_eq α] (a : α) : ∀ {l}, nodup l → nodup (erase a l) | [] n := nodup_nil | (b::l) n := by_cases (λ aeqb : a = b, begin rw [aeqb, erase_cons_head], exact (nodup_of_nodup_cons n) end) (λ aneb : a ≠ b, have nbinl : b ∉ l, from not_mem_of_nodup_cons n, have ndl : nodup l, from nodup_of_nodup_cons n, have ndeal : nodup (erase a l), from nodup_erase_of_nodup ndl, have nbineal : b ∉ erase a l, from λ i, absurd (erase_subset _ _ i) nbinl, have aux : nodup (b :: erase a l), from nodup_cons nbineal ndeal, begin rw [erase_cons_tail _ aneb], exact aux end) theorem mem_erase_of_nodup [decidable_eq α] (a : α) : ∀ {l}, nodup l → a ∉ erase a l | [] n := (not_mem_nil _) | (b::l) n := have ndl : nodup l, from nodup_of_nodup_cons n, have naineal : a ∉ erase a l, from mem_erase_of_nodup ndl, have nbinl : b ∉ l, from not_mem_of_nodup_cons n, by_cases (λ aeqb : a = b, begin rw [aeqb, erase_cons_head], exact nbinl end) (λ aneb : a ≠ b, have aux : a ∉ b :: erase a l, from assume ainbeal : a ∈ b :: erase a l, or.elim (eq_or_mem_of_mem_cons ainbeal) (λ aeqb : a = b, absurd aeqb aneb) (λ aineal : a ∈ erase a l, absurd aineal naineal), begin rw [erase_cons_tail _ aneb], exact aux end) def erase_dup [decidable_eq α] : list α → list α | [] := [] | (x :: xs) := if x ∈ xs then erase_dup xs else x :: erase_dup xs theorem erase_dup_nil [decidable_eq α] : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem [decidable_eq α] {a : α} {l : list α} : a ∈ l → erase_dup (a::l) = erase_dup l := assume ainl, calc erase_dup (a::l) = if a ∈ l then erase_dup l else a :: erase_dup l : rfl ... = erase_dup l : if_pos ainl theorem erase_dup_cons_of_not_mem [decidable_eq α] {a : α} {l : list α} : a ∉ l → erase_dup (a::l) = a :: erase_dup l := assume nainl, calc erase_dup (a::l) = if a ∈ l then erase_dup l else a :: erase_dup l : rfl ... = a :: erase_dup l : if_neg nainl theorem mem_erase_dup [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ l → a ∈ erase_dup l | [] h := absurd h (not_mem_nil _) | (b::l) h := by_cases (λ binl : b ∈ l, or.elim (eq_or_mem_of_mem_cons h) (λ aeqb : a = b, begin rw [erase_dup_cons_of_mem binl], rw -aeqb at binl, exact (mem_erase_dup binl) end) (λ ainl : a ∈ l, begin rw [erase_dup_cons_of_mem binl], exact (mem_erase_dup ainl) end)) (λ nbinl : b ∉ l, or.elim (eq_or_mem_of_mem_cons h) (λ aeqb : a = b, begin rw [erase_dup_cons_of_not_mem nbinl, aeqb], apply mem_cons_self end) (λ ainl : a ∈ l, begin rw [erase_dup_cons_of_not_mem nbinl], exact (or.inr (mem_erase_dup ainl)) end)) theorem mem_of_mem_erase_dup [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ erase_dup l → a ∈ l | [] h := begin rw [erase_dup_nil] at h, exact h end | (b::l) h := by_cases (λ binl : b ∈ l, have h₁ : a ∈ erase_dup l, begin rw [erase_dup_cons_of_mem binl] at h, exact h end, or.inr (mem_of_mem_erase_dup h₁)) (λ nbinl : b ∉ l, have h₁ : a ∈ b :: erase_dup l, begin rw [erase_dup_cons_of_not_mem nbinl] at h, exact h end, or.elim (eq_or_mem_of_mem_cons h₁) (λ aeqb : a = b, begin rw aeqb, apply mem_cons_self end) (λ ainel : a ∈ erase_dup l, or.inr (mem_of_mem_erase_dup ainel))) @[simp] theorem mem_erase_dup_iff [decidable_eq α] (a : α) (l : list α) : a ∈ erase_dup l ↔ a ∈ l := iff.intro mem_of_mem_erase_dup mem_erase_dup theorem erase_dup_sub [decidable_eq α] (l : list α) : erase_dup l ⊆ l := λ a i, mem_of_mem_erase_dup i theorem sub_erase_dup [decidable_eq α] (l : list α) : l ⊆ erase_dup l := λ a i, mem_erase_dup i theorem nodup_erase_dup [decidable_eq α] : ∀ l : list α, nodup (erase_dup l) | [] := begin rw erase_dup_nil, exact nodup_nil end | (a::l) := by_cases (λ ainl : a ∈ l, begin rw [erase_dup_cons_of_mem ainl], exact (nodup_erase_dup l) end) (λ nainl : a ∉ l, have r : nodup (erase_dup l), from nodup_erase_dup l, have nin : a ∉ erase_dup l, from assume ab : a ∈ erase_dup l, absurd (mem_of_mem_erase_dup ab) nainl, begin rw [erase_dup_cons_of_not_mem nainl], exact (nodup_cons nin r) end) theorem erase_dup_eq_of_nodup [decidable_eq α] : ∀ {l : list α}, nodup l → erase_dup l = l | [] d := rfl | (a::l) d := have nainl : a ∉ l, from not_mem_of_nodup_cons d, have dl : nodup l, from nodup_of_nodup_cons d, by rw [erase_dup_cons_of_not_mem nainl, erase_dup_eq_of_nodup dl] attribute [instance] def decidable_nodup [decidable_eq α] : ∀ (l : list α), decidable (nodup l) | [] := is_true nodup_nil | (a::l) := if h : a ∈ l then is_false (not_nodup_cons_of_mem h) else match (decidable_nodup l) with | (is_true nd) := is_true (nodup_cons h nd) | (is_false d) := is_false (not_nodup_cons_of_not_nodup d) end private def dgen (a : α) : ∀ l, nodup l → nodup (map (λ b : β, (a, b)) l) | [] h := nodup_nil | (x::l) h := have dl : nodup l, from nodup_of_nodup_cons h, have dm : nodup (map (λ b : β, (a, b)) l), from dgen l dl, have nxin : x ∉ l, from not_mem_of_nodup_cons h, have npin : (a, x) ∉ map (λ b, (a, b)) l, from assume pin, absurd (mem_of_mem_map_pair₁ pin) nxin, nodup_cons npin dm theorem nodup_product : ∀ {l₁ : list α} {l₂ : list β}, nodup l₁ → nodup l₂ → nodup (product l₁ l₂) | [] l₂ n₁ n₂ := nodup_nil | (a::l₁) l₂ n₁ n₂ := have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons n₁, have n₃ : nodup l₁, from nodup_of_nodup_cons n₁, have n₄ : nodup (product l₁ l₂), from nodup_product n₃ n₂, have dm : nodup (map (λ b : β, (a, b)) l₂), from dgen a l₂ n₂, have dsj : disjoint (map (λ b : β, (a, b)) l₂) (product l₁ l₂), from λ p : α × β, match p with | (a₁, b₁) := λ (i₁ : (a₁, b₁) ∈ map (λ b, (a, b)) l₂) (i₂ : (a₁, b₁) ∈ product l₁ l₂), have a₁inl₁ : a₁ ∈ l₁, from mem_of_mem_product_left i₂, have a₁ = a, from eq_of_mem_map_pair₁ i₁, have a ∈ l₁, begin rw -this, assumption end, absurd this nainl₁ end, nodup_append_of_nodup_of_nodup_of_disjoint dm n₄ dsj theorem nodup_filter (p : α → Prop) [decidable_pred p] : ∀ {l : list α}, nodup l → nodup (filter p l) | [] nd := nodup_nil | (a::l) nd := have nainl : a ∉ l, from not_mem_of_nodup_cons nd, have ndl : nodup l, from nodup_of_nodup_cons nd, have ndf : nodup (filter p l), from nodup_filter ndl, have nainf : a ∉ filter p l, from assume ainf, absurd (mem_of_mem_filter ainf) nainl, by_cases (λ pa : p a, begin rw [filter_cons_of_pos _ pa], exact (nodup_cons nainf ndf) end) (λ npa : ¬ p a, begin rw [filter_cons_of_neg _ npa], exact ndf end) lemma dmap_nodup_of_dinj {p : α → Prop} [h : decidable_pred p] {f : Π a, p a → β} (pdi : dinj p f) : ∀ {l : list α}, nodup l → nodup (dmap p f l) | [] := take P, nodup.ndnil | (a::l) := take Pnodup, if pa : p a then begin rw [dmap_cons_of_pos pa], apply nodup_cons, apply (not_mem_dmap_of_dinj_of_not_mem pdi pa), exact not_mem_of_nodup_cons Pnodup, exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup) end else begin rw [dmap_cons_of_neg pa], exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup) end theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := begin revert h, induction l with b l ih, { intro h₀, apply nodup_singleton }, intro h₀, rw [concat_cons], apply nodup_cons, { simp, intro h₁, apply h₀, simp, cases h₁ with h₂ h₂, simp [h₂], exact absurd h₂ (not_mem_of_nodup_cons h') }, apply ih, { apply nodup_of_nodup_cons h' }, intro h₁, apply h₀, exact mem_cons_of_mem _ h₁ end theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := if h' : a ∈ l then by simp [h', h] else begin rw [insert_of_not_mem h'], apply nodup_concat, repeat {assumption} end theorem nodup_upto : ∀ n, nodup (upto n) | 0 := nodup_nil | (n+1) := have d : nodup (upto n), from nodup_upto n, have n : n ∉ upto n, from assume i : n ∈ upto n, absurd (lt_of_mem_upto i) (nat.lt_irrefl n), nodup_cons n d theorem nodup_union_of_nodup_of_nodup [decidable_eq α] {l₁ l₂ : list α} (h₁ : nodup l₁) (h₂ : nodup l₂) : nodup (l₁ ∪ l₂) := begin revert h₁, generalize l₁ l, induction l₂ with a l₂ ih, { intros l nodupl, exact nodupl }, intros l nodupl, simp, apply ih, { apply nodup_of_nodup_cons h₂}, apply nodup_insert nodupl end theorem nodup_inter_of_nodup [decidable_eq α] : ∀ {l₁ : list α} (l₂), nodup l₁ → nodup (l₁ ∩ l₂) | [] l₂ d := nodup_nil | (a::l₁) l₂ d := have d₁ : nodup l₁, from nodup_of_nodup_cons d, have d₂ : nodup (inter l₁ l₂), from nodup_inter_of_nodup _ d₁, have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons d, have naini : a ∉ inter l₁ l₂, from λ i, absurd (mem_of_mem_inter_left i) nainl₁, by_cases (λ ainl₂ : a ∈ l₂, begin rw [inter_cons_of_mem _ ainl₂], exact (nodup_cons naini d₂) end) (λ nainl₂ : a ∉ l₂, begin rw [inter_cons_of_not_mem _ nainl₂], exact d₂ end) end nodup end list
b21f8e5449748a57d649847783ef3ec2d87c26e5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/combinatorics/set_family/kleitman.lean
6949daf8fde3e10e0eb55a4a00206d639b58f9d5
[ "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
3,746
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 combinatorics.set_family.harris_kleitman import combinatorics.set_family.intersecting /-! # Kleitman's bound on the size of intersecting families An intersecting family on `n` elements has size at most `2ⁿ⁻¹`, so we could naïvely think that two intersecting families could cover all `2ⁿ` sets. But actually that's not case because for example none of them can contain the empty set. Intersecting families are in some sense correlated. Kleitman's bound stipulates that `k` intersecting families cover at most `2ⁿ - 2ⁿ⁻ᵏ` sets. ## Main declarations * `finset.card_bUnion_le_of_intersecting`: Kleitman's theorem. ## References * [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966] -/ open finset fintype (card) variables {ι α : Type*} [fintype α] [decidable_eq α] [nonempty α] /-- **Kleitman's theorem**. An intersecting family on `n` elements contains at most `2ⁿ⁻¹` sets, and each further intersecting family takes at most half of the sets that are in no previous family. -/ lemma finset.card_bUnion_le_of_intersecting (s : finset ι) (f : ι → finset (finset α)) (hf : ∀ i ∈ s, (f i : set (finset α)).intersecting) : (s.bUnion f).card ≤ 2 ^ card α - 2 ^ (card α - s.card) := begin obtain hs | hs := le_total (card α) s.card, { rw [tsub_eq_zero_of_le hs, pow_zero], refine (card_le_of_subset $ bUnion_subset.2 $ λ i hi a ha, mem_compl.2 $ not_mem_singleton.2 $ (hf _ hi).ne_bot ha).trans_eq _, rw [card_compl, fintype.card_finset, card_singleton] }, induction s using finset.cons_induction with i s hi ih generalizing f, { simp }, classical, set f' : ι → finset (finset α) := λ j, if hj : j ∈ cons i s hi then (hf j hj).exists_card_eq.some else ∅ with hf', have hf₁ : ∀ j, j ∈ cons i s hi → f j ⊆ f' j ∧ 2 * (f' j).card = 2 ^ card α ∧ (f' j : set (finset α)).intersecting, { rintro j hj, simp_rw [hf', dif_pos hj, ←fintype.card_finset], exact classical.some_spec (hf j hj).exists_card_eq }, have hf₂ : ∀ j, j ∈ cons i s hi → is_upper_set (f' j : set (finset α)), { refine λ j hj, (hf₁ _ hj).2.2.is_upper_set' ((hf₁ _ hj).2.2.is_max_iff_card_eq.2 _), rw fintype.card_finset, exact (hf₁ _ hj).2.1 }, refine (card_le_of_subset $ bUnion_mono $ λ j hj, (hf₁ _ hj).1).trans _, nth_rewrite 0 cons_eq_insert i, rw bUnion_insert, refine (card_mono $ @le_sup_sdiff _ _ _ $ f' i).trans ((card_union_le _ _).trans _), rw [union_sdiff_left, sdiff_eq_inter_compl], refine le_of_mul_le_mul_left _ (pow_pos zero_lt_two $ card α + 1), rw [pow_succ', mul_add, mul_assoc, mul_comm _ 2, mul_assoc], refine (add_le_add ((mul_le_mul_left $ pow_pos two_pos _).2 (hf₁ _ $ mem_cons_self _ _).2.2.card_le) $ (mul_le_mul_left two_pos).2 $ is_upper_set.card_inter_le_finset _ _).trans _, { rw coe_bUnion, exact is_upper_set_Union₂ (λ i hi, hf₂ _ $ subset_cons _ hi) }, { rw coe_compl, exact (hf₂ _ $ mem_cons_self _ _).compl }, rw [mul_tsub, card_compl, fintype.card_finset, mul_left_comm, mul_tsub, (hf₁ _ $ mem_cons_self _ _).2.1, two_mul, add_tsub_cancel_left, ←mul_tsub, ←mul_two, mul_assoc, ←add_mul, mul_comm], refine mul_le_mul_left' _ _, refine (add_le_add_left (ih ((card_le_of_subset $ subset_cons _).trans hs) _ $ λ i hi, (hf₁ _ $ subset_cons _ hi).2.2) _).trans _, rw [mul_tsub, two_mul, ←pow_succ, ←add_tsub_assoc_of_le (pow_le_pow' (@one_le_two ℕ _ _ _ _ _) tsub_le_self), tsub_add_eq_add_tsub hs, card_cons, add_tsub_add_eq_tsub_right], end
030077af3b80fa290cdcc4642045ee6172fd3d71
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/1467.lean
61a7b72425fb54dc2655492b685262013eb8d1df
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
832
lean
constants f g h : ℕ → ℕ axiom H_f_g : ∀ n, f (g n) = n example (m : ℕ) : h m = h m := begin pose n : ℕ := g m, note H : f n = m := begin dsimp, rw H_f_g end, subst H, -- Error here end set_option pp.instantiate_mvars false example (m : ℕ) : h m = h m := begin define n : ℕ, -- add metavar exact g m, note H : f n = m := begin dsimp, rw H_f_g end, subst H, -- Error here end example (m : ℕ) : h m = h m := begin pose n : ℕ := g m, note H : f n = m := begin dsimp, rw H_f_g end, subst m, -- Error here end set_option pp.instantiate_mvars false example (m : ℕ) : h m = h m := begin define n : ℕ, -- add metavar exact g m, note H : f n = m := begin dsimp, rw H_f_g end, subst m, -- Error here end example (m p: ℕ) : h m = h m := begin pose a : ℕ := g p, pose n : ℕ := g a, clear p -- Error here end
2eecfb66ab5122874d329dc735f8ed2cac99128e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/roots_of_unity.lean
9837b2662687583148919e3f66c485aaa4a9e0ae
[ "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
40,552
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 data.nat.parity import data.polynomial.ring_division import group_theory.specific_groups.cyclic import ring_theory.integral_domain import number_theory.divisors import data.zmod.basic import tactic.zify import field_theory.separable import field_theory.finite.basic /-! # Roots of unity and primitive roots of unity We define roots of unity in the context of an arbitrary commutative monoid, as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative monoids, expressing that an element is a primitive root of unity. ## Main definitions * `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M` consisting of elements `x` that satisfy `x ^ n = 1`. * `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. * `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`. ## Main results * `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group. * `is_primitive_root.zmod_equiv_zpowers`: `zmod k` is equivalent to the subgroup generated by a primitive `k`-th root of unity. * `is_primitive_root.zpowers_eq`: in an integral domain, the subgroup generated by a primitive `k`-th root of unity is equal to the `k`-th roots of unity. * `is_primitive_root.card_primitive_roots`: if an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. ## Implementation details It is desirable that `roots_of_unity` is a subgroup, and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields. We therefore implement it as a subgroup of the units of a commutative monoid. We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`, because almost all lemmas need the positivity assumption, and in particular the type class instances for `fintype` and `is_cyclic`. On the other hand, for primitive roots of unity, it is desirable to have a predicate not just on units, but directly on elements of the ring/field. For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity in the complex numbers, without having to turn that number into a unit first. This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and `is_primitive_root.coe_units_iff` should provide the necessary glue. -/ open_locale classical big_operators noncomputable theory open polynomial open finset variables {M N G G₀ R S : Type*} variables [comm_monoid M] [comm_monoid N] [comm_group G] [comm_group_with_zero G₀] section roots_of_unity variables {k l : ℕ+} /-- `roots_of_unity k M` is the subgroup of elements `m : units M` that satisfy `m ^ k = 1` -/ def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup (units M) := { carrier := { ζ | ζ ^ (k : ℕ) = 1 }, one_mem' := one_pow _, mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *, inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, one_inv] at * } @[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : units M) : ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M := begin obtain ⟨d, rfl⟩ := h, intros ζ h, simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *, end lemma map_roots_of_unity (f : units M →* units N) (k : ℕ+) : (roots_of_unity k M).map f ≤ roots_of_unity k N := begin rintros _ ⟨ζ, h, rfl⟩, simp only [←monoid_hom.map_pow, *, mem_roots_of_unity, set_like.mem_coe, monoid_hom.map_one] at * end variables [comm_ring R] @[norm_cast] lemma roots_of_unity.coe_pow (ζ : roots_of_unity k R) (m : ℕ) : ↑(ζ ^ m) = (ζ ^ m : R) := begin change ↑(↑(ζ ^ m) : units R) = ↑(ζ : units R) ^ m, rw [subgroup.coe_pow, units.coe_pow], end variables [comm_ring S] /-- Restrict a ring homomorphism between integral domains to the nth roots of unity -/ def ring_hom.restrict_roots_of_unity (σ : R →+* S) (n : ℕ+) : roots_of_unity n R →* roots_of_unity n S := let h : ∀ ξ : roots_of_unity n R, (σ ξ) ^ (n : ℕ) = 1 := λ ξ, by { change (σ (ξ : units R)) ^ (n : ℕ) = 1, rw [←σ.map_pow, ←units.coe_pow, show ((ξ : units R) ^ (n : ℕ) = 1), from ξ.2, units.coe_one, σ.map_one] } in { to_fun := λ ξ, ⟨@unit_of_invertible _ _ _ (invertible_of_pow_eq_one _ _ (h ξ) n.2), by { ext, rw units.coe_pow, exact h ξ }⟩, map_one' := by { ext, exact σ.map_one }, map_mul' := λ ξ₁ ξ₂, by { ext, rw [subgroup.coe_mul, units.coe_mul], exact σ.map_mul _ _ } } @[simp] lemma ring_hom.restrict_roots_of_unity_coe_apply (σ : R →+* S) (ζ : roots_of_unity k R) : ↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ := rfl /-- Restrict a ring isomorphism between integral domains to the nth roots of unity -/ def ring_equiv.restrict_roots_of_unity (σ : R ≃+* S) (n : ℕ+) : roots_of_unity n R ≃* roots_of_unity n S := { to_fun := σ.to_ring_hom.restrict_roots_of_unity n, inv_fun := σ.symm.to_ring_hom.restrict_roots_of_unity n, left_inv := λ ξ, by { ext, exact σ.symm_apply_apply ξ }, right_inv := λ ξ, by { ext, exact σ.apply_symm_apply ξ }, map_mul' := (σ.to_ring_hom.restrict_roots_of_unity n).map_mul } @[simp] lemma ring_equiv.restrict_roots_of_unity_coe_apply (σ : R ≃+* S) (ζ : roots_of_unity k R) : ↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ := rfl @[simp] lemma ring_equiv.restrict_roots_of_unity_symm (σ : R ≃+* S) : (σ.restrict_roots_of_unity k).symm = σ.symm.restrict_roots_of_unity k := rfl variables [is_domain R] lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : units R} : ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) := by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow] variables (k R) /-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`. This is implemented as equivalence of subtypes, because `roots_of_unity` is a subgroup of the group of units, whereas `nth_roots` is a multiset. -/ def roots_of_unity_equiv_nth_roots : roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} := begin refine { to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩, inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩, left_inv := _, right_inv := _ }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, all_goals { rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx, simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx, tsub_add_cancel_of_le (show 1 ≤ (k : ℕ), from k.one_le)] }, { show (_ : units R) ^ (k : ℕ) = 1, simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] } end variables {k R} @[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) : (roots_of_unity_equiv_nth_roots R k x : R) = x := rfl @[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) : ((roots_of_unity_equiv_nth_roots R k).symm x : R) = x := rfl variables (k R) instance roots_of_unity.fintype : fintype (roots_of_unity k R) := fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) := is_cyclic_of_subgroup_is_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype) (units.ext.comp subtype.val_injective) lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k := calc fintype.card (roots_of_unity k R) = fintype.card {x // x ∈ nth_roots k (1 : R)} : fintype.card_congr (roots_of_unity_equiv_nth_roots R k) ... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.erase_dup_le _) ... = (nth_roots k (1 : R)).card : multiset.card_attach ... ≤ k : card_nth_roots k 1 variables {k R} lemma ring_hom.map_root_of_unity_eq_pow_self (σ : R →+* R) (ζ : roots_of_unity k R) : ∃ m : ℕ, σ ζ = ζ ^ m := begin obtain ⟨m, hm⟩ := (σ.restrict_roots_of_unity k).map_cyclic, rw [←σ.restrict_roots_of_unity_coe_apply, hm, zpow_eq_mod_order_of, ←int.to_nat_of_nonneg (m.mod_nonneg (int.coe_nat_ne_zero.mpr (pos_iff_ne_zero.mp (order_of_pos ζ)))), zpow_coe_nat, roots_of_unity.coe_pow], exact ⟨(m % (order_of ζ)).to_nat, rfl⟩, end end roots_of_unity /-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/ structure is_primitive_root (ζ : M) (k : ℕ) : Prop := (pow_eq_one : ζ ^ (k : ℕ) = 1) (dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l) section primitive_roots variables {k : ℕ} /-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity in the integral domain `R`. -/ def primitive_roots (k : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := (nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k) variables [comm_ring R] [is_domain R] @[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) : ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k := begin rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp], exact is_primitive_root.pow_eq_one end end primitive_roots namespace is_primitive_root variables {k l : ℕ} lemma iff_def (ζ : M) (k : ℕ) : is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) := ⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩ lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) : is_primitive_root ζ k := begin refine ⟨h1, _⟩, intros l hl, apply dvd_trans _ (k.gcd_dvd_right l), suffices : k.gcd l = k, { rw this }, rw eq_iff_le_not_lt, refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩, intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h', exact pow_gcd_eq_one _ h1 hl end section comm_monoid variables {ζ : M} (h : is_primitive_root ζ k) lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l := ⟨h.dvd_of_pow_eq_one l, by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩ lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ := begin apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)), rw [← pow_succ, tsub_add_cancel_of_le h0.nat_succ_le, h.pow_eq_one] end lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 := mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) : i = j := begin wlog hij : i ≤ j, apply le_antisymm hij, rw ← tsub_eq_zero_iff_le, apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt tsub_le_self hj), apply h.dvd_of_pow_eq_one, rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj, ← pow_add, tsub_add_cancel_of_le hij, H, one_mul] end lemma one : is_primitive_root (1 : M) 1 := { pow_eq_one := pow_one _, dvd_of_pow_eq_one := λ l hl, one_dvd _ } @[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 := begin split, { intro h, rw [← pow_one ζ, h.pow_eq_one] }, { rintro rfl, exact one } end @[simp] lemma coe_units_iff {ζ : units M} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one] lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : k = 0, { subst k, simp only [*, pow_one, nat.coprime_zero_right] at * }, rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩, rw [← units.coe_pow], rw coe_units_iff at h ⊢, refine { pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow], dvd_of_pow_eq_one := _ }, intros l hl, apply h.dvd_of_pow_eq_one, rw [← pow_one ζ, ← zpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, zpow_add, mul_pow, ← zpow_coe_nat, ← zpow_mul, mul_right_comm], simp only [zpow_mul, hl, h.pow_eq_one, one_zpow, one_pow, one_mul, zpow_coe_nat] end lemma pow_of_prime (h : is_primitive_root ζ k) {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ k) : is_primitive_root (ζ ^ p) k := h.pow_of_coprime p (hprime.coprime_iff_not_dvd.2 hdiv) lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) : is_primitive_root (ζ ^ i) k ↔ i.coprime k := begin refine ⟨_, h.pow_of_coprime i⟩, intro hi, obtain ⟨a, ha⟩ := i.gcd_dvd_left k, obtain ⟨b, hb⟩ := i.gcd_dvd_right k, suffices : b = k, { rwa [this, ← one_mul k, nat.mul_left_inj h0, eq_comm] at hb { occs := occurrences.pos [1] } }, rw [ha] at hi, rw [mul_comm] at hb, apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _), rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow] end end comm_monoid section comm_group variables {ζ : G} lemma zpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 := by { rw zpow_coe_nat, exact h.pow_eq_one } lemma zpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [zpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← zpow_neg, ← hl', zpow_coe_nat, one_inv] } end lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, one_inv, eq_self_iff_true, inv_pow], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj, ← inv_pow, hl, one_inv] end } @[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h } lemma zpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, rw zpow_coe_nat, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff, ← zpow_neg, ← hi', zpow_coe_nat], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end @[simp] lemma coe_subgroup_iff (H : subgroup G) {ζ : H} : is_primitive_root (ζ : G) k ↔ is_primitive_root ζ k := by simp only [iff_def, ← subgroup.coe_pow, ← H.coe_one, ← subtype.ext_iff] end comm_group section comm_group_with_zero variables {ζ : G₀} lemma zpow_eq_one₀ (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 := by { rw zpow_coe_nat, exact h.pow_eq_one } lemma zpow_eq_one_iff_dvd₀ (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [zpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj₀, ← zpow_neg₀, ← hl', zpow_coe_nat, inv_one] } end lemma inv' (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow₀], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj₀, ← inv_pow₀, hl, inv_one] end } @[simp] lemma inv_iff' : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv' h⟩, intro h, rw [← inv_inv₀ ζ], exact inv' h } lemma zpow_of_gcd_eq_one₀ (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, rw zpow_coe_nat, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff', ← zpow_neg₀, ← hi', zpow_coe_nat], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end end comm_group_with_zero section is_domain variables {ζ : R} variables [comm_ring R] [is_domain R] @[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ := begin rw [← finset.val_eq_zero, ← multiset.subset_zero, ← nth_roots_zero (1 : R), primitive_roots], simp only [finset.not_mem_empty, forall_const, forall_prop_of_false, multiset.to_finset_zero, finset.filter_true_of_mem, finset.empty_val, not_false_iff, multiset.zero_subset, nth_roots_zero] end @[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} := begin apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] }, { intros x hx, rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx, exact hx } end lemma neg_one (p : ℕ) [char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 := mk_of_lt (-1 : R) dec_trivial (by simp only [one_pow, neg_sq]) $ begin intros l hl0 hl2, obtain rfl : l = 1, { unfreezingI { clear_dependent R p }, dec_trivial! }, simp only [pow_one, ne.def], intro h, suffices h2 : p ∣ 2, { have := char_p.char_ne_one R p, unfreezingI { clear_dependent R }, have aux := nat.le_of_dvd dec_trivial h2, revert this hp h2, revert p, dec_trivial }, simp only [← char_p.cast_eq_zero_iff R p, nat.cast_bit0, nat.cast_one], rw [bit0, ← h, neg_add_self] { occs := occurrences.pos [1] } end lemma eq_neg_one_of_two_right (h : is_primitive_root ζ 2) : ζ = -1 := begin apply (eq_or_eq_neg_of_sq_eq_sq ζ 1 _).resolve_left, { rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial }, { simp only [h.pow_eq_one, one_pow] } end end is_domain section is_domain variables [comm_ring R] variables {ζ : units R} (h : is_primitive_root ζ k) protected lemma mem_roots_of_unity {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n R := h.pow_eq_one /-- The (additive) monoid equivalence between `zmod k` and the powers of a primitive root of unity `ζ`. -/ def zmod_equiv_zpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.zpowers ζ) := add_equiv.of_bijective (add_monoid_hom.lift_of_right_inverse (int.cast_add_hom $ zmod k) _ zmod.int_cast_right_inverse ⟨{ to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.zpowers ζ), map_zero' := by { simp only [zpow_zero], refl }, map_add' := by { intros i j, simp only [zpow_add], refl } }, (λ i hi, begin simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k, add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢, obtain ⟨i, rfl⟩ := hi, simp only [zpow_mul, h.pow_eq_one, one_zpow, zpow_coe_nat], refl end)⟩) begin split, { rw add_monoid_hom.injective_iff, intros i hi, rw subtype.ext_iff at hi, have := (h.zpow_eq_one_iff_dvd _).mp hi, rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm], exact zmod.int_cast_right_inverse i }, { rintro ⟨ξ, i, rfl⟩, refine ⟨int.cast_add_hom _ i, _⟩, rw [add_monoid_hom.lift_of_right_inverse_comp_apply], refl } end @[simp] lemma zmod_equiv_zpowers_apply_coe_int (i : ℤ) : h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) := add_monoid_hom.lift_of_right_inverse_comp_apply _ _ zmod.int_cast_right_inverse _ _ @[simp] lemma zmod_equiv_zpowers_apply_coe_nat (i : ℕ) : h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) := begin have : (i : zmod k) = (i : ℤ), by norm_cast, simp only [this, zmod_equiv_zpowers_apply_coe_int, zpow_coe_nat], refl end @[simp] lemma zmod_equiv_zpowers_symm_apply_zpow (i : ℤ) : h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i := by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_int] @[simp] lemma zmod_equiv_zpowers_symm_apply_zpow' (i : ℤ) : h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_zpowers_symm_apply_zpow i @[simp] lemma zmod_equiv_zpowers_symm_apply_pow (i : ℕ) : h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i := by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_nat] @[simp] lemma zmod_equiv_zpowers_symm_apply_pow' (i : ℕ) : h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_zpowers_symm_apply_pow i /-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`, then there is a `b`-th primitive root of unity in `R`. -/ lemma pow {ζ : R} {n : ℕ} {a b : ℕ} (hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) : is_primitive_root (ζ ^ a) b := begin subst n, simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and], intros l hl, have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn }, rwa ← mul_dvd_mul_iff_left ha0, exact h.dvd_of_pow_eq_one _ hl end variables [is_domain R] lemma zpowers_eq {k : ℕ+} {ζ : units R} (h : is_primitive_root ζ k) : subgroup.zpowers ζ = roots_of_unity k R := begin apply set_like.coe_injective, haveI : fact (0 < (k : ℕ)) := ⟨k.pos⟩, haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_zpowers).to_equiv, refine @set.eq_of_subset_of_card_le (units R) (subgroup.zpowers ζ) (roots_of_unity k R) F (roots_of_unity.fintype R k) (subgroup.zpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _, calc fintype.card (roots_of_unity k R) ≤ k : card_roots_of_unity R k ... = fintype.card (zmod k) : (zmod.card k).symm ... = fintype.card (subgroup.zpowers ζ) : fintype.card_congr (h.zmod_equiv_zpowers).to_equiv end lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) : ∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ := begin obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.zpowers_eq] at hξ, have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos, let i := n % k, have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0), lift i to ℕ using hi0 with i₀ hi₀, refine ⟨i₀, _, _⟩, { zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 }, { have aux := h.zpow_eq_one, rw [← coe_coe] at aux, rw [← zpow_coe_nat, hi₀, ← int.mod_add_div n k, zpow_add, zpow_mul, aux, one_zpow, mul_one] } end lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) : ∃ i < k, ζ ^ i = ξ := begin obtain ⟨ζ, rfl⟩ := h.is_unit h0, obtain ⟨ξ, rfl⟩ := is_unit_of_pow_eq_one ξ k hξ h0, obtain ⟨k, rfl⟩ : ∃ k' : ℕ+, k = k' := ⟨⟨k, h0⟩, rfl⟩, simp only [← units.coe_pow, ← units.ext_iff], rw coe_units_iff at h, apply h.eq_pow_of_mem_roots_of_unity, rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one] end lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) : is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one, rw h.pow_iff_coprime k.pos at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) : is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0, rw h.pow_iff_coprime h0 at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin haveI : fact (0 < ↑n) := ⟨n.pos⟩, let e := h.zmod_equiv_zpowers, haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ e.to_equiv, calc fintype.card (roots_of_unity n R) = fintype.card (subgroup.zpowers ζ) : fintype.card_congr $ by rw h.zpowers_eq ... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm ... = n : zmod.card n end lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin obtain ⟨ζ, hζ⟩ := h.is_unit n.pos, rw [← hζ, is_primitive_root.coe_units_iff] at h, exact h.card_roots_of_unity' end /-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n` if there is a primitive root of unity in `R`. -/ lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).card = n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.card_zero, nth_roots_zero] }, rw eq_iff_le_not_lt, use card_nth_roots n 1, { rw [not_lt], have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)} ≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.erase_dup_le _), rw multiset.card_attach at hcard, rw ← pnat.to_pnat'_coe hpos at hcard h ⊢, set m := nat.to_pnat' n, rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard, exact hcard } end /-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements if there is a primitive root of unity in `R`. -/ lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.nodup_zero, nth_roots_zero] }, apply (@multiset.erase_dup_eq_self R _ _).1, rw eq_iff_le_not_lt, split, { exact multiset.erase_dup_le (nth_roots n (1 : R)) }, { by_contra ha, replace ha := multiset.card_lt_of_lt ha, rw card_nth_roots h at ha, have hrw : (nth_roots n (1 : R)).erase_dup.card = fintype.card {x // x ∈ (nth_roots n (1 : R))}, { set fs := (⟨(nth_roots n (1 : R)).erase_dup, multiset.nodup_erase_dup _⟩ : finset R), rw [← finset.card_mk, ← fintype.card_of_subtype fs _], intro x, simp only [multiset.mem_erase_dup, finset.mem_mk] }, rw ← pnat.to_pnat'_coe hpos at h hrw ha, set m := nat.to_pnat' n, rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at ha, exact nat.lt_asymm ha ha } end @[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots_finset n R).card = n := by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots] open_locale nat /-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/ lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) (h0 : 0 < k) : (primitive_roots k R).card = φ k := begin symmetry, refine finset.card_congr (λ i _, ζ ^ i) _ _ _, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i - hi, rw mem_primitive_roots h0, exact h.pow_of_coprime i hi.symm }, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i j hi - hj - H, exact h.pow_inj hi hj H }, { simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ], intros ξ hξ, rw [mem_primitive_roots h0, h.is_primitive_root_iff h0] at hξ, rcases hξ with ⟨i, hin, hi, H⟩, exact ⟨i, ⟨hin, hi.symm⟩, H⟩ } end /-- The sets `primitive_roots k R` are pairwise disjoint. -/ lemma disjoint {k l : ℕ} (hk : 0 < k) (hl : 0 < l) (h : k ≠ l) : disjoint (primitive_roots k R) (primitive_roots l R) := begin intro z, simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots, hk, hl, iff_def], rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩, apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl] end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors ↑n).bUnion (λ i, (primitive_roots i R)) := begin symmetry, apply finset.eq_of_subset_of_card_le, { intros x, simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), exists_prop, finset.mem_bUnion, finset.mem_filter, finset.mem_range, mem_nth_roots, finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff], rintro ⟨a, ⟨d, hd⟩, ha⟩, have hazero : 0 < a, { contrapose! hd with ha0, simp only [nonpos_iff_eq_zero, zero_mul, *] at *, exact n.ne_zero }, rw mem_primitive_roots hazero at ha, rw [hd, pow_mul, ha.pow_eq_one, one_pow] }, { apply le_of_eq, rw [h.card_nth_roots_finset, finset.card_bUnion], { rw [← nat.sum_totient n, nat.filter_dvd_eq_divisors (pnat.ne_zero n), sum_congr rfl] { occs := occurrences.pos [1] }, simp only [finset.mem_filter, finset.mem_range, nat.mem_divisors], rintro k ⟨H, hk⟩, have hdvd := H, rcases H with ⟨d, hd⟩, rw mul_comm at hd, rw (h.pow n.pos hd).card_primitive_roots (pnat.pos_of_div_pos hdvd) }, { intros i hi j hj hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hi hj, exact disjoint (pnat.pos_of_div_pos hi) (pnat.pos_of_div_pos hj) hdiff } } end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots {ζ : R} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors n).bUnion (λ i, (primitive_roots i R)) := @nth_roots_one_eq_bUnion_primitive_roots' _ _ _ _ ⟨n, hpos⟩ h end is_domain section minpoly open minpoly variables {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) include n μ h hpos /--`μ` is integral over `ℤ`. -/ lemma is_integral : is_integral ℤ μ := begin use (X ^ n - 1), split, { exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) }, { simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub, sub_self] } end variables [char_zero K] /--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/ lemma minpoly_dvd_X_pow_sub_one : minpoly ℤ μ ∣ X ^ n - 1 := begin apply minpoly.gcd_domain_dvd ℚ (is_integral h hpos) (polynomial.monic.is_primitive (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm)), simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, ring_hom.eq_int_cast, int.cast_one, aeval_one, alg_hom.map_sub, sub_self] end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/ lemma separable_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) : separable (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := begin have hdvd : (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) ∣ X ^ n - 1, { simpa [map_pow, map_X, map_one, map_sub] using ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))) (minpoly_dvd_X_pow_sub_one h hpos) }, refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 hzero) end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/ lemma squarefree_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) : squarefree (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := (separable_minpoly_mod h hpos hdiv).squarefree /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `expand ℤ p Q`. -/ lemma minpoly_dvd_expand {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ n) : minpoly ℤ μ ∣ expand ℤ p (minpoly ℤ (μ ^ p)) := begin apply minpoly.gcd_domain_dvd ℚ (h.is_integral hpos), { apply monic.is_primitive, rw [polynomial.monic, leading_coeff, nat_degree_expand, mul_comm, coeff_expand_mul' (nat.prime.pos hprime), ← leading_coeff, ← polynomial.monic], exact minpoly.monic (is_integral (pow_of_prime h hprime hdiv) hpos) }, { rw [aeval_def, coe_expand, ← comp, eval₂_eq_eval_map, map_comp, map_pow, map_X, eval_comp, eval_pow, eval_X, ← eval₂_eq_eval_map, ← aeval_def], exact minpoly.aeval _ _ } end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q ^ p` modulo `p`. -/ lemma minpoly_dvd_pow_mod {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) ^ p := begin set Q := minpoly ℤ (μ ^ p), have hfrob : map (int.cast_ring_hom (zmod p)) Q ^ p = map (int.cast_ring_hom (zmod p)) (expand ℤ p Q), by rw [← zmod.expand_card, map_expand hprime.1.pos], rw [hfrob], apply ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))), exact minpoly_dvd_expand h hpos hprime.1 hdiv end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q` modulo `p`. -/ lemma minpoly_dvd_mod_p {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) := (unique_factorization_monoid.dvd_pow_iff_dvd_of_squarefree (squarefree_minpoly_mod h hpos hdiv) hprime.1.ne_zero).1 (minpoly_dvd_pow_mod h hpos hdiv) /-- If `p` is a prime that does not divide `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ p` are the same. -/ lemma minpoly_eq_pow {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : minpoly ℤ μ = minpoly ℤ (μ ^ p) := begin by_contra hdiff, set P := minpoly ℤ μ, set Q := minpoly ℤ (μ ^ p), have Pmonic : P.monic := minpoly.monic (h.is_integral hpos), have Qmonic : Q.monic := minpoly.monic ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have Pirr : irreducible P := minpoly.irreducible (h.is_integral hpos), have Qirr : irreducible Q := minpoly.irreducible ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have PQprim : is_primitive (P * Q) := Pmonic.is_primitive.mul Qmonic.is_primitive, have prod : P * Q ∣ X ^ n - 1, { rw [(is_primitive.int.dvd_iff_map_cast_dvd_map_cast (P * Q) (X ^ n - 1) PQprim (monic_X_pow_sub_C (1 : ℤ) (ne_of_gt hpos)).is_primitive), map_mul], refine is_coprime.mul_dvd _ _ _, { have aux := is_primitive.int.irreducible_iff_irreducible_map_cast Pmonic.is_primitive, refine (dvd_or_coprime _ _ (aux.1 Pirr)).resolve_left _, rw map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic, intro hdiv, refine hdiff (eq_of_monic_of_associated Pmonic Qmonic _), exact associated_of_dvd_dvd hdiv (Pirr.dvd_symm Qirr hdiv) }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2, exact minpoly_dvd_X_pow_sub_one h hpos }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Qmonic).2, exact minpoly_dvd_X_pow_sub_one (pow_of_prime h hprime.1 hdiv) hpos } }, replace prod := ring_hom.map_dvd ((map_ring_hom (int.cast_ring_hom (zmod p)))) prod, rw [coe_map_ring_hom, map_mul, map_sub, map_one, map_pow, map_X] at prod, obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hpos hdiv, rw [hR, ← mul_assoc, ← map_mul, ← sq, map_pow] at prod, have habs : map (int.cast_ring_hom (zmod p)) P ^ 2 ∣ map (int.cast_ring_hom (zmod p)) P ^ 2 * R, { use R }, replace habs := lt_of_lt_of_le (enat.coe_lt_coe.2 one_lt_two) (multiplicity.le_multiplicity_of_pow_dvd (dvd_trans habs prod)), have hfree : squarefree (X ^ n - 1 : polynomial (zmod p)), { refine squarefree_X_pow_sub_C 1 _ one_ne_zero, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 hzero) }, cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree (map (int.cast_ring_hom (zmod p)) P) with hle hunit, { rw nat.cast_one at habs, exact hle.not_lt habs }, { replace hunit := degree_eq_zero_of_is_unit hunit, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom (zmod p)) _ at hunit, { exact (minpoly.degree_pos (is_integral h hpos)).ne' hunit }, simp only [Pmonic, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ m` are the same. -/ lemma minpoly_eq_pow_coprime {m : ℕ} (hcop : nat.coprime m n) : minpoly ℤ μ = minpoly ℤ (μ ^ m) := begin revert n hcop, refine unique_factorization_monoid.induction_on_prime m _ _ _, { intros n hn h hpos, congr, simpa [(nat.coprime_zero_left n).mp hn] using h }, { intros u hunit n hcop h hpos, congr, simp [nat.is_unit_iff.mp hunit] }, { intros a p ha hprime hind n hcop h hpos, rw hind (nat.coprime.coprime_mul_left hcop) h hpos, clear hind, replace hprime := nat.prime_iff.2 hprime, have hdiv := (nat.prime.coprime_iff_not_dvd hprime).1 (nat.coprime.coprime_mul_right hcop), haveI := fact.mk hprime, rw [minpoly_eq_pow (h.pow_of_coprime a (nat.coprime.coprime_mul_left hcop)) hpos hdiv], congr' 1, ring_exp } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomial of a primitive `n`-th root of unity `μ` has `μ ^ m` as root. -/ lemma pow_is_root_minpoly {m : ℕ} (hcop : nat.coprime m n) : is_root (map (int.cast_ring_hom K) (minpoly ℤ μ)) (μ ^ m) := by simpa [minpoly_eq_pow_coprime h hpos hcop, eval_map, aeval_def (μ ^ m) _] using minpoly.aeval ℤ (μ ^ m) /-- `primitive_roots n K` is a subset of the roots of the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma is_roots_of_minpoly : primitive_roots n K ⊆ (map (int.cast_ring_hom K) (minpoly ℤ μ)).roots.to_finset := begin intros x hx, obtain ⟨m, hle, hcop, rfl⟩ := (is_primitive_root_iff h hpos).1 ((mem_primitive_roots hpos).1 hx), simpa [multiset.mem_to_finset, mem_roots (map_monic_ne_zero $ minpoly.monic $ is_integral h hpos)] using pow_is_root_minpoly h hpos hcop end /-- The degree of the minimal polynomial of `μ` is at least `totient n`. -/ lemma totient_le_degree_minpoly : nat.totient n ≤ (minpoly ℤ μ).nat_degree := let P : polynomial ℤ := minpoly ℤ μ,-- minimal polynomial of `μ` P_K : polynomial K := map (int.cast_ring_hom K) P -- minimal polynomial of `μ` sent to `K[X]` in calc n.totient = (primitive_roots n K).card : (h.card_primitive_roots hpos).symm ... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h hpos) ... ≤ P_K.roots.card : multiset.to_finset_card_le _ ... ≤ P_K.nat_degree : (card_roots' $ map_monic_ne_zero (minpoly.monic $ is_integral h hpos)) ... ≤ P.nat_degree : nat_degree_map_le _ _ end minpoly end is_primitive_root
3ce8d52290710c31dfd7d4f5ac1ada3a49d3de2a
1e3a43e8ba59c6fe1c66775b6e833e721eaf1675
/src/algebra/big_operators.lean
31a8097959381b74f8c8920752f59b51a151845b
[ "Apache-2.0" ]
permissive
Sterrs/mathlib
ea6910847b8dfd18500486de9ab0ee35704a3f52
d9327e433804004aa1dc65091bbe0de1e5a08c5e
refs/heads/master
1,650,769,884,257
1,587,808,694,000
1,587,808,694,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,433
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Some big operators for lists and finite sets. -/ import data.finset import data.nat.enat import tactic.omega universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `s.prod f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`s.sum f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (s.prod f) = s.prod (λx, g (f x)) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (s.prod f) = s.prod (λx, g (f x)) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [semiring β] [semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (s.sum f) = s.sum (λx, g (f x)) := g.to_add_monoid_hom.map_sum f s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : ({a, b} : finset α).prod f = f a * f b := by simp [prod_insert (not_mem_singleton.2 h.symm), mul_comm] @[simp, priority 1100] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : (s.image sum.inl ∪ t.image sum.inr).prod (sum.elim f g) = s.prod f * t.prod g := begin rw [prod_union, prod_image, prod_image], { simp only [sum.elim_inl, sum.elim_inr] }, { exact λ _ _ _ _, sum.inr.inj }, { exact λ _ _ _ _, sum.inl.inj }, { rintros i hi, erw [finset.mem_inter, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨⟨i, hi, rfl⟩, ⟨j, hj, H⟩⟩, cases H } end @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (s.filter $ λx, f x ≠ 1).prod f = s.prod f := prod_subset (filter_subset _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact and.intro } @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : s.prod (λ x, if p x then f x else g x) = (s.filter p).prod (λ x, f x) * (s.filter (λ x, ¬ p x)).prod (λ x, g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : s.prod (λ x, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : s.prod (λ x, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := begin rw ←prod_ite_eq, congr, ext x, by_cases x = a; finish end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by classical; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : prod_filter_ne_one.symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : s.prod f ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : s.prod f ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : (finset.range n).sum (λ i, f (i+1) - f i) = f n - f 0 := begin induction n with n IH, { simp }, rw [finset.sum_range_succ, IH, nat.succ_eq_add_one], have : f n ≤ f (n+1) := h (nat.le_succ _), have : f 0 ≤ f n := h (nat.zero_le _), omega end lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a ≤ b) (f : ℕ → δ) : (Ico a (b + 1)).sum f = (Ico a b).sum f + f b := by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm] @[to_additive] lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) : (Ico a b.succ).prod f = (Ico a b).prod f * f b := @sum_Ico_succ_top (additive β) _ _ _ hab _ lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a < b) (f : ℕ → δ) : (Ico a b).sum f = f a + (Ico (a + 1) b).sum f := have ha : a ∉ Ico (a + 1) b, by simp, by rw [← sum_insert ha, Ico.insert_succ_bot hab] @[to_additive] lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) : (Ico a b).prod f = f a * (Ico (a + 1) b).prod f := @sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _ @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) -- `to_additive` fails on this lemma, so we prove it manually below lemma prod_flip {n : ℕ} (f : ℕ → β) : (range (nat.succ n)).prod (λ r, f (n - r)) = (range (nat.succ n)).prod f := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n), mul_comm], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx])) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one /-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets of `s`, and over all subsets of `s` to which one adds `x`. -/ @[to_additive] lemma prod_powerset_insert [decidable_eq α] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) : (insert x s).powerset.prod f = s.powerset.prod f * s.powerset.prod (λt, f (insert x t)) := begin rw [powerset_insert, finset.prod_union, finset.prod_image], { assume t₁ h₁ t₂ h₂ heq, rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h), ← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] }, { rw finset.disjoint_iff_ne, assume t₁ h₁ t₂ h₂, rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩, rw ← H₃₂, exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) } end @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : s.prod (t.piecewise f g) = (s ∩ t).prod f * (s \ t).prod g := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (s.filter (λy, y ≈ x)).prod f = 1) : s.prod f = 1 := begin suffices : (s.image quotient.mk).prod (λ xbar, (s.filter (λ y, ⟦y⟧ = xbar)).prod f) = s.prod f, { rw [←this, ←finset.prod_eq_one], intros xbar xbar_in_s, rcases (mem_image).mp xbar_in_s with ⟨x, x_in_s, xbar_eq_x⟩, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s }, apply finset.prod_image' f, intros, refl end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : s.prod (function.update f i b) = s.prod f := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : s.prod (function.update f i b) = b * (s \ (singleton i)).prod f := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } end comm_monoid lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : s.sum (function.update f i b) = b + (s \ (singleton i)).sum f := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_smul' [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul'] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) : s.sum f = card s * m := begin rw [← nat.smul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} : s.sum (λ x, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) : (range (nat.succ n)).sum (λ r, f (n - r)) = (range (nat.succ n)).sum f := @prod_flip (multiplicative β) _ _ _ attribute [to_additive] prod_flip lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (nat.cast_add_monoid_hom β).map_sum f s lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (nat.cast_ring_hom β).map_prod f s protected lemma sum_nat_coe_enat (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin classical, induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α} (h : ∀ x ∈ s, a ∣ f x) : a ∣ s.sum f := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (s.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section comm_monoid variables [comm_monoid β] lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.prod (λ x, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (s.sum_hom (λ x, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (s.sum_hom _).symm lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := by simp lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := by simp end semiring lemma sum_div [division_ring β] {s : finset α} {f : α → β} {b : β} : s.sum f / b = s.sum (λx, f x / b) := calc s.sum f / b = s.sum (λ x, f x * (1 / b)) : by rw [div_eq_mul_one_div, sum_mul] ... = s.sum (λ x, f x / b) : by { congr, ext, rw ← div_eq_mul_one_div (f x) b } section comm_semiring variables [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := by haveI := classical.dec_eq α; calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] /-- The product over a sum can be written as a sum over the product of sets, `finset.pi`. `finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/ lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end open_locale classical /-- The product of `f a + g a` over all of `s` is the sum over the powerset of `s` of the product of `f` over a subset `t` times the product of `g` over the complement of `t` -/ lemma prod_add (f g : α → β) (s : finset α) : s.prod (λ a, f a + g a) = s.powerset.sum (λ t : finset α, t.prod f * (s \ t).prod g) := calc s.prod (λ a, f a + g a) = s.prod (λ a, ({false, true} : finset Prop).sum (λ p : Prop, if p then f a else g a)) : by simp ... = (s.pi (λ _, {false, true})).sum (λ p : Π a ∈ s, Prop, s.attach.prod (λ a : {a // a ∈ s}, if p a.1 a.2 then f a.1 else g a.1)) : prod_sum ... = s.powerset.sum (λ (t : finset α), t.prod f * (s \ t).prod g) : begin refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _), { simp [subset_iff]; tauto }, { intros t ht, erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)], refine congr_arg2 _ (prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩) _ _ _ (λ b hb, ⟨b, by cases b; finish⟩)) (prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩) _ _ _ (λ b hb, ⟨b, by cases b; finish⟩)); intros; simp * at *; simp * at * }, { finish [function.funext_iff, finset.ext, subset_iff] }, { assume f hf, exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h), by simp, by funext; intros; simp *⟩ } end /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset` gives `(a + b)^s.card`.-/ lemma sum_pow_mul_eq_add_pow {α R : Type*} [comm_semiring R] (a b : R) (s : finset α) : s.powerset.sum (λ t : finset α, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card := begin rw [← prod_const, prod_add], refine finset.sum_congr rfl (λ t ht, _), rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)] end lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} : ∀ {s : finset α}, s.prod (λ i, x ^ (f i)) = x ^ (s.sum f) := begin apply finset.induction, { simp }, { assume a s has H, rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end end integral_domain section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := begin classical, apply finset.induction_on s, exact (λ _, le_refl _), assume a s ha ih h, have : f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] end lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := by classical; calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] end lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_add_comm_monoid section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := by classical; calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_add_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_add_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : s.sum f < s.sum g := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) : s.sum f < s.sum g := begin apply sum_lt_sum, { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end lemma sum_lt_sum_of_subset [decidable_eq α] (h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) : s₁.sum f < s₂.sum f := calc s₁.sum f < (insert i s₁).sum f : begin simp only [mem_sdiff] at hi, rw sum_insert hi.2, exact lt_add_of_pos_left (finset.sum s₁ f) hpos, end ... ≤ s₂.sum f : begin simp only [mem_sdiff] at hi, apply sum_le_sum_of_subset_of_nonneg, { simp [finset.insert_subset, h, hi.1] }, { assume x hx h'x, apply hnonneg x, simp [mem_insert, not_or_distrib] at h'x, rw mem_sdiff, simp [hx, h'x] } end end ordered_cancel_comm_monoid section decidable_linear_ordered_cancel_comm_monoid variables [decidable_linear_ordered_cancel_add_comm_monoid β] theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : s.sum f ≤ s.sum g) : ∃ i ∈ s, f i ≤ g i := begin classical, contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end end decidable_linear_ordered_cancel_comm_monoid section linear_ordered_comm_ring variables [linear_ordered_comm_ring β] open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring β] lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) : s.prod f ≤ s.prod g := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply canonically_ordered_semiring.mul_le_mul, { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end end canonically_ordered_comm_semiring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_Ico_id_eq_fact : ∀ n : ℕ, (Ico 1 n.succ).prod (λ x, x) = nat.fact n | 0 := rfl | (n+1) := by rw [prod_Ico_succ_top $ nat.succ_le_succ $ zero_le n, nat.fact_succ, prod_Ico_id_eq_fact n, nat.succ_eq_add_one, mul_comm] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset namespace with_top open finset open_locale classical /-- sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ }) (λa s ha ih h, begin rw [sum_insert ha, add_lt_top], split, { apply h, apply mem_insert_self }, { apply ih, intros a ha, apply h, apply mem_insert_of_mem ha } end) /-- sum of finite numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top end with_top
4c429f26747c8a2f22ab2bfd5886dce0eebca5e0
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-numbertheory-101.lean
20d14bd01abc001e6314871c9022cb4f964ed097
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
243
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.nat.basic import data.real.basic example : (17 * 18) % 4 = 2 := begin norm_num, end
ff385315fcf659986300bcccc97a14b5b6b201a0
b392eb79fb36952401156496daa60628ccb07438
/Lib4/PrePort/Numbers.lean
412a8b6672df0c1204ead79985c4747486ea01cb
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
1,906
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam In Lean3, numerals are encoded using 0, 1, bit0, and bit1, whereas in Lean4, nats are encoded as kernel literals and numerals of type α are encoded using the following class: class OfNat (α : Type u) (n : Nat) where ofNat : α Specifically, the numeral (17 : α) is notation for @OfNat.ofNat α 17 (inst : OfNat α 17) We automatically wrap the bit-representation with the OfNat representation during porting (the two are definitionally equal). The non-kernel-computing `nat2bits` instance cannot be used during porting, since mathlib currently relies on e.g. 2+2=4 computing in the kernel. We keep it in PrePort to support various typeclass experiments. -/ namespace Mathlib -- We define these classes here so that we can align Mathlib's -- classes to them. class HasZero (α : Type u) := (zero : α) class HasOne (α : Type u) := (one : α) universes u variable {α : Type u} [HasZero α] [HasOne α] [Add α] [Inhabited α] def bit0 (x : α) : α := x + x def bit1 (x : α) : α := bit0 x + HasOne.one -- TODO: these should be nat-lits, but currently the auto-porter -- is sometimes creating terms with `OfNat.ofNat Nat ...` instead instance instZero2Nat : OfNat α (no_index 0) /- (nat_lit 0) -/ := ⟨HasZero.zero⟩ instance instOne2Nat : OfNat α (no_index 1) /- (nat_lit 1) -/ := ⟨HasOne.one⟩ -- TODO: well-founded partial def nat2bits (n : Nat) : α := if n == 0 then arbitrary else if n == 1 then HasOne.one else if n % 2 == 1 then bit1 (nat2bits (n / 2)) else bit0 (nat2bits (n / 2)) instance instBits2Nat (n : Nat) : OfNat α (no_index (n+1)) /- (n+1) -/ := ⟨nat2bits (n+1)⟩ #print instZero2Nat #print instOne2Nat #print instBits2Nat end Mathlib
2d4747e3299d4a038d7fd37606c03de17d773123
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/equiv/denumerable.lean
32147eef4f0c16478b54b3d02cb044c5393fea0b
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
9,056
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Denumerable (countably infinite) types, as a typeclass extending encodable. This is used to provide explicit encode/decode functions from nat, where the functions are known inverses of each other. -/ import data.equiv.encodable.basic import data.sigma import data.fintype.basic import data.list.min_max open nat /-- A denumerable type is one which is (constructively) bijective with ℕ. Although we already have a name for this property, namely `α ≃ ℕ`, we are here interested in using it as a typeclass. -/ class denumerable (α : Type*) extends encodable α := (decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n) namespace denumerable section variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable theorem decode_is_some (α) [denumerable α] (n : ℕ) : (decode α n).is_some := option.is_some_iff_exists.2 $ (decode_inv n).imp $ λ a, Exists.fst def of_nat (α) [f : denumerable α] (n : ℕ) : α := option.get (decode_is_some α n) @[simp, priority 900] theorem decode_eq_of_nat (α) [denumerable α] (n : ℕ) : decode α n = some (of_nat α n) := option.eq_some_of_is_some _ @[simp] theorem of_nat_of_decode {n b} (h : decode α n = some b) : of_nat α n = b := option.some.inj $ (decode_eq_of_nat _ _).symm.trans h @[simp] theorem encode_of_nat (n) : encode (of_nat α n) = n := let ⟨a, h, e⟩ := decode_inv n in by rwa [of_nat_of_decode h] @[simp] theorem of_nat_encode (a) : of_nat α (encode a) = a := of_nat_of_decode (encodek _) def eqv (α) [denumerable α] : α ≃ ℕ := ⟨encode, of_nat α, of_nat_encode, encode_of_nat⟩ def mk' {α} (e : α ≃ ℕ) : denumerable α := { encode := e, decode := some ∘ e.symm, encodek := λ a, congr_arg some (e.symm_apply_apply _), decode_inv := λ n, ⟨_, rfl, e.apply_symm_apply _⟩ } def of_equiv (α) {β} [denumerable α] (e : β ≃ α) : denumerable β := { decode_inv := λ n, by simp, ..encodable.of_equiv _ e } @[simp] theorem of_equiv_of_nat (α) {β} [denumerable α] (e : β ≃ α) (n) : @of_nat β (of_equiv _ e) n = e.symm (of_nat α n) := by apply of_nat_of_decode; show option.map _ _ = _; simp def equiv₂ (α β) [denumerable α] [denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : denumerable nat := ⟨λ n, ⟨_, rfl, rfl⟩⟩ @[simp] theorem of_nat_nat (n) : of_nat ℕ n = n := rfl instance option : denumerable (option α) := ⟨λ n, by cases n; simp⟩ instance sum : denumerable (α ⊕ β) := ⟨λ n, begin suffices : ∃ a ∈ @decode_sum α β _ _ n, encode_sum a = bit (bodd n) (div2 n), {simpa [bit_decomp]}, simp [decode_sum]; cases bodd n; simp [decode_sum, bit, encode_sum] end⟩ section sigma variables {γ : α → Type*} [∀ a, denumerable (γ a)] instance sigma : denumerable (sigma γ) := ⟨λ n, by simp [decode_sigma]; exact ⟨_, _, ⟨rfl, heq.rfl⟩, by simp⟩⟩ @[simp] theorem sigma_of_nat_val (n : ℕ) : of_nat (sigma γ) n = ⟨of_nat α (unpair n).1, of_nat (γ _) (unpair n).2⟩ := option.some.inj $ by rw [← decode_eq_of_nat, decode_sigma_val]; simp; refl end sigma instance prod : denumerable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem prod_of_nat_val (n : ℕ) : of_nat (α × β) n = (of_nat α (unpair n).1, of_nat β (unpair n).2) := by simp; refl @[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = unpair := by funext; simp instance int : denumerable ℤ := denumerable.mk' equiv.int_equiv_nat instance pnat : denumerable ℕ+ := denumerable.mk' equiv.pnat_equiv_nat instance ulift : denumerable (ulift α) := of_equiv _ equiv.ulift instance plift : denumerable (plift α) := of_equiv _ equiv.plift def pair : α × α ≃ α := equiv₂ _ _ end end denumerable namespace nat.subtype open function encodable variables {s : set ℕ} [infinite s] section classical open_locale classical lemma exists_succ (x : s) : ∃ n, x.1 + n + 1 ∈ s := classical.by_contradiction $ λ h, have ∀ (a : ℕ) (ha : a ∈ s), a < x.val.succ, from λ a ha, lt_of_not_ge (λ hax, h ⟨a - (x.1 + 1), by rwa [add_right_comm, nat.add_sub_cancel' hax]⟩), fintype.false ⟨(((multiset.range x.1.succ).filter (∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), subtype.mk y hy) (by simp [-multiset.range_succ])).to_finset, by simpa [subtype.ext_iff_val, multiset.mem_filter, -multiset.range_succ]⟩ end classical variable [decidable_pred s] def succ (x : s) : s := have h : ∃ m, x.1 + m + 1 ∈ s, from exists_succ x, ⟨x.1 + nat.find h + 1, nat.find_spec h⟩ lemma succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x := have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _, let ⟨k, hk⟩ := nat.exists_eq_add_of_lt h in have nat.find hx ≤ k, from nat.find_min' _ (hk ▸ x.2), show y.1 + nat.find hx + 1 ≤ x.1, by rw hk; exact add_le_add_right (add_le_add_left this _) _ lemma le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y := have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _, show x.1 ≤ y.1 + nat.find hx + 1, from le_of_not_gt $ λ hxy, have y.1 + nat.find hx + 1 ≤ y.1 := h ⟨_, nat.find_spec hx⟩ hxy, not_lt_of_le this $ calc y.1 ≤ y.1 + nat.find hx : le_add_of_nonneg_right (nat.zero_le _) ... < y.1 + nat.find hx + 1 : nat.lt_succ_self _ lemma lt_succ_self (x : s) : x < succ x := calc x.1 ≤ x.1 + _ : le_self_add ... < succ x : nat.lt_succ_self (x.1 + _) lemma lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y := ⟨λ h, le_of_not_gt (λ h', not_le_of_gt h (succ_le_of_lt h')), λ h, lt_of_le_of_lt h (lt_succ_self _)⟩ def of_nat (s : set ℕ) [decidable_pred s] [infinite s] : ℕ → s | 0 := ⊥ | (n+1) := succ (of_nat n) lemma of_nat_surjective_aux : ∀ {x : ℕ} (hx : x ∈ s), ∃ n, of_nat s n = ⟨x, hx⟩ | x := λ hx, let t : list s := ((list.range x).filter (λ y, y ∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), ⟨y, hy⟩) (by simp) in have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩, by simp [list.mem_filter, subtype.ext_iff_val, t]; intros; refl, have wf : ∀ m : s, list.maximum t = m → m.1 < x, from λ m hmax, by simpa [hmt] using list.maximum_mem hmax, begin cases hmax : list.maximum t with m, { exact ⟨0, le_antisymm (@bot_le s _ _) (le_of_not_gt (λ h, list.not_mem_nil (⊥ : s) $ by rw [← list.maximum_eq_none.1 hmax, hmt]; exact h))⟩ }, { cases of_nat_surjective_aux m.2 with a ha, exact ⟨a + 1, le_antisymm (by rw of_nat; exact succ_le_of_lt (by rw ha; exact wf _ hmax)) $ by rw of_nat; exact le_succ_of_forall_lt_le (λ z hz, by rw ha; cases m; exact list.le_maximum_of_mem (hmt.2 hz) hmax)⟩ } end using_well_founded {dec_tac := `[tauto]} lemma of_nat_surjective : surjective (of_nat s) := λ ⟨x, hx⟩, of_nat_surjective_aux hx private def to_fun_aux (x : s) : ℕ := (list.range x).countp s private lemma to_fun_aux_eq (x : s) : to_fun_aux x = ((finset.range x).filter s).card := by rw [to_fun_aux, list.countp_eq_length_filter]; refl open finset private lemma right_inverse_aux : ∀ n, to_fun_aux (of_nat s n) = n | 0 := begin rw [to_fun_aux_eq, card_eq_zero, eq_empty_iff_forall_not_mem], assume n, rw [mem_filter, of_nat, mem_range], assume h, exact not_lt_of_le bot_le (show (⟨n, h.2⟩ : s) < ⊥, from h.1) end | (n+1) := have ih : to_fun_aux (of_nat s n) = n, from right_inverse_aux n, have h₁ : (of_nat s n : ℕ) ∉ (range (of_nat s n)).filter s, by simp, have h₂ : (range (succ (of_nat s n))).filter s = insert (of_nat s n) ((range (of_nat s n)).filter s), begin simp only [finset.ext_iff, mem_insert, mem_range, mem_filter], assume m, exact ⟨λ h, by simp only [h.2, and_true]; exact or.symm (lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)), λ h, h.elim (λ h, h.symm ▸ ⟨lt_succ_self _, subtype.property _⟩) (λ h, ⟨lt_of_le_of_lt (le_of_lt h.1) (lt_succ_self _), h.2⟩)⟩ end, begin clear_aux_decl, simp only [to_fun_aux_eq, of_nat, range_succ] at *, conv {to_rhs, rw [← ih, ← card_insert_of_not_mem h₁, ← h₂] }, end def denumerable (s : set ℕ) [decidable_pred s] [infinite s] : denumerable s := denumerable.of_equiv ℕ { to_fun := to_fun_aux, inv_fun := of_nat s, left_inv := left_inverse_of_surjective_of_right_inverse of_nat_surjective right_inverse_aux, right_inv := right_inverse_aux } end nat.subtype namespace denumerable open encodable def of_encodable_of_infinite (α : Type*) [encodable α] [infinite α] : denumerable α := begin letI := @decidable_range_encode α _; letI : infinite (set.range (@encode α _)) := infinite.of_injective _ (equiv.of_injective _ encode_injective).injective, letI := nat.subtype.denumerable (set.range (@encode α _)), exact denumerable.of_equiv (set.range (@encode α _)) (equiv_range_encode α) end end denumerable
6702f19b10cb9c5998c7ba578287c00030be492e
f3a5af2927397cf346ec0e24312bfff077f00425
/src/mynat/mul.lean
b2b2560aed7908cb90b344ade5ba8b28d6f7f338
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
356
lean
import mynat.add namespace mynat def mul : mynat → mynat → mynat | m zero := zero | m (succ n) := mul m n + m instance : has_mul mynat := ⟨mul⟩ -- notation a * b := mul a b example : (1 : mynat) * 1 = 1 := begin refl end lemma mul_zero (m : mynat) : m * 0 = 0 := rfl lemma mul_succ (m n : mynat) : m * (succ n) = m * n + m := rfl end mynat
196bbfdfbfc0661398ae84887ba8707c95548bfa
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/degree/default_auto.lean
69092f057f111b318ca7a844c9eadd0f07a4beb7
[]
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
160
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.degree.lemmas import Mathlib.PostPort namespace Mathlib end Mathlib
7d6868d5a6dae62766fc9cdfc6288adc61284f3a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_topology/fundamental_groupoid/simply_connected.lean
05e4e9f523fa410fd18c5b262c3b27b9642f18b1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,908
lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import algebraic_topology.fundamental_groupoid.induced_maps import topology.homotopy.contractible import category_theory.punit import algebraic_topology.fundamental_groupoid.punit /-! # Simply connected spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines simply connected spaces. A topological space is simply connected if its fundamental groupoid is equivalent to `unit`. ## Main theorems - `simply_connected_iff_unique_homotopic` - A space is simply connected if and only if it is nonempty and there is a unique path up to homotopy between any two points - `simply_connected_space.of_contractible` - A contractible space is simply connected -/ noncomputable theory open category_theory open continuous_map open_locale continuous_map /-- A simply connected space is one whose fundamental groupoid is equivalent to `discrete unit` -/ class simply_connected_space (X : Type*) [topological_space X] : Prop := (equiv_unit [] : nonempty (fundamental_groupoid X ≌ discrete unit)) lemma simply_connected_def (X : Type*) [topological_space X] : simply_connected_space X ↔ nonempty (fundamental_groupoid X ≌ discrete unit) := ⟨λ h, @simply_connected_space.equiv_unit X _ h, λ h, ⟨h⟩⟩ lemma simply_connected_iff_unique_homotopic (X : Type*) [topological_space X] : simply_connected_space X ↔ (nonempty X) ∧ ∀ (x y : X), nonempty (unique (path.homotopic.quotient x y)) := by { rw [simply_connected_def, equiv_punit_iff_unique], refl, } namespace simply_connected_space variables {X : Type*} [topological_space X] [simply_connected_space X] instance (x y : X) : subsingleton (path.homotopic.quotient x y) := @unique.subsingleton _ (nonempty.some (by { rw simply_connected_iff_unique_homotopic at *, tauto })) local attribute [instance] path.homotopic.setoid @[priority 100] instance : path_connected_space X := let unique_homotopic := (simply_connected_iff_unique_homotopic X).mp infer_instance in { nonempty := unique_homotopic.1, joined := λ x y, ⟨(unique_homotopic.2 x y).some.default.out⟩, } /-- In a simply connected space, any two paths are homotopic -/ lemma paths_homotopic {x y : X} (p₁ p₂ : path x y) : path.homotopic p₁ p₂ := by simpa using @subsingleton.elim (path.homotopic.quotient x y) _ ⟦p₁⟧ ⟦p₂⟧ @[priority 100] instance of_contractible (Y : Type*) [topological_space Y] [contractible_space Y] : simply_connected_space Y := { equiv_unit := let H : Top.of Y ≃ₕ Top.of unit := (contractible_space.hequiv_unit Y).some in ⟨(fundamental_groupoid_functor.equiv_of_homotopy_equiv H).trans fundamental_groupoid.punit_equiv_discrete_punit⟩, } end simply_connected_space local attribute [instance] path.homotopic.setoid /-- A space is simply connected iff it is path connected, and there is at most one path up to homotopy between any two points. -/ lemma simply_connected_iff_paths_homotopic {Y : Type*} [topological_space Y] : simply_connected_space Y ↔ (path_connected_space Y) ∧ (∀ x y : Y, subsingleton (path.homotopic.quotient x y)) := ⟨by { introI, split; apply_instance, }, λ h, begin casesI h, rw simply_connected_iff_unique_homotopic, exact ⟨infer_instance, λ x y, ⟨unique_of_subsingleton ⟦path_connected_space.some_path x y⟧⟩⟩, end⟩ /-- Another version of `simply_connected_iff_paths_homotopic` -/ lemma simply_connected_iff_paths_homotopic' {Y : Type*} [topological_space Y] : simply_connected_space Y ↔ (path_connected_space Y) ∧ (∀ {x y : Y} (p₁ p₂ : path x y), path.homotopic p₁ p₂) := begin convert simply_connected_iff_paths_homotopic, simp [path.homotopic.quotient, setoid.eq_top_iff], refl, end
7198dfd425b5b6189c0b7420d07fd4a8015899c8
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/t4.lean
12ebf8ed6c6ec6ec10e0b29bccdc343a40a8783d
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,192
lean
prelude definition Prop : Type.{1} := Type.{0} constant N : Type.{1} check N constant a : N check a check Prop → Prop constant F.{l} : Type.{l} → Type.{l} check F.{2} universe u check F.{u} constant vec.{l} (A : Type.{l}) (n : N) : Type.{l} constant f (a b : N) : N constant len.{l} (A : Type.{l}) (n : N) (v : vec.{l} A n) : N check f check len.{1} context parameter A : Type parameter B : Prop hypothesis H : B parameter {C : Type} check B -> B check A → A check C end check A -- Error: A is part of the section constant R : Type → Type check R.{1 0} check fun x y : N, x namespace tst constant N : Type.{2} constant M : Type.{2} print raw N -- Two possible interpretations N and tst.N print raw tst.N -- Only one interpretation end tst print raw N -- Only one interpretation namespace foo constant M : Type.{3} print raw M -- Only one interpretation end foo check tst.M check foo.M namespace foo check M end foo check M -- Error print "ok" (* local env = get_env() print("Declarations:") env:for_each_decl(function(d) print(d:name()) end) print("-------------") *) universe l_1 constant T1 : Type -- T1 parameter is going to be called l_2
da10c07ea02be9c20914026a83484a39683e5505
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/char_zero/quotient.lean
0503face396f1c3820095a310c01d70b5f6190d1
[ "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
2,805
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.quotient_group /-! # Lemmas about quotients in characteristic zero -/ variables {R : Type*} [division_ring R] [char_zero R] {p : R} namespace add_subgroup /-- `z • r` is a multiple of `p` iff `r` is `pk/z` above a multiple of `p`, where `0 ≤ k < |z|`. -/ lemma zsmul_mem_zmultiples_iff_exists_sub_div {r : R} {z : ℤ} (hz : z ≠ 0) : z • r ∈ add_subgroup.zmultiples p ↔ ∃ k : fin z.nat_abs, r - (k : ℕ) • (p / z : R) ∈ add_subgroup.zmultiples p:= begin rw [add_subgroup.mem_zmultiples_iff], simp_rw [add_subgroup.mem_zmultiples_iff, div_eq_mul_inv, ←smul_mul_assoc, eq_sub_iff_add_eq], have hz' : (z : R) ≠ 0 := int.cast_ne_zero.mpr hz, conv_rhs { simp only [←(mul_right_injective₀ hz').eq_iff] { single_pass := tt}, }, simp_rw [←zsmul_eq_mul, smul_add, ←mul_smul_comm, zsmul_eq_mul (z : R)⁻¹, mul_inv_cancel hz', mul_one, ←coe_nat_zsmul, smul_smul, ←add_smul], split, { rintro ⟨k, h⟩, simp_rw ← h, refine ⟨⟨(k % z).to_nat, _⟩, k / z, _⟩, { rw [←int.coe_nat_lt, int.to_nat_of_nonneg (int.mod_nonneg _ hz)], exact (int.mod_lt _ hz).trans_eq (int.abs_eq_nat_abs _) }, rw [fin.coe_mk, int.to_nat_of_nonneg (int.mod_nonneg _ hz), int.div_add_mod] }, { rintro ⟨k, n, h⟩, exact ⟨_, h⟩, }, end lemma nsmul_mem_zmultiples_iff_exists_sub_div {r : R} {n : ℕ} (hn : n ≠ 0) : n • r ∈ add_subgroup.zmultiples p ↔ ∃ k : fin n, r - (k : ℕ) • (p / n : R) ∈ add_subgroup.zmultiples p:= begin simp_rw [←coe_nat_zsmul r, zsmul_mem_zmultiples_iff_exists_sub_div (int.coe_nat_ne_zero.mpr hn), int.cast_coe_nat], refl, end end add_subgroup namespace quotient_add_group lemma zmultiples_zsmul_eq_zsmul_iff {ψ θ : R ⧸ add_subgroup.zmultiples p} {z : ℤ} (hz : z ≠ 0) : z • ψ = z • θ ↔ (∃ k : fin z.nat_abs, ψ = θ + (k : ℕ) • (p / z : R)) := begin induction ψ using quotient.induction_on', induction θ using quotient.induction_on', have : (quotient.mk' : R → R ⧸ add_subgroup.zmultiples p) = coe := rfl, simp only [this], simp_rw [←coe_zsmul, ←coe_nsmul, ←coe_add, quotient_add_group.eq_iff_sub_mem, ←smul_sub, ←sub_sub, add_subgroup.zsmul_mem_zmultiples_iff_exists_sub_div hz], end lemma zmultiples_nsmul_eq_nsmul_iff {ψ θ : R ⧸ add_subgroup.zmultiples p} {n : ℕ} (hz : n ≠ 0) : n • ψ = n • θ ↔ (∃ k : fin n, ψ = θ + (k : ℕ) • (p / n : R)) := begin simp_rw [←coe_nat_zsmul ψ, ←coe_nat_zsmul θ, zmultiples_zsmul_eq_zsmul_iff (int.coe_nat_ne_zero.mpr hz), int.cast_coe_nat], refl, end end quotient_add_group
fe33b900e5e8104fe14651136b0e03a6b2e9df3e
c777c32c8e484e195053731103c5e52af26a25d1
/src/set_theory/game/nim.lean
fbbbb91d3abbd3a542582739a47861e67d99cfd0
[ "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
14,487
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Markus Himmel -/ import data.nat.bitwise import set_theory.game.birthday import set_theory.game.impartial /-! # Nim and the Sprague-Grundy theorem This file contains the definition for nim for any ordinal `o`. In the game of `nim o₁` both players may move to `nim o₂` for any `o₂ < o₁`. We also define a Grundy value for an impartial game `G` and prove the Sprague-Grundy theorem, that `G` is equivalent to `nim (grundy_value G)`. Finally, we compute the sum of finite Grundy numbers: if `G` and `H` have Grundy values `n` and `m`, where `n` and `m` are natural numbers, then `G + H` has the Grundy value `n xor m`. ## Implementation details The pen-and-paper definition of nim defines the possible moves of `nim o` to be `set.Iio o`. However, this definition does not work for us because it would make the type of nim `ordinal.{u} → pgame.{u + 1}`, which would make it impossible for us to state the Sprague-Grundy theorem, since that requires the type of `nim` to be `ordinal.{u} → pgame.{u}`. For this reason, we instead use `o.out.α` for the possible moves. You can use `to_left_moves_nim` and `to_right_moves_nim` to convert an ordinal less than `o` into a left or right move of `nim o`, and vice versa. -/ noncomputable theory universe u open_locale pgame namespace pgame /-- The definition of single-heap nim, which can be viewed as a pile of stones where each player can take a positive number of stones from it on their turn. -/ -- Uses `noncomputable!` to avoid `rec_fn_macro only allowed in meta definitions` VM error noncomputable! def nim : ordinal.{u} → pgame.{u} | o₁ := let f := λ o₂, have ordinal.typein o₁.out.r o₂ < o₁ := ordinal.typein_lt_self o₂, nim (ordinal.typein o₁.out.r o₂) in ⟨o₁.out.α, o₁.out.α, f, f⟩ using_well_founded { dec_tac := tactic.assumption } open ordinal lemma nim_def (o : ordinal) : nim o = pgame.mk o.out.α o.out.α (λ o₂, nim (ordinal.typein (<) o₂)) (λ o₂, nim (ordinal.typein (<) o₂)) := by { rw nim, refl } lemma left_moves_nim (o : ordinal) : (nim o).left_moves = o.out.α := by { rw nim_def, refl } lemma right_moves_nim (o : ordinal) : (nim o).right_moves = o.out.α := by { rw nim_def, refl } lemma move_left_nim_heq (o : ordinal) : (nim o).move_left == λ i : o.out.α, nim (typein (<) i) := by { rw nim_def, refl } lemma move_right_nim_heq (o : ordinal) : (nim o).move_right == λ i : o.out.α, nim (typein (<) i) := by { rw nim_def, refl } /-- Turns an ordinal less than `o` into a left move for `nim o` and viceversa. -/ noncomputable def to_left_moves_nim {o : ordinal} : set.Iio o ≃ (nim o).left_moves := (enum_iso_out o).to_equiv.trans (equiv.cast (left_moves_nim o).symm) /-- Turns an ordinal less than `o` into a right move for `nim o` and viceversa. -/ noncomputable def to_right_moves_nim {o : ordinal} : set.Iio o ≃ (nim o).right_moves := (enum_iso_out o).to_equiv.trans (equiv.cast (right_moves_nim o).symm) @[simp] theorem to_left_moves_nim_symm_lt {o : ordinal} (i : (nim o).left_moves) : ↑(to_left_moves_nim.symm i) < o := (to_left_moves_nim.symm i).prop @[simp] theorem to_right_moves_nim_symm_lt {o : ordinal} (i : (nim o).right_moves) : ↑(to_right_moves_nim.symm i) < o := (to_right_moves_nim.symm i).prop @[simp] lemma move_left_nim' {o : ordinal.{u}} (i) : (nim o).move_left i = nim (to_left_moves_nim.symm i).val := (congr_heq (move_left_nim_heq o).symm (cast_heq _ i)).symm lemma move_left_nim {o : ordinal} (i) : (nim o).move_left (to_left_moves_nim i) = nim i := by simp @[simp] lemma move_right_nim' {o : ordinal} (i) : (nim o).move_right i = nim (to_right_moves_nim.symm i).val := (congr_heq (move_right_nim_heq o).symm (cast_heq _ i)).symm lemma move_right_nim {o : ordinal} (i) : (nim o).move_right (to_right_moves_nim i) = nim i := by simp /-- A recursion principle for left moves of a nim game. -/ @[elab_as_eliminator] def left_moves_nim_rec_on {o : ordinal} {P : (nim o).left_moves → Sort*} (i : (nim o).left_moves) (H : ∀ a < o, P $ to_left_moves_nim ⟨a, H⟩) : P i := by { rw ←to_left_moves_nim.apply_symm_apply i, apply H } /-- A recursion principle for right moves of a nim game. -/ @[elab_as_eliminator] def right_moves_nim_rec_on {o : ordinal} {P : (nim o).right_moves → Sort*} (i : (nim o).right_moves) (H : ∀ a < o, P $ to_right_moves_nim ⟨a, H⟩) : P i := by { rw ←to_right_moves_nim.apply_symm_apply i, apply H } instance is_empty_nim_zero_left_moves : is_empty (nim 0).left_moves := by { rw nim_def, exact ordinal.is_empty_out_zero } instance is_empty_nim_zero_right_moves : is_empty (nim 0).right_moves := by { rw nim_def, exact ordinal.is_empty_out_zero } /-- `nim 0` has exactly the same moves as `0`. -/ def nim_zero_relabelling : nim 0 ≡r 0 := relabelling.is_empty _ theorem nim_zero_equiv : nim 0 ≈ 0 := equiv.is_empty _ noncomputable instance unique_nim_one_left_moves : unique (nim 1).left_moves := (equiv.cast $ left_moves_nim 1).unique noncomputable instance unique_nim_one_right_moves : unique (nim 1).right_moves := (equiv.cast $ right_moves_nim 1).unique @[simp] theorem default_nim_one_left_moves_eq : (default : (nim 1).left_moves) = @to_left_moves_nim 1 ⟨0, zero_lt_one⟩ := rfl @[simp] theorem default_nim_one_right_moves_eq : (default : (nim 1).right_moves) = @to_right_moves_nim 1 ⟨0, zero_lt_one⟩ := rfl @[simp] theorem to_left_moves_nim_one_symm (i) : (@to_left_moves_nim 1).symm i = ⟨0, zero_lt_one⟩ := by simp @[simp] theorem to_right_moves_nim_one_symm (i) : (@to_right_moves_nim 1).symm i = ⟨0, zero_lt_one⟩ := by simp theorem nim_one_move_left (x) : (nim 1).move_left x = nim 0 := by simp theorem nim_one_move_right (x) : (nim 1).move_right x = nim 0 := by simp /-- `nim 1` has exactly the same moves as `star`. -/ def nim_one_relabelling : nim 1 ≡r star := begin rw nim_def, refine ⟨_, _, λ i, _, λ j, _⟩, any_goals { dsimp, apply equiv.equiv_of_unique }, all_goals { simp, exact nim_zero_relabelling } end theorem nim_one_equiv : nim 1 ≈ star := nim_one_relabelling.equiv @[simp] lemma nim_birthday (o : ordinal) : (nim o).birthday = o := begin induction o using ordinal.induction with o IH, rw [nim_def, birthday_def], dsimp, rw max_eq_right le_rfl, convert lsub_typein o, exact funext (λ i, IH _ (typein_lt_self i)) end @[simp] lemma neg_nim (o : ordinal) : -nim o = nim o := begin induction o using ordinal.induction with o IH, rw nim_def, dsimp; congr; funext i; exact IH _ (ordinal.typein_lt_self i) end instance nim_impartial (o : ordinal) : impartial (nim o) := begin induction o using ordinal.induction with o IH, rw [impartial_def, neg_nim], refine ⟨equiv_rfl, λ i, _, λ i, _⟩; simpa using IH _ (typein_lt_self _) end lemma nim_fuzzy_zero_of_ne_zero {o : ordinal} (ho : o ≠ 0) : nim o ‖ 0 := begin rw [impartial.fuzzy_zero_iff_lf, nim_def, lf_zero_le], rw ←ordinal.pos_iff_ne_zero at ho, exact ⟨(ordinal.principal_seg_out ho).top, by simp⟩ end @[simp] lemma nim_add_equiv_zero_iff (o₁ o₂ : ordinal) : nim o₁ + nim o₂ ≈ 0 ↔ o₁ = o₂ := begin split, { refine not_imp_not.1 (λ (hne : _ ≠ _), (impartial.not_equiv_zero_iff _).2 _), wlog h : o₁ < o₂, { exact (fuzzy_congr_left add_comm_equiv).1 (this _ _ hne.symm (hne.lt_or_lt.resolve_left h)) }, rw [impartial.fuzzy_zero_iff_gf, zero_lf_le, nim_def o₂], refine ⟨to_left_moves_add (sum.inr _), _⟩, { exact (ordinal.principal_seg_out h).top }, { simpa using (impartial.add_self (nim o₁)).2 } }, { rintro rfl, exact impartial.add_self (nim o₁) } end @[simp] lemma nim_add_fuzzy_zero_iff {o₁ o₂ : ordinal} : nim o₁ + nim o₂ ‖ 0 ↔ o₁ ≠ o₂ := by rw [iff_not_comm, impartial.not_fuzzy_zero_iff, nim_add_equiv_zero_iff] @[simp] lemma nim_equiv_iff_eq {o₁ o₂ : ordinal} : nim o₁ ≈ nim o₂ ↔ o₁ = o₂ := by rw [impartial.equiv_iff_add_equiv_zero, nim_add_equiv_zero_iff] /-- The Grundy value of an impartial game, the ordinal which corresponds to the game of nim that the game is equivalent to -/ noncomputable def grundy_value : Π (G : pgame.{u}), ordinal.{u} | G := ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_eq_mex_left (G : pgame) : grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) := by rw grundy_value /-- The Sprague-Grundy theorem which states that every impartial game is equivalent to a game of nim, namely the game of nim corresponding to the games Grundy value -/ theorem equiv_nim_grundy_value : ∀ (G : pgame.{u}) [G.impartial], G ≈ nim (grundy_value G) | G := begin introI hG, rw [impartial.equiv_iff_add_equiv_zero, ←impartial.forall_left_moves_fuzzy_iff_equiv_zero], intro i, apply left_moves_add_cases i, { intro i₁, rw add_move_left_inl, apply (fuzzy_congr_left (add_congr_left (equiv_nim_grundy_value (G.move_left i₁)).symm)).1, rw nim_add_fuzzy_zero_iff, intro heq, rw [eq_comm, grundy_value_eq_mex_left G] at heq, have h := ordinal.ne_mex _, rw heq at h, exact (h i₁).irrefl }, { intro i₂, rw [add_move_left_inr, ←impartial.exists_left_move_equiv_iff_fuzzy_zero], revert i₂, rw nim_def, intro i₂, have h' : ∃ i : G.left_moves, (grundy_value (G.move_left i)) = ordinal.typein (quotient.out (grundy_value G)).r i₂, { revert i₂, rw grundy_value_eq_mex_left, intros i₂, have hnotin : _ ∉ _ := λ hin, (le_not_le_of_lt (ordinal.typein_lt_self i₂)).2 (cInf_le' hin), simpa using hnotin}, cases h' with i hi, use to_left_moves_add (sum.inl i), rw [add_move_left_inl, move_left_mk], apply (add_congr_left (equiv_nim_grundy_value (G.move_left i))).trans, simpa only [hi] using impartial.add_self (nim (grundy_value (G.move_left i))) } end using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_eq_iff_equiv_nim {G : pgame} [G.impartial] {o : ordinal} : grundy_value G = o ↔ G ≈ nim o := ⟨by { rintro rfl, exact equiv_nim_grundy_value G }, by { intro h, rw ←nim_equiv_iff_eq, exact (equiv_nim_grundy_value G).symm.trans h }⟩ @[simp] lemma nim_grundy_value (o : ordinal.{u}) : grundy_value (nim o) = o := grundy_value_eq_iff_equiv_nim.2 pgame.equiv_rfl lemma grundy_value_eq_iff_equiv (G H : pgame) [G.impartial] [H.impartial] : grundy_value G = grundy_value H ↔ G ≈ H := grundy_value_eq_iff_equiv_nim.trans (equiv_congr_left.1 (equiv_nim_grundy_value H) _).symm @[simp] lemma grundy_value_zero : grundy_value 0 = 0 := grundy_value_eq_iff_equiv_nim.2 nim_zero_equiv.symm lemma grundy_value_iff_equiv_zero (G : pgame) [G.impartial] : grundy_value G = 0 ↔ G ≈ 0 := by rw [←grundy_value_eq_iff_equiv, grundy_value_zero] @[simp] lemma grundy_value_star : grundy_value star = 1 := grundy_value_eq_iff_equiv_nim.2 nim_one_equiv.symm @[simp] lemma grundy_value_neg (G : pgame) [G.impartial] : grundy_value (-G) = grundy_value G := by rw [grundy_value_eq_iff_equiv_nim, neg_equiv_iff, neg_nim, ←grundy_value_eq_iff_equiv_nim] lemma grundy_value_eq_mex_right : ∀ (G : pgame) [G.impartial], grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_right i)) | ⟨l, r, L, R⟩ := begin introI H, rw [←grundy_value_neg, grundy_value_eq_mex_left], congr, ext i, haveI : (R i).impartial := @impartial.move_right_impartial ⟨l, r, L, R⟩ _ i, apply grundy_value_neg end /-- The Grundy value of the sum of two nim games with natural numbers of piles equals their bitwise xor. -/ -- Todo: this actually generalizes to all ordinals, by defining `ordinal.lxor` as the pairwise -- `nat.lxor` of base `ω` Cantor normal forms. @[simp] lemma grundy_value_nim_add_nim (n m : ℕ) : grundy_value (nim.{u} n + nim.{u} m) = nat.lxor n m := begin -- We do strong induction on both variables. induction n using nat.strong_induction_on with n hn generalizing m, induction m using nat.strong_induction_on with m hm, rw grundy_value_eq_mex_left, apply (ordinal.mex_le_of_ne.{u u} (λ i, _)).antisymm (ordinal.le_mex_of_forall (λ ou hu, _)), -- The Grundy value `nat.lxor n m` can't be reached by left moves. { apply left_moves_add_cases i; { -- A left move leaves us with a Grundy value of `nat.lxor k m` for `k < n`, or `nat.lxor n k` -- for `k < m`. refine λ a, left_moves_nim_rec_on a (λ ok hk, _), obtain ⟨k, rfl⟩ := ordinal.lt_omega.1 (hk.trans (ordinal.nat_lt_omega _)), simp only [add_move_left_inl, add_move_left_inr, move_left_nim', equiv.symm_apply_apply], -- The inequality follows from injectivity. rw nat_cast_lt at hk, rw hn _ hk <|> rw hm _ hk, refine λ h, hk.ne _, rw ordinal.nat_cast_inj at h, rwa nat.lxor_left_inj at h <|> rwa nat.lxor_right_inj at h } }, -- Every other smaller Grundy value can be reached by left moves. { -- If `u < nat.lxor m n`, then either `nat.lxor u n < m` or `nat.lxor u m < n`. obtain ⟨u, rfl⟩ := ordinal.lt_omega.1 (hu.trans (ordinal.nat_lt_omega _)), replace hu := ordinal.nat_cast_lt.1 hu, cases nat.lt_lxor_cases hu with h h, -- In the first case, reducing the `m` pile to `nat.lxor u n` gives the desired Grundy value. { refine ⟨to_left_moves_add (sum.inl $ to_left_moves_nim ⟨_, ordinal.nat_cast_lt.2 h⟩), _⟩, simp [nat.lxor_cancel_right, hn _ h] }, -- In the second case, reducing the `n` pile to `nat.lxor u m` gives the desired Grundy value. { refine ⟨to_left_moves_add (sum.inr $ to_left_moves_nim ⟨_, ordinal.nat_cast_lt.2 h⟩), _⟩, have : n.lxor (u.lxor n) = u, rw [nat.lxor_comm u, nat.lxor_cancel_left], simpa [hm _ h] using this } } end lemma nim_add_nim_equiv {n m : ℕ} : nim n + nim m ≈ nim (nat.lxor n m) := by rw [←grundy_value_eq_iff_equiv_nim, grundy_value_nim_add_nim] lemma grundy_value_add (G H : pgame) [G.impartial] [H.impartial] {n m : ℕ} (hG : grundy_value G = n) (hH : grundy_value H = m) : grundy_value (G + H) = nat.lxor n m := begin rw [←nim_grundy_value (nat.lxor n m), grundy_value_eq_iff_equiv], refine equiv.trans _ nim_add_nim_equiv, convert add_congr (equiv_nim_grundy_value G) (equiv_nim_grundy_value H); simp only [hG, hH] end end pgame
c83337d407ff7681ba71011e44f58043d85addd0
c86b74188c4b7a462728b1abd659ab4e5828dd61
/tests/lean/run/meta2.lean
36b85cd110fb33681e0f52a402541ae4c18a7383
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,272
lean
import Lean.Meta open Lean open Lean.Meta -- set_option trace.Meta true --set_option trace.Meta.isDefEq.step false -- set_option trace.Meta.isDefEq.delta false set_option trace.Meta.debug true def print (msg : MessageData) : MetaM Unit := do trace[Meta.debug] msg def checkM (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" def getAssignment (m : Expr) : MetaM Expr := do let v? ← getExprMVarAssignment? m.mvarId!; (match v? with | some v => pure v | none => throwError "metavariable is not assigned") def nat := mkConst `Nat def boolE := mkConst `Bool def succ := mkConst `Nat.succ def zero := mkConst `Nat.zero def add := mkConst `Nat.add def io := mkConst `IO def type := mkSort levelOne def boolFalse := mkConst `Bool.false def boolTrue := mkConst `Bool.true def tst1 : MetaM Unit := do print "----- tst1 -----"; let mvar <- mkFreshExprMVar nat; checkM $ isExprDefEq mvar (mkNatLit 10); checkM $ isExprDefEq mvar (mkNatLit 10); pure () #eval tst1 def tst2 : MetaM Unit := do print "----- tst2 -----"; let mvar <- mkFreshExprMVar nat; checkM $ isExprDefEq (mkApp succ mvar) (mkApp succ (mkNatLit 10)); checkM $ isExprDefEq mvar (mkNatLit 10); pure () #eval tst2 def tst3 : MetaM Unit := do print "----- tst3 -----"; let t := mkLambda `x BinderInfo.default nat $ mkBVar 0; let mvar ← mkFreshExprMVar (mkForall `x BinderInfo.default nat nat); lambdaTelescope t fun xs _ => do let x := xs[0]; checkM $ isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]); pure (); let v ← getAssignment mvar; print v; pure () #eval tst3 def tst4 : MetaM Unit := do print "----- tst4 -----"; let t := mkLambda `x BinderInfo.default nat $ mkBVar 0; lambdaTelescope t fun xs _ => do let x := xs[0]; let mvar ← mkFreshExprMVar (mkForall `x BinderInfo.default nat nat); -- the following `isExprDefEq` fails because `x` is also in the context of `mvar` checkM $ not <$> isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]); checkM $ approxDefEq $ isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]); let v ← getAssignment mvar; print v; pure (); pure () #eval tst4 def mkAppC (c : Name) (xs : Array Expr) : MetaM Expr := do let r ← mkAppM c xs; check r; pure r def mkProd (a b : Expr) : MetaM Expr := mkAppC `Prod #[a, b] def mkPair (a b : Expr) : MetaM Expr := mkAppC `Prod.mk #[a, b] def mkFst (s : Expr) : MetaM Expr := mkAppC `Prod.fst #[s] def mkSnd (s : Expr) : MetaM Expr := mkAppC `Prod.snd #[s] def tst5 : MetaM Unit := do print "----- tst5 -----"; let p₁ ← mkPair (mkNatLit 1) (mkNatLit 2); let x ← mkFst p₁; print x; let v ← whnf x; print v; let v ← withTransparency TransparencyMode.reducible $ whnf x; print v; let x ← mkId x; print x; let prod ← mkProd nat nat; let m ← mkFreshExprMVar prod; let y ← mkFst m; checkM $ isExprDefEq y x; print y; let x ← mkProjection p₁ `fst; print x; let y ← mkProjection p₁ `snd; print y #eval tst5 def tst6 : MetaM Unit := do print "----- tst6 -----"; withLocalDeclD `x nat $ fun x => do let m ← mkFreshExprMVar nat; let t := mkAppN add #[m, mkNatLit 4]; let s := mkAppN add #[x, mkNatLit 3]; checkM $ not <$> isExprDefEq t s; let s := mkAppN add #[x, mkNatLit 6]; checkM $ isExprDefEq t s; let v ← getAssignment m; checkM $ pure $ v == mkAppN add #[x, mkNatLit 2]; print v; let m ← mkFreshExprMVar nat; let t := mkAppN add #[m, mkNatLit 4]; let s := mkNatLit 3; checkM $ not <$> isExprDefEq t s; let s := mkNatLit 10; checkM $ isExprDefEq t s; let v ← getAssignment m; checkM $ pure $ v == mkNatLit 6; print v; pure () #eval tst6 def tst7 : MetaM Unit := do print "----- tst7 -----"; withLocalDeclD `x type $ fun x => do let m1 ← mkFreshExprMVar (← mkArrow type type); let m2 ← mkFreshExprMVar type; let t := mkApp io x; -- we need to use foApprox to solve `?m1 ?m2 =?= IO x` checkM $ not <$> isDefEq (mkApp m1 m2) t; checkM $ approxDefEq $ isDefEq (mkApp m1 m2) t; let v ← getAssignment m1; checkM $ pure $ v == io; let v ← getAssignment m2; checkM $ pure $ v == x; pure () #eval tst7 def tst9 : MetaM Unit := do print "----- tst9 -----"; let env ← getEnv; print (toString (← isReducible `Prod.fst)) print (toString (← isReducible `Add.add)) pure () #eval tst9 def tst10 : MetaM Unit := do print "----- tst10 -----"; let t ← withLocalDeclD `x nat $ fun x => do { let b := mkAppN add #[x, mkAppN add #[mkNatLit 2, mkNatLit 3]]; mkLambdaFVars #[x] b }; print t; let t ← reduce t; print t; pure () #eval tst10 def tst11 : MetaM Unit := do print "----- tst11 -----"; checkM $ isType nat; checkM $ isType (← mkArrow nat nat); checkM $ not <$> isType add; checkM $ not <$> isType (mkNatLit 1); withLocalDeclD `x nat fun x => do checkM $ not <$> isType x; checkM $ not <$> (mkLambdaFVars #[x] x >>= isType); checkM $ not <$> (mkLambdaFVars #[x] nat >>= isType); let t ← mkEq x (mkNatLit 0); let t ← mkForallFVars #[x] t (usedOnly := true); print t; checkM $ isType t; pure (); pure () #eval tst11 def tst12 : MetaM Unit := do print "----- tst12 -----"; withLocalDeclD `x nat $ fun x => do let t ← mkEqRefl x >>= mkLambdaFVars #[x]; print t; let type ← inferType t; print type; isProofQuick t >>= fun b => print (toString b); isProofQuick nat >>= fun b => print (toString b); isProofQuick type >>= fun b => print (toString b); pure (); pure () #eval tst12 def tst13 : MetaM Unit := do print "----- tst13 -----"; let m₁ ← mkFreshExprMVar (← mkArrow type type); let m₂ ← mkFreshExprMVar (mkApp m₁ nat); let t ← mkId m₂; print t; let r ← abstractMVars t; print r.expr; let (_, _, e) ← openAbstractMVarsResult r; print e; pure () def mkDecEq (type : Expr) : MetaM Expr := mkAppC `DecidableEq #[type] def mkStateM (σ : Expr) : MetaM Expr := mkAppC `StateM #[σ] def mkMonad (m : Expr) : MetaM Expr := mkAppC `Monad #[m] def mkMonadState (σ m : Expr) : MetaM Expr := mkAppC `MonadState #[σ, m] def mkAdd (a : Expr) : MetaM Expr := mkAppC `Add #[a] def mkToString (a : Expr) : MetaM Expr := mkAppC `ToString #[a] def tst14 : MetaM Unit := do print "----- tst14 -----"; let stateM ← mkStateM nat; print stateM; let monad ← mkMonad stateM; let globalInsts ← getGlobalInstancesIndex; let insts ← globalInsts.getUnify monad; print (insts.map (·.val)); pure () #eval tst14 def tst15 : MetaM Unit := do print "----- tst15 -----"; let inst ← _root_.mkAdd nat; let r ← synthInstance inst; print r; pure () #eval tst15 def tst16 : MetaM Unit := do print "----- tst16 -----"; let prod ← mkProd nat nat; let inst ← mkToString prod; print inst; let r ← synthInstance inst; print r; pure () #eval tst16 def tst17 : MetaM Unit := do print "----- tst17 -----"; let prod ← mkProd nat nat; let prod ← mkProd boolE prod; let inst ← mkToString prod; print inst; let r ← synthInstance inst; print r; pure () #eval tst17 def tst18 : MetaM Unit := do print "----- tst18 -----"; let decEqNat ← mkDecEq nat; let r ← synthInstance decEqNat; print r; pure () #eval tst18 def tst19 : MetaM Unit := do print "----- tst19 -----"; let stateM ← mkStateM nat; print stateM; let monad ← mkMonad stateM; print monad; let r ← synthInstance monad; print r; pure () #eval tst19 def tst20 : MetaM Unit := do print "----- tst20 -----"; let stateM ← mkStateM nat; print stateM; let monadState ← mkMonadState nat stateM; print monadState; let r ← synthInstance monadState; print r; pure () #eval tst20 def tst21 : MetaM Unit := do print "----- tst21 -----"; withLocalDeclD `x nat $ fun x => do withLocalDeclD `y nat $ fun y => do withLocalDeclD `z nat $ fun z => do let eq₁ ← mkEq x y; let eq₂ ← mkEq y z; withLocalDeclD `h₁ eq₁ $ fun h₁ => do withLocalDeclD `h₂ eq₂ $ fun h₂ => do let h ← mkEqTrans h₁ h₂; let h ← mkEqSymm h; let h ← mkCongrArg succ h; let h₂ ← mkEqRefl succ; let h ← mkCongr h₂ h; let t ← inferType h; check h; print h; print t; let h ← mkCongrFun h₂ x; let t ← inferType h; check h; print t; pure () #eval tst21 def tst22 : MetaM Unit := do print "----- tst22 -----"; withLocalDeclD `x nat $ fun x => do withLocalDeclD `y nat $ fun y => do let t ← mkAppC `Add.add #[x, y]; print t; let t ← mkAppC `Add.add #[y, x]; print t; let t ← mkAppC `ToString.toString #[x]; print t; pure () #eval tst22 def test1 : Nat := (fun x y => x + y) 0 1 def tst23 : MetaM Unit := do print "----- tst23 -----"; let cinfo ← getConstInfo `test1; let v := cinfo.value?.get!; print v; print v.headBeta #eval tst23 def tst26 : MetaM Unit := do print "----- tst26 -----"; let m1 ← mkFreshExprMVar (← mkArrow nat nat); let m2 ← mkFreshExprMVar nat; let m3 ← mkFreshExprMVar nat; checkM $ approxDefEq $ isDefEq (mkApp m1 m2) m3; checkM $ do { let b ← isExprMVarAssigned $ m1.mvarId!; pure (!b) }; checkM $ isExprMVarAssigned $ m3.mvarId!; pure () #eval tst26 section set_option trace.Meta.isDefEq.step true set_option trace.Meta.isDefEq.delta true set_option trace.Meta.isDefEq.assign true def tst27 : MetaM Unit := do print "----- tst27 -----"; let m ← mkFreshExprMVar nat; checkM $ isDefEq (mkNatLit 1) (mkApp (mkConst `Nat.succ) m); pure () #eval tst27 end def tst28 : MetaM Unit := do print "----- tst28 -----"; withLocalDeclD `x nat $ fun x => withLocalDeclD `y nat $ fun y => withLocalDeclD `z nat $ fun z => do let t1 ← mkAppM `Add.add #[x, y]; let t1 ← mkAppM `Add.add #[x, t1]; let t1 ← mkAppM `Add.add #[t1, t1]; let t2 ← mkAppM `Add.add #[z, y]; let t3 ← mkAppM `Eq #[t2, t1]; let t3 ← mkForallFVars #[z] t3; let m ← mkFreshExprMVar nat; let p ← mkAppM `Add.add #[x, m]; print t3; let r ← kabstract t3 p; print r; let p ← mkAppM `Add.add #[x, y]; let r ← kabstract t3 p; print r; pure () #eval tst28 def norm : Level → Level := @Lean.Level.normalize def tst29 : MetaM Unit := do print "----- tst29 -----"; let u := mkLevelParam `u; let v := mkLevelParam `v; let u1 := mkLevelSucc u; let m := mkLevelMax levelOne u1; print (norm m); checkM $ pure $ norm m == u1; let m := mkLevelMax u1 levelOne; print (norm m); checkM $ pure $ norm m == u1; let m := mkLevelMax (mkLevelMax levelOne (mkLevelSucc u1)) (mkLevelSucc levelOne); checkM $ pure $ norm m == mkLevelSucc u1; print m; print (norm m); let m := mkLevelMax (mkLevelMax (mkLevelSucc (mkLevelSucc u1)) (mkLevelSucc u1)) (mkLevelSucc levelOne); print m; print (norm m); checkM $ pure $ norm m == mkLevelSucc (mkLevelSucc u1); let m := mkLevelMax (mkLevelMax (mkLevelSucc v) (mkLevelSucc u1)) (mkLevelSucc levelOne); print m; print (norm m); pure () #eval tst29 def tst30 : MetaM Unit := do print "----- tst30 -----"; let m1 ← mkFreshExprMVar nat; let m2 ← mkFreshExprMVar (← mkArrow nat nat); withLocalDeclD `x nat $ fun x => do let t := mkApp succ $ mkApp m2 x; print t; checkM $ approxDefEq $ isDefEq m1 t; let r ← instantiateMVars m1; print r; let r ← instantiateMVars m2; print r; pure () #eval tst30 def tst31 : MetaM Unit := do print "----- tst31 -----"; let m ← mkFreshExprMVar nat; let t := mkLet `x nat zero m; print t; checkM $ isDefEq t m; pure () def tst32 : MetaM Unit := do print "----- tst32 -----"; withLocalDeclD `a nat $ fun a => do withLocalDeclD `b nat $ fun b => do let aeqb ← mkEq a b; withLocalDeclD `h2 aeqb $ fun h2 => do let t ← mkEq (mkApp2 add a a) a; print t; let motive := mkLambda `x BinderInfo.default nat (mkApp3 (mkConst `Eq [levelOne]) nat (mkApp2 add a (mkBVar 0)) a); withLocalDeclD `h1 t $ fun h1 => do let r ← mkEqNDRec motive h1 h2; print r; let rType ← inferType r >>= whnf; print rType; check r; pure () #eval tst32 def tst33 : MetaM Unit := do print "----- tst33 -----"; withLocalDeclD `a nat $ fun a => do withLocalDeclD `b nat $ fun b => do let aeqb ← mkEq a b; withLocalDeclD `h2 aeqb $ fun h2 => do let t ← mkEq (mkApp2 add a a) a; let motive := mkLambda `x BinderInfo.default nat $ mkLambda `h BinderInfo.default (mkApp3 (mkConst `Eq [levelOne]) nat a (mkBVar 0)) $ (mkApp3 (mkConst `Eq [levelOne]) nat (mkApp2 add a (mkBVar 1)) a); withLocalDeclD `h1 t $ fun h1 => do let r ← mkEqRec motive h1 h2; print r; let rType ← inferType r >>= whnf; print rType; check r; pure () #eval tst33 def tst34 : MetaM Unit := do print "----- tst34 -----"; let type := mkSort levelOne; withLocalDeclD `α type $ fun α => do let m ← mkFreshExprMVar type; let t ← mkLambdaFVars #[α] (← mkArrow m m); print t; pure () #eval tst34 def tst35 : MetaM Unit := do print "----- tst35 -----"; let type := mkSort levelOne; withLocalDeclD `α type $ fun α => do let m1 ← mkFreshExprMVar type; let m2 ← mkFreshExprMVar (← mkArrow nat type); let v := mkLambda `x BinderInfo.default nat m1; assignExprMVar m2.mvarId! v; let w := mkApp m2 zero; let t1 ← mkLambdaFVars #[α] (← mkArrow w w); print t1; let m3 ← mkFreshExprMVar type; let t2 ← mkLambdaFVars #[α] (← mkArrow (mkBVar 0) (mkBVar 1)); print t2; checkM $ isDefEq t1 t2; pure () #eval tst35 #check @Id def tst36 : MetaM Unit := do print "----- tst36 -----"; let type := mkSort levelOne; let m1 ← mkFreshExprMVar (← mkArrow type type); withLocalDeclD `α type $ fun α => do let m2 ← mkFreshExprMVar type; let t ← mkAppM `Id #[m2]; checkM $ approxDefEq $ isDefEq (mkApp m1 α) t; checkM $ approxDefEq $ isDefEq m1 (mkConst `Id [levelZero]); pure () #eval tst36 def tst37 : MetaM Unit := do print "----- tst37 -----"; let m1 ← mkFreshExprMVar (←mkArrow nat (←mkArrow type type)); let m2 ← mkFreshExprMVar (←mkArrow nat type); withLocalDeclD `v nat $ fun v => do let lhs := mkApp2 m1 v (mkApp m2 v); let rhs ← mkAppM `StateM #[nat, nat]; print lhs; print rhs; checkM $ approxDefEq $ isDefEq lhs rhs; pure () #eval tst37 def tst38 : MetaM Unit := do print "----- tst38 -----"; let m1 ← mkFreshExprMVar nat; withLocalDeclD `x nat $ fun x => do let m2 ← mkFreshExprMVar type; withLocalDeclD `y m2 $ fun y => do let m3 ← mkFreshExprMVar (←mkArrow m2 nat); let rhs := mkApp m3 y; checkM $ approxDefEq $ isDefEq m2 nat; print m2; checkM $ getAssignment m2 >>= fun v => pure $ v == nat; checkM $ approxDefEq $ isDefEq m1 rhs; print m2; checkM $ getAssignment m2 >>= fun v => pure $ v == nat; pure () set_option pp.all true set_option trace.Meta.isDefEq.step true set_option trace.Meta.isDefEq.delta true set_option trace.Meta.isDefEq.assign true #eval tst38 def tst39 : MetaM Unit := do print "----- tst39 -----"; withLocalDeclD `α type $ fun α => withLocalDeclD `β type $ fun β => do let p ← mkProd α β; let t ← mkForallFVars #[α, β] p; print t; let e ← instantiateForall t #[nat, boolE]; print e; pure () #eval tst39 def tst40 : MetaM Unit := do print "----- tst40 -----"; withLocalDeclD `α type $ fun α => withLocalDeclD `β type $ fun β => withLocalDeclD `a α $ fun a => withLocalDeclD `b β $ fun b => do let p ← mkProd α β; let t1 ← mkForallFVars #[α, β] p; let t2 ← mkForallFVars #[α, β, a, b] p; print t1; print $ toString $ t1.bindingBody!.hasLooseBVarInExplicitDomain 0 false; print $ toString $ t1.bindingBody!.hasLooseBVarInExplicitDomain 0 true; print $ toString $ t2.bindingBody!.hasLooseBVarInExplicitDomain 0 false; print $ t1.inferImplicit 2 false; checkM $ pure $ ((t1.inferImplicit 2 false).bindingInfo! == BinderInfo.default); checkM $ pure $ ((t1.inferImplicit 2 false).bindingBody!.bindingInfo! == BinderInfo.default); print $ t1.inferImplicit 2 true; checkM $ pure $ ((t1.inferImplicit 2 true).bindingInfo! == BinderInfo.implicit); checkM $ pure $ ((t1.inferImplicit 2 true).bindingBody!.bindingInfo! == BinderInfo.implicit); print t2; print $ t2.inferImplicit 2 false; checkM $ pure $ ((t2.inferImplicit 2 false).bindingInfo! == BinderInfo.implicit); checkM $ pure $ ((t2.inferImplicit 2 false).bindingBody!.bindingInfo! == BinderInfo.implicit); print $ t2.inferImplicit 1 false; checkM $ pure $ ((t2.inferImplicit 1 false).bindingInfo! == BinderInfo.implicit); checkM $ pure $ ((t2.inferImplicit 1 false).bindingBody!.bindingInfo! == BinderInfo.default); pure () #eval tst40 universes u structure A (α : Type u) := (x y : α) structure B (α : Type u) := (z : α) structure C (α : Type u) extends A α, B α := (w : Bool) def mkA (x y : Expr) : MetaM Expr := mkAppC `A.mk #[x, y] def mkB (z : Expr) : MetaM Expr := mkAppC `B.mk #[z] def mkC (x y z w : Expr) : MetaM Expr := do let a ← mkA x y; let b ← mkB z; mkAppC `C.mk #[a, b, w] def tst41 : MetaM Unit := do print "----- tst41 -----"; let c ← mkC (mkNatLit 1) (mkNatLit 2) (mkNatLit 3) boolTrue; print c; let x ← mkProjection c `x; check x; print x; let y ← mkProjection c `y; check y; print y; let z ← mkProjection c `z; check z; print z; let w ← mkProjection c `w; check w; print w; pure () set_option trace.Meta.isDefEq.step false set_option trace.Meta.isDefEq.delta false set_option trace.Meta.isDefEq.assign false #eval tst41 set_option pp.all false def tst42 : MetaM Unit := do print "----- tst42 -----"; let t ← mkListLit nat [mkNatLit 1, mkNatLit 2]; print t; check t; let t ← mkArrayLit nat [mkNatLit 1, mkNatLit 2]; print t; check t; (match t.arrayLit? with | some (_, xs) => do checkM $ pure $ xs.length == 2; (match (xs.get! 0).natLit?, (xs.get! 1).natLit? with | some 1, some 2 => pure () | _, _ => throwError "nat lits expected") | none => throwError "array lit expected") #eval tst42
c335be26fda2bf01fbad605baf0fefd3b20297d1
6d50885e7b3f72447a03f21d5268d6af87c0a404
/instructor-notes/2019.10.14.prop_logic/prop_logic.lean
5f75943ac9859c8fb8505f98e25391bf4df1527a
[]
no_license
kevinsullivan/uva-cs-dm-s20-old
583c756cded281fcee7f1afc42cb3e08f89c2493
797672cb0ffae6a42a3518c9225d5807191fd113
refs/heads/master
1,607,500,914,982
1,578,752,991,000
1,578,752,991,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,767
lean
namespace prop_logic /- *** SYNTAX *** -/ inductive var : Type | mkVar : ℕ → var inductive unOp : Type | notOp inductive binOp : Type | andOp | orOp | xorOp | implOp | iffOp inductive pExp : Type | litExp : bool → pExp | varExp : var → pExp | unOpExp : unOp → pExp → pExp | binOpExp : binOp → pExp → pExp → pExp open var open pExp open unOp open binOp -- Shorthand notations def pTrue := litExp tt def pFalse := litExp ff def pNot := unOpExp notOp def pAnd := binOpExp andOp def pOr := binOpExp orOp def pXor := binOpExp xorOp def pImpl := binOpExp implOp def pIff := binOpExp iffOp -- conventional notation notation e1 ∧ e2 := pAnd e1 e2 notation e1 ∨ e2 := pOr e1 e2 notation ¬ e := pNot e notation e1 ⇒ e2 := pImpl e1 e2 notation e1 ⊕ e2 := pXor e1 e2 notation e1 ↔ e2 := pIff e1 e2 /- *** SEMANTICS *** -/ def interpUnOp : unOp → (bool → bool) | notOp := bnot def bimpl : bool → bool → bool | tt ff := ff | _ _ := tt def biff : bool → bool → bool | tt tt := tt | ff ff := tt | _ _ := ff def interpBinOp : binOp → (bool → bool → bool) | andOp := band | orOp := bor | xorOp := bxor | implOp := bimpl | iffOp := biff /- Given a pExp and an interpretation for the variables, evaluate the pExp to determine its Boolean truth value. -/ 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) def num_var_mentions : pExp → ℕ | (litExp b) := 0 | (varExp v) := 1 | (unOpExp op e) := num_var_mentions e | (binOpExp op e1 e2) := num_var_mentions e1 + num_var_mentions e2 end prop_logic
49fc0c84f195243f41f5245e4417a70196e58ed0
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/bundled.lean
540a3f2b1a0536289f1e362180af41636caea487
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,037
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Bundled structures -/ import algebra.group structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) attribute Group.carrier [coercion] attribute Group.struct [instance] structure CommGroup := (carrier : Type) (struct : comm_group carrier) attribute CommGroup.carrier [coercion] attribute CommGroup.struct [instance] structure AddSemigroup := (carrier : Type) (struct : add_semigroup carrier) attribute AddSemigroup.carrier [coercion] attribute AddSemigroup.struct [instance] structure AddCommSemigroup := (carrier : Type) (struct : add_comm_semigroup carrier) attribute AddCommSemigroup.carrier [coercion] attribute AddCommSemigroup.struct [instance] structure AddMonoid := (carrier : Type) (struct : add_monoid carrier) attribute AddMonoid.carrier [coercion] attribute AddMonoid.struct [instance] structure AddCommMonoid := (carrier : Type) (struct : add_comm_monoid carrier) attribute AddCommMonoid.carrier [coercion] attribute AddCommMonoid.struct [instance] structure AddGroup := (carrier : Type) (struct : add_group carrier) attribute AddGroup.carrier [coercion] attribute AddGroup.struct [instance] structure AddCommGroup := (carrier : Type) (struct : add_comm_group carrier) attribute AddCommGroup.carrier [coercion] attribute AddCommGroup.struct [instance]
04c0a40b7dbb675741066a539ec554c802a00040
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/nat/find.lean
bba8d29a59a43063f5a0ec94ae0248d6fbc1702b
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
3,596
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 Choice function for decidable predicates on natural numbers. This module provides the following two declarations: choose {p : nat → Prop} [d : decidable_pred p] : (∃ x, p x) → nat choose_spec {p : nat → Prop} [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) -/ import data.nat.basic data.nat.order open nat subtype decidable well_founded namespace nat section find_x parameter {p : nat → Prop} private definition lbp (x : nat) : Prop := ∀ y, y < x → ¬ p y private lemma lbp_zero : lbp 0 := λ y h, absurd h (not_lt_zero y) private lemma lbp_succ {x : nat} : lbp x → ¬ p x → lbp (succ x) := λ lx npx y yltsx, or.elim (eq_or_lt_of_le (le_of_succ_le_succ yltsx)) (suppose y = x, by substvars; assumption) (suppose y < x, lx y this) private definition gtb (a b : nat) : Prop := a > b ∧ lbp a local infix ` ≺ `:50 := gtb private lemma acc_of_px {x : nat} : p x → acc gtb x := assume h, acc.intro x (λ (y : nat) (l : y ≺ x), obtain (h₁ : y > x) (h₂ : ∀ a, a < y → ¬ p a), from l, absurd h (h₂ x h₁)) private lemma acc_of_acc_succ {x : nat} : acc gtb (succ x) → acc gtb x := assume h, acc.intro x (λ (y : nat) (l : y ≺ x), by_cases (suppose y = succ x, by substvars; assumption) (suppose y ≠ succ x, have x < y, from and.elim_left l, have succ x < y, from lt_of_le_of_ne this (ne.symm `y ≠ succ x`), acc.inv h (and.intro this (and.elim_right l)))) private lemma acc_of_px_of_gt {x y : nat} : p x → y > x → acc gtb y := assume px ygtx, acc.intro y (λ (z : nat) (l : z ≺ y), obtain (zgty : z > y) (h : ∀ a, a < z → ¬ p a), from l, absurd px (h x (lt.trans ygtx zgty))) private lemma acc_of_acc_of_lt : ∀ {x y : nat}, acc gtb x → y < x → acc gtb y | 0 y a0 ylt0 := absurd ylt0 !not_lt_zero | (succ x) y asx yltsx := assert acc gtb x, from acc_of_acc_succ asx, by_cases (suppose y = x, by substvars; assumption) (suppose y ≠ x, acc_of_acc_of_lt `acc gtb x` (lt_of_le_of_ne (le_of_lt_succ yltsx) this)) parameter (ex : ∃ a, p a) parameter [dp : decidable_pred p] include dp private lemma acc_of_ex (x : nat) : acc gtb x := obtain (w : nat) (pw : p w), from ex, lt.by_cases (suppose x < w, acc_of_acc_of_lt (acc_of_px pw) this) (suppose x = w, by subst x; exact (acc_of_px pw)) (suppose x > w, acc_of_px_of_gt pw this) private lemma wf_gtb : well_founded gtb := well_founded.intro acc_of_ex private definition find.F (x : nat) : (Π x₁, x₁ ≺ x → lbp x₁ → {a : nat | p a}) → lbp x → {a : nat | p a} := match x with | 0 := λ f l0, by_cases (λ p0 : p 0, tag 0 p0) (suppose ¬ p 0, have lbp 1, from lbp_succ l0 this, have 1 ≺ 0, from and.intro (lt.base 0) `lbp 1`, f 1 `1 ≺ 0` `lbp 1`) | (succ n) := λ f lsn, by_cases (suppose p (succ n), tag (succ n) this) (suppose ¬ p (succ n), have lss : lbp (succ (succ n)), from lbp_succ lsn this, have succ (succ n) ≺ succ n, from and.intro (lt.base (succ n)) lss, f (succ (succ n)) this lss) end private definition find_x : {x : nat | p x} := @fix _ _ _ wf_gtb find.F 0 lbp_zero end find_x protected definition find {p : nat → Prop} [d : decidable_pred p] : (∃ x, p x) → nat := assume h, elt_of (find_x h) protected theorem find_spec {p : nat → Prop} [d : decidable_pred p] (ex : ∃ x, p x) : p (nat.find ex) := has_property (find_x ex) end nat
518b4b20f97a157a6087d51e7ec9516e9c506385
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/algebra/ordered_group.hlean
696cca23a367c35b121cab92966a56a9afc8f366
[ "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
21,549
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Partially ordered additive groups, modeled on Isabelle's library. We could refine the structures, but we would have to declare more inheritance paths. Ported from the standard library -/ import .order .group open core namespace algebra variable {A : Type} /- partially ordered monoids, such as the natural numbers -/ structure ordered_cancel_comm_monoid [class] (A : Type) extends add_comm_monoid A, add_left_cancel_semigroup A, add_right_cancel_semigroup A, order_pair A := (add_le_add_left : Πa b, le a b → Πc, le (add c a) (add c b)) (le_of_add_le_add_left : Πa b c, le (add a b) (add a c) → le b c) section variables [s : ordered_cancel_comm_monoid A] variables {a b c d e : A} include s definition add_le_add_left (H : a ≤ b) (c : A) : c + a ≤ c + b := !ordered_cancel_comm_monoid.add_le_add_left H c definition add_le_add_right (H : a ≤ b) (c : A) : a + c ≤ b + c := (add.comm c a) ▸ (add.comm c b) ▸ (add_le_add_left H c) definition add_le_add (Hab : a ≤ b) (Hcd : c ≤ d) : a + c ≤ b + d := le.trans (add_le_add_right Hab c) (add_le_add_left Hcd b) definition add_lt_add_left (H : a < b) (c : A) : c + a < c + b := have H1 : c + a ≤ c + b, from add_le_add_left (le_of_lt H) c, have H2 : c + a ≠ c + b, from take H3 : c + a = c + b, have H4 : a = b, from add.left_cancel H3, ne_of_lt H H4, lt_of_le_of_ne H1 H2 definition add_lt_add_right (H : a < b) (c : A) : a + c < b + c := begin rewrite [add.comm, {b + _}add.comm], exact (add_lt_add_left H c) end definition le_add_of_nonneg_right (H : b ≥ 0) : a ≤ a + b := begin have H1 : a + b ≥ a + 0, from add_le_add_left H a, rewrite add_zero at H1, exact H1 end definition le_add_of_nonneg_left (H : b ≥ 0) : a ≤ b + a := begin have H1 : 0 + a ≤ b + a, from add_le_add_right H a, rewrite zero_add at H1, exact H1 end definition add_lt_add (Hab : a < b) (Hcd : c < d) : a + c < b + d := lt.trans (add_lt_add_right Hab c) (add_lt_add_left Hcd b) definition add_lt_add_of_le_of_lt (Hab : a ≤ b) (Hcd : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right Hab c) (add_lt_add_left Hcd b) definition add_lt_add_of_lt_of_le (Hab : a < b) (Hcd : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right Hab c) (add_le_add_left Hcd b) definition lt_add_of_pos_right (H : b > 0) : a < a + b := !add_zero ▸ add_lt_add_left H a definition lt_add_of_pos_left (H : b > 0) : a < b + a := !zero_add ▸ add_lt_add_right H a -- here we start using le_of_add_le_add_left. definition le_of_add_le_add_left (H : a + b ≤ a + c) : b ≤ c := !ordered_cancel_comm_monoid.le_of_add_le_add_left H definition le_of_add_le_add_right (H : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rewrite [add.comm, {b + _}add.comm], exact H end) definition lt_of_add_lt_add_left (H : a + b < a + c) : b < c := have H1 : b ≤ c, from le_of_add_le_add_left (le_of_lt H), have H2 : b ≠ c, from assume H3 : b = c, lt.irrefl _ (H3 ▸ H), lt_of_le_of_ne H1 H2 definition lt_of_add_lt_add_right (H : a + b < c + b) : a < c := lt_of_add_lt_add_left ((add.comm a b) ▸ (add.comm c b) ▸ H) definition add_le_add_left_iff (a b c : A) : a + b ≤ a + c ↔ b ≤ c := iff.intro le_of_add_le_add_left (assume H, add_le_add_left H _) definition add_le_add_right_iff (a b c : A) : a + b ≤ c + b ↔ a ≤ c := iff.intro le_of_add_le_add_right (assume H, add_le_add_right H _) definition add_lt_add_left_iff (a b c : A) : a + b < a + c ↔ b < c := iff.intro lt_of_add_lt_add_left (assume H, add_lt_add_left H _) definition add_lt_add_right_iff (a b c : A) : a + b < c + b ↔ a < c := iff.intro lt_of_add_lt_add_right (assume H, add_lt_add_right H _) -- here we start using properties of zero. definition add_nonneg (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a + b := !zero_add ▸ (add_le_add Ha Hb) definition add_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a + b := !zero_add ▸ (add_lt_add Ha Hb) definition add_pos_of_pos_of_nonneg (Ha : 0 < a) (Hb : 0 ≤ b) : 0 < a + b := !zero_add ▸ (add_lt_add_of_lt_of_le Ha Hb) definition add_pos_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 < a + b := !zero_add ▸ (add_lt_add_of_le_of_lt Ha Hb) definition add_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : a + b ≤ 0 := !zero_add ▸ (add_le_add Ha Hb) definition add_neg (Ha : a < 0) (Hb : b < 0) : a + b < 0 := !zero_add ▸ (add_lt_add Ha Hb) definition add_neg_of_neg_of_nonpos (Ha : a < 0) (Hb : b ≤ 0) : a + b < 0 := !zero_add ▸ (add_lt_add_of_lt_of_le Ha Hb) definition add_neg_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : a + b < 0 := !zero_add ▸ (add_lt_add_of_le_of_lt Ha Hb) -- TODO: add nonpos version (will be easier with simplifier) definition add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg (Ha : 0 ≤ a) (Hb : 0 ≤ b) : a + b = 0 ↔ a = 0 × b = 0 := iff.intro (assume Hab : a + b = 0, have Ha' : a ≤ 0, from calc a = a + 0 : by rewrite add_zero ... ≤ a + b : add_le_add_left Hb ... = 0 : Hab, have Haz : a = 0, from le.antisymm Ha' Ha, have Hb' : b ≤ 0, from calc b = 0 + b : by rewrite zero_add ... ≤ a + b : add_le_add_right Ha ... = 0 : Hab, have Hbz : b = 0, from le.antisymm Hb' Hb, pair Haz Hbz) (assume Hab : a = 0 × b = 0, match Hab with | pair Ha' Hb' := by rewrite [Ha', Hb', add_zero] end) definition le_add_of_nonneg_of_le (Ha : 0 ≤ a) (Hbc : b ≤ c) : b ≤ a + c := !zero_add ▸ add_le_add Ha Hbc definition le_add_of_le_of_nonneg (Hbc : b ≤ c) (Ha : 0 ≤ a) : b ≤ c + a := !add_zero ▸ add_le_add Hbc Ha definition lt_add_of_pos_of_le (Ha : 0 < a) (Hbc : b ≤ c) : b < a + c := !zero_add ▸ add_lt_add_of_lt_of_le Ha Hbc definition lt_add_of_le_of_pos (Hbc : b ≤ c) (Ha : 0 < a) : b < c + a := !add_zero ▸ add_lt_add_of_le_of_lt Hbc Ha definition add_le_of_nonpos_of_le (Ha : a ≤ 0) (Hbc : b ≤ c) : a + b ≤ c := !zero_add ▸ add_le_add Ha Hbc definition add_le_of_le_of_nonpos (Hbc : b ≤ c) (Ha : a ≤ 0) : b + a ≤ c := !add_zero ▸ add_le_add Hbc Ha definition add_lt_of_neg_of_le (Ha : a < 0) (Hbc : b ≤ c) : a + b < c := !zero_add ▸ add_lt_add_of_lt_of_le Ha Hbc definition add_lt_of_le_of_neg (Hbc : b ≤ c) (Ha : a < 0) : b + a < c := !add_zero ▸ add_lt_add_of_le_of_lt Hbc Ha definition lt_add_of_nonneg_of_lt (Ha : 0 ≤ a) (Hbc : b < c) : b < a + c := !zero_add ▸ add_lt_add_of_le_of_lt Ha Hbc definition lt_add_of_lt_of_nonneg (Hbc : b < c) (Ha : 0 ≤ a) : b < c + a := !add_zero ▸ add_lt_add_of_lt_of_le Hbc Ha definition lt_add_of_pos_of_lt (Ha : 0 < a) (Hbc : b < c) : b < a + c := !zero_add ▸ add_lt_add Ha Hbc definition lt_add_of_lt_of_pos (Hbc : b < c) (Ha : 0 < a) : b < c + a := !add_zero ▸ add_lt_add Hbc Ha definition add_lt_of_nonpos_of_lt (Ha : a ≤ 0) (Hbc : b < c) : a + b < c := !zero_add ▸ add_lt_add_of_le_of_lt Ha Hbc definition add_lt_of_lt_of_nonpos (Hbc : b < c) (Ha : a ≤ 0) : b + a < c := !add_zero ▸ add_lt_add_of_lt_of_le Hbc Ha definition add_lt_of_neg_of_lt (Ha : a < 0) (Hbc : b < c) : a + b < c := !zero_add ▸ add_lt_add Ha Hbc definition add_lt_of_lt_of_neg (Hbc : b < c) (Ha : a < 0) : b + a < c := !add_zero ▸ add_lt_add Hbc Ha end -- TODO: add properties of max and min /- partially ordered groups -/ structure ordered_comm_group [class] (A : Type) extends add_comm_group A, order_pair A := (add_le_add_left : Πa b, le a b → Πc, le (add c a) (add c b)) definition ordered_comm_group.le_of_add_le_add_left [s : ordered_comm_group A] {a b c : A} (H : a + b ≤ a + c) : b ≤ c := assert H' : -a + (a + b) ≤ -a + (a + c), from ordered_comm_group.add_le_add_left _ _ H _, by rewrite *neg_add_cancel_left at H'; exact H' definition ordered_comm_group.to_ordered_cancel_comm_monoid [instance] [coercion] [reducible] [s : ordered_comm_group A] : ordered_cancel_comm_monoid A := ⦃ ordered_cancel_comm_monoid, s, add_left_cancel := @add.left_cancel A s, add_right_cancel := @add.right_cancel A s, le_of_add_le_add_left := @ordered_comm_group.le_of_add_le_add_left A s ⦄ section variables [s : ordered_comm_group A] (a b c d e : A) include s definition neg_le_neg {a b : A} (H : a ≤ b) : -b ≤ -a := have H1 : 0 ≤ -a + b, from !add.left_inv ▸ !(add_le_add_left H), !add_neg_cancel_right ▸ !zero_add ▸ add_le_add_right H1 (-b) definition le_of_neg_le_neg {a b : A} (H : -b ≤ -a) : a ≤ b := neg_neg a ▸ neg_neg b ▸ neg_le_neg H definition neg_le_neg_iff_le : -a ≤ -b ↔ b ≤ a := iff.intro le_of_neg_le_neg neg_le_neg definition nonneg_of_neg_nonpos {a : A} (H : -a ≤ 0) : 0 ≤ a := le_of_neg_le_neg (neg_zero⁻¹ ▸ H) definition neg_nonpos_of_nonneg {a : A} (H : 0 ≤ a) : -a ≤ 0 := neg_zero ▸ neg_le_neg H definition neg_nonpos_iff_nonneg : -a ≤ 0 ↔ 0 ≤ a := iff.intro nonneg_of_neg_nonpos neg_nonpos_of_nonneg definition nonpos_of_neg_nonneg {a : A} (H : 0 ≤ -a) : a ≤ 0 := le_of_neg_le_neg (neg_zero⁻¹ ▸ H) definition neg_nonneg_of_nonpos {a : A} (H : a ≤ 0) : 0 ≤ -a := neg_zero ▸ neg_le_neg H definition neg_nonneg_iff_nonpos : 0 ≤ -a ↔ a ≤ 0 := iff.intro nonpos_of_neg_nonneg neg_nonneg_of_nonpos definition neg_lt_neg {a b : A} (H : a < b) : -b < -a := have H1 : 0 < -a + b, from !add.left_inv ▸ !(add_lt_add_left H), !add_neg_cancel_right ▸ !zero_add ▸ add_lt_add_right H1 (-b) definition lt_of_neg_lt_neg {a b : A} (H : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg H definition neg_lt_neg_iff_lt : -a < -b ↔ b < a := iff.intro lt_of_neg_lt_neg neg_lt_neg definition pos_of_neg_neg {a : A} (H : -a < 0) : 0 < a := lt_of_neg_lt_neg (neg_zero⁻¹ ▸ H) definition neg_neg_of_pos {a : A} (H : 0 < a) : -a < 0 := neg_zero ▸ neg_lt_neg H definition neg_neg_iff_pos : -a < 0 ↔ 0 < a := iff.intro pos_of_neg_neg neg_neg_of_pos definition neg_of_neg_pos {a : A} (H : 0 < -a) : a < 0 := lt_of_neg_lt_neg (neg_zero⁻¹ ▸ H) definition neg_pos_of_neg {a : A} (H : a < 0) : 0 < -a := neg_zero ▸ neg_lt_neg H definition neg_pos_iff_neg : 0 < -a ↔ a < 0 := iff.intro neg_of_neg_pos neg_pos_of_neg definition le_neg_iff_le_neg : a ≤ -b ↔ b ≤ -a := !neg_neg ▸ !neg_le_neg_iff_le definition neg_le_iff_neg_le : -a ≤ b ↔ -b ≤ a := !neg_neg ▸ !neg_le_neg_iff_le definition lt_neg_iff_lt_neg : a < -b ↔ b < -a := !neg_neg ▸ !neg_lt_neg_iff_lt definition neg_lt_iff_neg_lt : -a < b ↔ -b < a := !neg_neg ▸ !neg_lt_neg_iff_lt definition sub_nonneg_iff_le : 0 ≤ a - b ↔ b ≤ a := !sub_self ▸ !add_le_add_right_iff definition sub_nonpos_iff_le : a - b ≤ 0 ↔ a ≤ b := !sub_self ▸ !add_le_add_right_iff definition sub_pos_iff_lt : 0 < a - b ↔ b < a := !sub_self ▸ !add_lt_add_right_iff definition sub_neg_iff_lt : a - b < 0 ↔ a < b := !sub_self ▸ !add_lt_add_right_iff definition add_le_iff_le_neg_add : a + b ≤ c ↔ b ≤ -a + c := have H: a + b ≤ c ↔ -a + (a + b) ≤ -a + c, from iff.symm (!add_le_add_left_iff), !neg_add_cancel_left ▸ H definition add_le_iff_le_sub_left : a + b ≤ c ↔ b ≤ c - a := by rewrite [sub_eq_add_neg, {c+_}add.comm]; apply add_le_iff_le_neg_add definition add_le_iff_le_sub_right : a + b ≤ c ↔ a ≤ c - b := have H: a + b ≤ c ↔ a + b - b ≤ c - b, from iff.symm (!add_le_add_right_iff), !add_neg_cancel_right ▸ H definition le_add_iff_neg_add_le : a ≤ b + c ↔ -b + a ≤ c := assert H: a ≤ b + c ↔ -b + a ≤ -b + (b + c), from iff.symm (!add_le_add_left_iff), by rewrite neg_add_cancel_left at H; exact H definition le_add_iff_sub_left_le : a ≤ b + c ↔ a - b ≤ c := by rewrite [sub_eq_add_neg, {a+_}add.comm]; apply le_add_iff_neg_add_le definition le_add_iff_sub_right_le : a ≤ b + c ↔ a - c ≤ b := assert H: a ≤ b + c ↔ a - c ≤ b + c - c, from iff.symm (!add_le_add_right_iff), by rewrite add_neg_cancel_right at H; exact H definition add_lt_iff_lt_neg_add_left : a + b < c ↔ b < -a + c := assert H: a + b < c ↔ -a + (a + b) < -a + c, from iff.symm (!add_lt_add_left_iff), begin rewrite neg_add_cancel_left at H, exact H end definition add_lt_iff_lt_neg_add_right : a + b < c ↔ a < -b + c := by rewrite add.comm; apply add_lt_iff_lt_neg_add_left definition add_lt_iff_lt_sub_left : a + b < c ↔ b < c - a := begin rewrite [sub_eq_add_neg, {c+_}add.comm], apply add_lt_iff_lt_neg_add_left end definition add_lt_add_iff_lt_sub_right : a + b < c ↔ a < c - b := assert H: a + b < c ↔ a + b - b < c - b, from iff.symm (!add_lt_add_right_iff), by rewrite add_neg_cancel_right at H; exact H definition lt_add_iff_neg_add_lt_left : a < b + c ↔ -b + a < c := assert H: a < b + c ↔ -b + a < -b + (b + c), from iff.symm (!add_lt_add_left_iff), by rewrite neg_add_cancel_left at H; exact H definition lt_add_iff_neg_add_lt_right : a < b + c ↔ -c + a < b := by rewrite add.comm; apply lt_add_iff_neg_add_lt_left definition lt_add_iff_sub_lt_left : a < b + c ↔ a - b < c := by rewrite [sub_eq_add_neg, {a + _}add.comm]; apply lt_add_iff_neg_add_lt_left definition lt_add_iff_sub_lt_right : a < b + c ↔ a - c < b := by rewrite add.comm; apply lt_add_iff_sub_lt_left -- TODO: the Isabelle library has varations on a + b ≤ b ↔ a ≤ 0 definition le_iff_le_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a ≤ b ↔ c ≤ d := calc a ≤ b ↔ a - b ≤ 0 : iff.symm (sub_nonpos_iff_le a b) ... = (c - d ≤ 0) : by rewrite H ... ↔ c ≤ d : sub_nonpos_iff_le c d definition lt_iff_lt_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a < b ↔ c < d := calc a < b ↔ a - b < 0 : iff.symm (sub_neg_iff_lt a b) ... = (c - d < 0) : by rewrite H ... ↔ c < d : sub_neg_iff_lt c d definition sub_le_sub_left {a b : A} (H : a ≤ b) (c : A) : c - b ≤ c - a := add_le_add_left (neg_le_neg H) c definition sub_le_sub_right {a b : A} (H : a ≤ b) (c : A) : a - c ≤ b - c := add_le_add_right H (-c) definition sub_le_sub {a b c d : A} (Hab : a ≤ b) (Hcd : c ≤ d) : a - d ≤ b - c := add_le_add Hab (neg_le_neg Hcd) definition sub_lt_sub_left {a b : A} (H : a < b) (c : A) : c - b < c - a := add_lt_add_left (neg_lt_neg H) c definition sub_lt_sub_right {a b : A} (H : a < b) (c : A) : a - c < b - c := add_lt_add_right H (-c) definition sub_lt_sub {a b c d : A} (Hab : a < b) (Hcd : c < d) : a - d < b - c := add_lt_add Hab (neg_lt_neg Hcd) definition sub_lt_sub_of_le_of_lt {a b c d : A} (Hab : a ≤ b) (Hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt Hab (neg_lt_neg Hcd) definition sub_lt_sub_of_lt_of_le {a b c d : A} (Hab : a < b) (Hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le Hab (neg_le_neg Hcd) definition sub_le_self (a : A) {b : A} (H : b ≥ 0) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg H) ... = a : by rewrite add_zero definition sub_lt_self (a : A) {b : A} (H : b > 0) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos H) ... = a : by rewrite add_zero end structure decidable_linear_ordered_comm_group [class] (A : Type) extends ordered_comm_group A, decidable_linear_order A section variables [s : decidable_linear_ordered_comm_group A] variables {a b c d e : A} include s definition eq_zero_of_neg_eq (H : -a = a) : a = 0 := lt.by_cases (assume H1 : a < 0, have H2: a > 0, from H ▸ neg_pos_of_neg H1, absurd H1 (lt.asymm H2)) (assume H1 : a = 0, H1) (assume H1 : a > 0, have H2: a < 0, from H ▸ neg_neg_of_pos H1, absurd H1 (lt.asymm H2)) definition abs (a : A) : A := if 0 ≤ a then a else -a definition abs_of_nonneg (H : a ≥ 0) : abs a = a := if_pos H definition abs_of_pos (H : a > 0) : abs a = a := if_pos (le_of_lt H) definition abs_of_neg (H : a < 0) : abs a = -a := if_neg (not_le_of_lt H) definition abs_zero : abs 0 = (0:A) := abs_of_nonneg (le.refl _) definition abs_of_nonpos (H : a ≤ 0) : abs a = -a := decidable.by_cases (assume H1 : a = 0, by rewrite [H1, abs_zero, neg_zero]) (assume H1 : a ≠ 0, have H2 : a < 0, from lt_of_le_of_ne H H1, abs_of_neg H2) definition abs_neg (a : A) : abs (-a) = abs a := sum.rec_on (le.total 0 a) (assume H1 : 0 ≤ a, by rewrite [abs_of_nonpos (neg_nonpos_of_nonneg H1), neg_neg, abs_of_nonneg H1]) (assume H1 : a ≤ 0, by rewrite [abs_of_nonneg (neg_nonneg_of_nonpos H1), abs_of_nonpos H1]) definition abs_nonneg (a : A) : abs a ≥ 0 := sum.rec_on (le.total 0 a) (assume H : 0 ≤ a, by rewrite (abs_of_nonneg H); exact H) (assume H : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos H ... = abs a : abs_of_nonpos H) definition abs_abs (a : A) : abs (abs a) = abs a := abs_of_nonneg !abs_nonneg definition le_abs_self (a : A) : a ≤ abs a := sum.rec_on (le.total 0 a) (assume H : 0 ≤ a, abs_of_nonneg H ▸ !le.refl) (assume H : a ≤ 0, le.trans H !abs_nonneg) definition neg_le_abs_self (a : A) : -a ≤ abs a := !abs_neg ▸ !le_abs_self definition eq_zero_of_abs_eq_zero (H : abs a = 0) : a = 0 := have H1 : a ≤ 0, from H ▸ le_abs_self a, have H2 : -a ≤ 0, from H ▸ abs_neg a ▸ le_abs_self (-a), le.antisymm H1 (nonneg_of_neg_nonpos H2) definition abs_eq_zero_iff_eq_zero (a : A) : abs a = 0 ↔ a = 0 := iff.intro eq_zero_of_abs_eq_zero (assume H, ap abs H ⬝ !abs_zero) definition abs_pos_of_pos (H : a > 0) : abs a > 0 := by rewrite (abs_of_pos H); exact H definition abs_pos_of_neg (H : a < 0) : abs a > 0 := !abs_neg ▸ abs_pos_of_pos (neg_pos_of_neg H) definition abs_pos_of_ne_zero (H : a ≠ 0) : abs a > 0 := sum.rec_on (lt_or_gt_of_ne H) abs_pos_of_neg abs_pos_of_pos definition abs_sub (a b : A) : abs (a - b) = abs (b - a) := by rewrite [-neg_sub, abs_neg] definition abs.by_cases {P : A → Type} {a : A} (H1 : P a) (H2 : P (-a)) : P (abs a) := sum.rec_on (le.total 0 a) (assume H : 0 ≤ a, (abs_of_nonneg H)⁻¹ ▸ H1) (assume H : a ≤ 0, (abs_of_nonpos H)⁻¹ ▸ H2) definition abs_le_of_le_of_neg_le (H1 : a ≤ b) (H2 : -a ≤ b) : abs a ≤ b := abs.by_cases H1 H2 definition abs_lt_of_lt_of_neg_lt (H1 : a < b) (H2 : -a < b) : abs a < b := abs.by_cases H1 H2 -- the triangle inequality section private lemma aux1 {a b : A} (H1 : a + b ≥ 0) (H2 : a ≥ 0) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume H3 : b ≥ 0, calc abs (a + b) ≤ abs (a + b) : le.refl ... = a + b : by rewrite (abs_of_nonneg H1) ... = abs a + b : by rewrite (abs_of_nonneg H2) ... = abs a + abs b : by rewrite (abs_of_nonneg H3)) (assume H3 : ¬ b ≥ 0, assert H4 : b ≤ 0, from le_of_lt (lt_of_not_le H3), calc abs (a + b) = a + b : by rewrite (abs_of_nonneg H1) ... = abs a + b : by rewrite (abs_of_nonneg H2) ... ≤ abs a + 0 : add_le_add_left H4 ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos H4) ... = abs a + abs b : by rewrite (abs_of_nonpos H4)) private lemma aux2 {a b : A} (H1 : a + b ≥ 0) : abs (a + b) ≤ abs a + abs b := sum.rec_on (le.total b 0) (assume H2 : b ≤ 0, have H3 : ¬ a < 0, from assume H4 : a < 0, have H5 : a + b < 0, from !add_zero ▸ add_lt_add_of_lt_of_le H4 H2, not_lt_of_le H1 H5, aux1 H1 (le_of_not_lt H3)) (assume H2 : 0 ≤ b, begin have H3 : abs (b + a) ≤ abs b + abs a, begin rewrite add.comm at H1, exact aux1 H1 H2 end, rewrite [add.comm, {abs a + _}add.comm], exact H3 end) definition abs_add_le_abs_add_abs (a b : A) : abs (a + b) ≤ abs a + abs b := sum.rec_on (le.total 0 (a + b)) (assume H2 : 0 ≤ a + b, aux2 H2) (assume H2 : a + b ≤ 0, assert H3 : -a + -b = -(a + b), by rewrite neg_add, assert H4 : -(a + b) ≥ 0, from iff.mp' (neg_nonneg_iff_nonpos (a+b)) H2, have H5 : -a + -b ≥ 0, begin rewrite -H3 at H4, exact H4 end, calc abs (a + b) = abs (-a + -b) : by rewrite [-abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 H5 ... = abs a + abs b : by rewrite *abs_neg) end definition abs_sub_abs_le_abs_sub (a b : A) : abs a - abs b ≤ abs (a - b) := have H1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rewrite sub_add_cancel ... = abs (a - b + b) : by rewrite sub_add_cancel ... ≤ abs (a - b) + abs b : abs_add_le_abs_add_abs, algebra.le_of_add_le_add_right H1 end end algebra
630105d052a1284d225ee8e35705d66474bd3937
1437b3495ef9020d5413178aa33c0a625f15f15f
/category_theory/examples/rings.lean
d604b650e114b566eae8edcd3168e54989f8b9d0
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,084
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl Introduce CommRing -- the category of commutative rings. Currently only the basic setup. -/ import category_theory.examples.monoids import category_theory.fully_faithful import algebra.ring universes u v open category_theory namespace category_theory.examples /-- The category of rings. -/ @[reducible] def Ring : Type (u+1) := bundled ring instance (x : Ring) : ring x := x.str instance concrete_is_ring_hom : concrete_category @is_ring_hom := ⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩ instance Ring_hom_is_ring_hom {R S : Ring} (f : R ⟶ S) : is_ring_hom (f : R → S) := f.2 /-- The category of commutative rings. -/ @[reducible] def CommRing : Type (u+1) := bundled comm_ring instance (x : CommRing) : comm_ring x := x.str -- Here we don't use the `concrete` machinery, -- because it would require introducing a useless synonym for `is_ring_hom`. instance : category CommRing := { hom := λ R S, { f : R → S // is_ring_hom f }, id := λ R, ⟨ id, by resetI; apply_instance ⟩, comp := λ R S T g h, ⟨ h.1 ∘ g.1, begin haveI := g.2, haveI := h.2, apply_instance end ⟩ } instance CommRing_hom_coe {R S : CommRing} : has_coe_to_fun (R ⟶ S) := { F := λ f, R → S, coe := λ f, f.1 } @[simp] lemma CommRing_hom_coe_app {R S : CommRing} (f : R ⟶ S) (r : R) : f r = f.val r := rfl instance CommRing_hom_is_ring_hom {R S : CommRing} (f : R ⟶ S) : is_ring_hom (f : R → S) := f.2 namespace CommRing /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ def forget_to_CommMon : CommRing ⥤ CommMon := { obj := λ X, { α := X.1, str := by apply_instance }, map := λ X Y f, ⟨ f, by apply_instance ⟩ } instance : faithful (forget_to_CommMon) := {} example : faithful (forget_to_CommMon ⋙ CommMon.forget_to_Mon) := by apply_instance end CommRing end category_theory.examples
2c11d3650621e4580dfc008a07381ff73a6f595a
4efff1f47634ff19e2f786deadd394270a59ecd2
/archive/100-theorems-list/83_friendship_graphs.lean
3436361f82e42b1297c8dea2b0b18c9434f9ba4c
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
13,897
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark, Kyle Miller. -/ import combinatorics.adj_matrix import linear_algebra.char_poly.coeff import data.int.modeq import data.zmod.basic import tactic /-! # The Friendship Theorem ## Definitions and Statement - A `friendship` graph is one in which any two distinct vertices have exactly one neighbor in common - A `politician`, at least in the context of this problem, is a vertex in a graph which is adjacent to every other vertex. - The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a politician. ## Proof outline The proof revolves around the theory of adjacency matrices, although some steps could equivalently be phrased in terms of counting walks. - Assume `G` is a finite friendship graph. - First we show that any two nonadjacent vertices have the same degree - Assume for contradiction that `G` does not have a politician. - Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`. - Show that `G` has `d ^ 2 - d + 1` vertices. - By casework, show that if `d = 0, 1, 2`, then `G` has a politician. - If `3 ≤ d`, let `p` be a prime factor of `d - 1`. - If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`. - This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`. ## References - [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos] - [C. Huneke, *The Friendship Theorem*][huneke2002] -/ open_locale classical big_operators noncomputable theory open finset simple_graph matrix universes u v variables {V : Type u} {R : Type v} [semiring R] section friendship_def variables (G : simple_graph V) /-- This is the set of all vertices mutually adjacent to a pair of vertices. -/ def common_friends [fintype V] (v w : V) : finset V := G.neighbor_finset v ∩ G.neighbor_finset w /-- This property of a graph is the hypothesis of the friendship theorem: every pair of nonadjacent vertices has exactly one common friend, a vertex to which both are adjacent. -/ def friendship [fintype V] : Prop := ∀ ⦃v w : V⦄, v ≠ w → (common_friends G v w).card = 1 /-- A politician is a vertex that is adjacent to all other vertices. -/ def exists_politician : Prop := ∃ (v : V), ∀ (w : V), v ≠ w → G.adj v w lemma mem_common_friends [fintype V] {v w : V} {a : V} : a ∈ common_friends G v w ↔ G.adj v a ∧ G.adj w a := by simp [common_friends] end friendship_def variables [fintype V] [inhabited V] {G : simple_graph V} {d : ℕ} (hG : friendship G) include hG namespace friendship variables (R) /-- One characterization of a friendship graph is that there is exactly one walk of length 2 between distinct vertices. These walks are counted in off-diagonal entries of the square of the adjacency matrix, so for a friendship graph, those entries are all 1. -/ theorem adj_matrix_sq_of_ne {v w : V} (hvw : v ≠ w) : ((G.adj_matrix R) ^ 2) v w = 1 := begin rw [pow_two, ← nat.cast_one, ← hG hvw], simp [common_friends, neighbor_finset_eq_filter, finset.filter_filter, finset.filter_inter], end /-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices. We use it to show that nonadjacent vertices have equal degrees. -/ lemma adj_matrix_pow_three_of_not_adj {v w : V} (non_adj : ¬ G.adj v w) : ((G.adj_matrix R) ^ 3) v w = degree G v := begin rw [pow_succ, mul_eq_mul, adj_matrix_mul_apply, degree, card_eq_sum_ones, sum_nat_cast], apply sum_congr rfl, intros x hx, rw [adj_matrix_sq_of_ne _ hG, nat.cast_one], rintro ⟨rfl⟩, rw mem_neighbor_finset at hx, apply non_adj hx, end variable {R} /-- As `v` and `w` not being adjacent implies `degree G v = ((G.adj_matrix R) ^ 3) v w` and `degree G w = ((G.adj_matrix R) ^ 3) v w`, the degrees are equal if `((G.adj_matrix R) ^ 3) v w = ((G.adj_matrix R) ^ 3) w v` This is true as the adjacency matrix is symmetric. -/ lemma degree_eq_of_not_adj {v w : V} (hvw : ¬ G.adj v w) : degree G v = degree G w := begin rw [← nat.cast_id (G.degree v), ← nat.cast_id (G.degree w), ← adj_matrix_pow_three_of_not_adj ℕ hG hvw, ← adj_matrix_pow_three_of_not_adj ℕ hG (λ h, hvw (G.sym h))], conv_lhs {rw ← transpose_adj_matrix}, simp only [pow_succ, pow_two, mul_eq_mul, ← transpose_mul, transpose_apply], simp only [← mul_eq_mul, mul_assoc], end /-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree, and if there isn't a politician, we can show this for adjacent vertices by finding a vertex neither is adjacent to, and then using transitivity. -/ theorem is_regular_of_not_exists_politician (hG' : ¬exists_politician G) : ∃ (d : ℕ), G.is_regular_of_degree d := begin have v := arbitrary V, use G.degree v, intro x, by_cases hvx : G.adj v x, swap, { exact eq.symm (degree_eq_of_not_adj hG hvx), }, dunfold exists_politician at hG', push_neg at hG', rcases hG' v with ⟨w, hvw', hvw⟩, rcases hG' x with ⟨y, hxy', hxy⟩, by_cases hxw : G.adj x w, swap, { rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG hxw }, rw degree_eq_of_not_adj hG hxy, by_cases hvy : G.adj v y, swap, { apply eq.symm (degree_eq_of_not_adj hG hvy) }, rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG, intro hcontra, rcases finset.card_eq_one.mp (hG hvw') with ⟨a, h⟩, have hx : x ∈ common_friends G v w := (mem_common_friends G).mpr ⟨hvx, G.sym hxw⟩, have hy : y ∈ common_friends G v w := (mem_common_friends G).mpr ⟨hvy, G.sym hcontra⟩, rw [h, mem_singleton] at hx hy, apply hxy', rw [hy, hx], end /-- Let `A` be the adjacency matrix of a graph `G`. If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1. If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`. Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/ theorem adj_matrix_sq_of_regular (hd : G.is_regular_of_degree d) : ((G.adj_matrix R) ^ 2) = λ v w, if v = w then d else 1 := begin ext v w, by_cases h : v = w, { rw [h, pow_two, mul_eq_mul, adj_matrix_mul_self_apply_self, hd], simp, }, { rw [adj_matrix_sq_of_ne R hG h, if_neg h], }, end /-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute the eigenvalue to be `d * d`, or as `d + (fintype.card V - 1)`, so those quantities must be equal. This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/ lemma card_of_regular (hd : G.is_regular_of_degree d) : d + (fintype.card V - 1) = d * d := begin let v := arbitrary V, transitivity ((G.adj_matrix ℕ) ^ 2).mul_vec (λ _, 1) v, { rw [adj_matrix_sq_of_regular hG hd, mul_vec, dot_product, ← insert_erase (mem_univ v)], simp only [sum_insert, mul_one, if_true, nat.cast_id, eq_self_iff_true, mem_erase, not_true, ne.def, not_false_iff, add_right_inj, false_and], rw [finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one], refl, intros x hx, simp [(ne_of_mem_erase hx).symm], }, { rw [pow_two, mul_eq_mul, ← mul_vec_mul_vec], simp [adj_matrix_mul_vec_const_apply_of_regular hd, neighbor_finset, card_neighbor_set_eq_degree, hd v], } end /-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a factor `p ∣ d-1`. -/ lemma card_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (fintype.card V : zmod p) = 1 := begin have hpos : 0 < (fintype.card V), { rw fintype.card_pos_iff, apply_instance, }, rw [← nat.succ_pred_eq_of_pos hpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], have h := congr_arg (λ n, (↑n : zmod p)) (card_of_regular hG hd), revert h, simp [dmod], end lemma adj_matrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) ^ 2 = λ _ _, 1 := by simp [adj_matrix_sq_of_regular hG hd, dmod] lemma adj_matrix_sq_mul_const_one_of_regular (hd : G.is_regular_of_degree d) : (G.adj_matrix R) * (λ _ _, 1) = λ _ _, d := by { ext x, simp [← hd x, degree] } lemma adj_matrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) * (λ _ _, 1) = λ _ _, 1 := by rw [adj_matrix_sq_mul_const_one_of_regular hG hd, dmod] /-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/ lemma adj_matrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) {k : ℕ} (hk : 2 ≤ k) : (G.adj_matrix (zmod p)) ^ k = λ _ _, 1 := begin iterate 2 {cases k with k, { exfalso, linarith, }, }, induction k with k hind, apply adj_matrix_sq_mod_p_of_regular hG dmod hd, rw pow_succ, have h2 : 2 ≤ k.succ.succ := by omega, rw hind h2, apply adj_matrix_mul_const_one_mod_p_of_regular hG dmod hd, end /-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`. Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1 mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original adjacency matrix, which is 0, a contradiction. -/ lemma false_of_three_le_degree (hd : G.is_regular_of_degree d) (h : 3 ≤ d) : false := begin -- get a prime factor of d - 1 let p : ℕ := (d - 1).min_fac, have p_dvd_d_pred := (zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mpr (d - 1).min_fac_dvd, have dpos : 0 < d := by linarith, have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast, haveI : fact p.prime := nat.min_fac_prime (by linarith), have hp2 : 2 ≤ p, { apply nat.prime.two_le, assumption }, have dmod : (d : zmod p) = 1, { rw [← nat.succ_pred_eq_of_pos dpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], apply p_dvd_d_pred, }, have Vmod := card_mod_p_of_regular hG dmod hd, -- now we reduce to a trace calculation have := zmod.trace_pow_card (G.adj_matrix (zmod p)), contrapose! this, clear this, -- the trace is 0 mod p when computed one way rw [trace_adj_matrix, zero_pow], -- but the trace is 1 mod p when computed the other way rw adj_matrix_pow_mod_p_of_regular hG dmod hd hp2, swap, { apply nat.prime.pos, assumption, }, { dunfold fintype.card at Vmod, simp only [matrix.trace, diag_apply, mul_one, nsmul_eq_mul, linear_map.coe_mk, sum_const], rw [Vmod, ← nat.cast_one, zmod.nat_coe_zmod_eq_zero_iff_dvd, nat.dvd_one, nat.min_fac_eq_one_iff], linarith, }, end /-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is trivially a politician. -/ lemma exists_politician_of_degree_le_one (hd : G.is_regular_of_degree d) (hd1 : d ≤ 1) : exists_politician G := begin have sq : d * d = d := by { interval_cases d; norm_num }, have h := card_of_regular hG hd, rw sq at h, have : fintype.card V ≤ 1, { cases fintype.card V with n, { exact zero_le _, }, { have : n = 0, { rw [nat.succ_sub_succ_eq_sub, nat.sub_zero] at h, linarith }, subst n, } }, use arbitrary V, intros w h, exfalso, apply h, apply fintype.card_le_one_iff.mp this, end /-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph, and all the vertices are politicians. -/ lemma neighbor_finset_eq_of_degree_eq_two (hd : G.is_regular_of_degree 2) (v : V) : G.neighbor_finset v = finset.univ.erase v := begin apply finset.eq_of_subset_of_card_le, { rw finset.subset_iff, intro x, rw [mem_neighbor_finset, finset.mem_erase], exact λ h, ⟨ne.symm (G.ne_of_adj h), finset.mem_univ _⟩ }, convert_to 2 ≤ _, convert_to _ = fintype.card V - 1, { have hfr:= card_of_regular hG hd, linarith }, { exact finset.card_erase_of_mem (finset.mem_univ _), }, { dsimp [is_regular_of_degree, degree] at hd, rw hd, } end lemma exists_politician_of_degree_eq_two (hd : G.is_regular_of_degree 2) : exists_politician G := begin have v := arbitrary V, use v, intros w hvw, rw [← mem_neighbor_finset, neighbor_finset_eq_of_degree_eq_two hG hd v, finset.mem_erase], exact ⟨ne.symm hvw, finset.mem_univ _⟩, end lemma exists_politician_of_degree_le_two (hd : G.is_regular_of_degree d) (h : d ≤ 2) : exists_politician G := begin interval_cases d, iterate 2 { apply exists_politician_of_degree_le_one hG hd, norm_num }, { exact exists_politician_of_degree_eq_two hG hd }, end end friendship /-- We wish to show that a friendship graph has a politician (a vertex adjacent to all others). We proceed by contradiction, and assume the graph has no politician. We have already proven that a friendship graph with no politician is `d`-regular for some `d`, and now we do casework on `d`. If the degree is at most 2, we observe by casework that it has a politician anyway. If the degree is at least 3, the graph cannot exist. -/ theorem friendship_theorem : exists_politician G := begin by_contradiction npG, rcases hG.is_regular_of_not_exists_politician npG with ⟨d, dreg⟩, have h : d ≤ 2 ∨ 3 ≤ d := by omega, cases h with dle2 dge3, { refine npG (hG.exists_politician_of_degree_le_two dreg dle2) }, { exact hG.false_of_three_le_degree dreg dge3 }, end
fca8adb0440d73a7f705dc1aa6a53d45e0ac9186
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/assignments/assignment_6/assignment_6.lean
1b2bd2adec3dd53e300607ec132ac8f9dfa3924a
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
11,851
lean
import inClassNotes.typeclasses.functor import inClassNotes.typeclasses.algebra open alg /- Copy this file to where you want to work on it and then adjust the imports accordingly. Work through the file following directions as indicated. Turn in your completed file on Collab. -/ universe u universe v /- 1. We've imported our definitions from our class on basic algebraic structures, such as monoid and group. Go learn what an algebraic *ring* is, define a typeclass that expresses its definition, and define an instance that expresses the claim that the integers (ℤ or *int* in Lean) is a ring. You may "stub out" the required proofs with *sorry*. -/ class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) class ring (α : Type u) extends add_comm_group α, mul_monoid α, distrib α #check ring instance ring_Z: ring ℤ:= ⟨sorry, sorry⟩ open alg set_option old_structure_cmd true class has_ring (α : Type u) extends alg.add_comm_group α, mul_monoid α := (dist_left : ∀ (a b c : α), mul_groupoid.a_mul a (add_groupoid.a_add b c) = add_groupoid.a_add (mul_groupoid.a_mul a b) (mul_groupoid.a_mul a c)) (dist_right : ∀ (a b c : α), mul_groupoid.a_mul (add_groupoid.a_add b c) a = add_groupoid.a_add (mul_groupoid.a_mul b a) (mul_groupoid.a_mul c a)) #check has_ring axioms (T : Type) (t_add : T → T → T) (t_mul : T → T → T) /- 2. Go learn what an algebraic *field* is, then define a typeclass to formalize its definition, and finally define two instances that express the claims that the rational numbers (ℚ) and the real numbers (ℝ) are both fields. Again you may (and should) stub out the proof fields in your instances using sorry. -/ set_option old_structure_cmd true class mul_comm_semigroup (α : Type u) extends mul_semigroup α := (mul_comm : ∀ a b : α, a * b = b * a) class comm_ring (α : Type u) extends ring α, mul_comm_semigroup α class field (α : Type u) extends comm_ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : α)⁻¹ = 0) instance field_R: field ℝ:= ⟨sorry, sorry, sorry⟩ instance field_Q: field ℚ:= ⟨sorry, sorry, sorry⟩ /- 3. Graduate students required. Undergrads extra credit. Go figure out what an algebraic module is and write a typeclass to specify it formally. Create an instance to implement the typeclass for the integers (ℤ not ℕ). Stub out the proofs. In lieu of a formal proof, present a *brief informal* (in English) argument to convince your instructor that the integers really do form a module under the usual arithmetic operators. -/ class add_comm_semigroup (α : Type u) extends add_semigroup α := (add_comm : ∀ a b : α, a + b = b + a) class add_comm_monoid (M : Type u) extends add_monoid M, add_comm_semigroup M class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) class mul_action (α : Type u) (β : Type v) [mul_monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) * b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) * b = x * y * b) class distrib_mul_action (α : Type u) (β : Type v) [mul_monoid α] [add_monoid β] extends mul_action α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : α), r • (0 : β) = 0) class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends distrib_mul_action α β := (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (zero_smul : ∀x : β, (0 : α) • x = 0) abbreviation module (α : Type u)(β: Type v) [ring α] [add_comm_group β] := semimodule α β instance module_R_M: module ℤ ℤ:= ⟨sorry, sorry, sorry⟩ /- 4. The set of (our representations of) natural numbers is defined inductively. Here's how they are defined, copied straight from Lean's library. inductive nat | zero : nat | succ (n : nat) : nat Complete the following function definitions for natural number addition, multiplication, and exponentiation. Write your own functions here without using Lean's implementations (i.e., don't use nat.mul, *, etc). You may not use + except as a shorthand for using the nat.succ constructor to add one. If you need to do addition of something other than one, use your own add function. Similarly, if you need to multiply, using your mul function. -/ def add : nat → nat → nat | 0 m := m | (n' + 1) m := (add n' m) + 1 def mul : nat → nat → nat | 0 m := 0 | (n' + 1) m := add (mul n' m) m -- first arg raised to second def exp : nat → nat → nat | n 0 := 1 | n (m'+1) := mul n (exp n m') #eval exp 2 10 -- expect 1024 /- 5. Many computations can be expressed as compositions of map and fold (also sometimes called reduce). For example, you can compute the length of a list by mapping each element to the number, 1, and by the folding the list under natural number addition. A slightly more interesting function counts the number of elements in a list that satisfy some predicate (specified by a boolean-returning function). A. Write a function, mul_map_reduce, that takes (1) a function, f : α → β, where β must be a monoid; and (2) a list, l, of objects of type α; and that then uses f to map l to a list of objects of a type, β, and that then does a fold on the list to reduce it to a final value of type β. Be sure to use a typeclass instance in specifying the type of your function to ensure that the only types that can serve as values of β have monoid structures. Use both our mul_monoid_foldr and fmap functions to implement your solution. -/ -- Your answer here -- instance has_one_nat : alg.has_one nat := ⟨ 1 ⟩ -- instance mul_groupoid_nat : mul_groupoid nat := ⟨ nat.mul ⟩ -- instance mul_semigroup_nat : mul_semigroup nat := ⟨ _ ⟩ -- instance mul_monoid_nat : mul_monoid nat := ⟨ _ , _ ⟩ def mul_map_reduce {α β: Type} [mul_monoid β] (f: α → β) (l: list α) : β := mul_monoid_foldr (fmap f l) #check @mul_map_reduce #check @mul_monoid_foldr /- B. Complete the given application of mul_map_reduce with a lambda expression to compute the product of the non-zero values in the list [1,0,2,0,3,0,4]. -/ #eval mul_map_reduce (fun x, if x=0 then 1 else x ) [1,0,2,0,3,0,4] -- expect 24 /- 6. Here you practice with type families. A. Define a family of types, each of which is index by two natural numbers, such that each type is inhabited if and only if the two natural numbers are equal. You may call your type family nat_eql. Use implicit args when it makes the use of your type family easier. -/ inductive nat_eql: nat → nat → Type | zeros_equal : nat_eql 0 0 <<<<<<< HEAD | n_succ_m_succ_equal : Π {n m : nat}, (nat_eql n m) --- | n'+1 m'+1 := (nat_eql n' m') ======= | n_succ_m_succ_equal : Π {n m : nat}, nat_eql n m → nat_eql (n+1) (m+1) >>>>>>> upstream/master /- B. Now either complete the following programs or argue informally (and briefly) why that won't be possible. -/ open nat_eql <<<<<<< HEAD #check nat_eql ======= def eq_0_0 : nat_eql 0 0 := zeros_equal def eq_0_1 : nat_eql 0 1 := _ def eq_1_1 : nat_eql 1 1 := n_succ_m_succ_equal eq_0_0 def eq_2_2 : nat_eql 2 2 := n_succ_m_succ_equal (n_succ_m_succ_equal eq_0_0) >>>>>>> upstream/master def eq_0_0 : nat_eql 0 0 := zeros_equal def eq_0_1 : nat_eql 0 1 := n_succ_m_succ_equal def eq_1_1 : nat_eql 1 1 := n_succ_m_succ_equal def eq_2_2 : nat_eql 2 2 := n_succ_m_succ_equal /- C. The apply tactic in Lean's tactic language let's you build the term you need by applying an already defined function. Moreover, you can leave holes (underscores) for the arguments and those holes then become subgoals. In this way, using tactics allows you to build a solution using interactive, top-down, type-guided, aka structured, programming! Show that eq_2_2 is inhabited using Lean's tactic language. We get you started. Hint: remember the "exact" tactic. Hint: Think *top down*. Write a single, simple expression that provides a complete solution *except* for the holes that remain to be filled. Then recursively "fill the holes". Continue until you're done. Voila! -/ def eq_10_10 : nat_eql 10 10 := begin apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, apply n_succ_m_succ_equal, exact eq_0_0, end /- In Lean, "repeat" is a tactic that takes another tactic as an argument (enclosed in curly braces), applies it repeatedly until it fails, and leaves you in the resulting tactic state. Use the repeat tactic to show that "nat_eql 500 500" is inhabited. If you get a deterministic timeout, pick smaller numbers, such as 100 and 100. It's ok with us. -/ def eq_500_500 : nat_eql 500 500 := begin repeat {apply n_succ_m_succ_equal}, exact eq_0_0, end <<<<<<< HEAD -- def band_tactic: bool → bool → bool := -- begin -- assume x y, -- cases x, -- exact ff, -- cases y, -- exact ff, -- exact tt, -- end -- #eval band_tactic tt ff ======= #reduce eq_500_500 >>>>>>> upstream/master /- 7. Typeclasses and instances are used in Lean to implement *coercions*, also known as type casts. As in Java, C++, and many other languages, coercions are automatically applied conversions of values of one type, α, to values of another type, β, so that that values of type α can be used where values of type β are needed. For example, in many languages you may use an integer wherever a Boolean value is expected. The conversion is typically from zero to false and from any non-zero value to true. Here's the has_coe (has coercion) typeclass as defined in Lean's libraries. As you can see, a coercion is really just a function, coe, from one type to another, associated with the pair of those two types. class has_coe (a : Sort u) (b : Sort v) := (coe : a → b) A. We provide a simple function, needs_bool, that takes a bool value and just returns it. Your job is to allow this function to be applied to any nat value by defining a new coercion from nat to bool. First define a function, say nat_to_bool, that converts any nat, n, to a bool, by the rule that zero goes to false and any other nat goes to tt. Then define an instance of the has_coe typeclass to enable coercions from nat to bool. You should call it nat_to_bool_coe. When you're done the test cases below should work. -/ def nat_to_bool : nat → bool | 0 := ff | _ := tt instance nat_to_bool_coe : has_coe nat bool := ⟨ nat_to_bool ⟩ def needs_bool : bool → bool := λ b, b -- Test cases #eval needs_bool (1:nat) -- expect tt #eval needs_bool (0:nat) -- expect ff /- Not only are coercions, when available, applied automatically, but, with certain limitations, Lean can also chain them automatically. Define a second coercion called string_to_nat_coe, from string to nat, that will coerce any string to its length as a nat (using the string.length function). When you're done, you should be able to apply the needs_bool function to any string, where the empty string returns ff and non-empty, tt. -/ instance string_to_nat_coe : has_coe string nat := ⟨ λ (s : string), s.length ⟩ -- Test cases #eval needs_bool "Hello" -- expect tt #eval needs_bool "" -- expect ff /- Do you see how the coercions are being chained, aka, composed, automatically? -/ -- Good job! example : 1 = 1 := begin exact (eq.refl 1), end example : 1 = 1 := begin apply eq.refl _, end
08f0c2b481cc386afa4f735e534ea59a2d34e936
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/finsupp_vector_space.lean
9ba2e859aed462f264d718a44c7e6e4508bd2fbf
[ "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
6,492
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `ι →₀ β`. -/ import data.finsupp data.mv_polynomial linear_algebra.dimension noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule namespace finsupp section module variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply linear_independent.image (hf i) h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end end module section vector_space variables {K : Type*} {V : Type*} {ι : Type*} variables [field K] [add_comm_group V] [vector_space K V] open linear_map submodule lemma is_basis_single {φ : ι → Type*} (f : Π ι, φ ι → V) (hf : ∀i, is_basis K (f i)) : is_basis K (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin split, { apply linear_independent_single, exact λ i, (hf i).1 }, { rw [range_sigma_eq_Union_range, span_Union], simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image], simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] } end end vector_space section dim universes u v variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [vector_space K V] lemma dim_eq : vector_space.dim K (ι →₀ V) = cardinal.mk ι * vector_space.dim K V := begin rcases exists_is_basis K V with ⟨bs, hbs⟩, rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim, ← (is_basis_single _ (λa:ι, hbs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (injective_single.{u u} _), cardinal.sum_const] } end end dim end finsupp section vector_space /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₁] [vector_space K V₁] variables [add_comm_group V₂] [vector_space K V₂] variables [add_comm_group V'] [vector_space K V'] open vector_space set_option class.instance_max_depth 70 lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (dim K V) = cardinal.lift.{w v} (dim K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', rcases exists_is_basis K V with ⟨m, hm⟩, rcases exists_is_basis K V' with ⟨m', hm'⟩, rw [←cardinal.lift_inj.1 hm.mk_eq_dim, ←cardinal.lift_inj.1 hm'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨((module_equiv_finsupp hm).trans (finsupp.dom_lcongr e)).trans (module_equiv_finsupp hm').symm⟩, end def equiv_of_dim_eq_dim (h : dim K V₁ = dim K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end def fin_dim_vectorspace_equiv (n : ℕ) (hn : (dim K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end lemma eq_bot_iff_dim_eq_zero (p : submodule K V) (h : dim K p = 0) : p = ⊥ := begin have : dim K p = dim K (⊥ : submodule K V) := by rwa [dim_bot], let e := equiv_of_dim_eq_dim this, exact e.eq_bot_of_equiv _ end lemma injective_of_surjective (f : V₁ →ₗ[K] V₂) (hV₁ : dim K V₁ < cardinal.omega) (heq : dim K V₂ = dim K V₁) (hf : f.range = ⊤) : f.ker = ⊥ := have hk : dim K f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hV₁, begin rcases cardinal.lt_omega.1 hV₁ with ⟨d₁, eq₁⟩, rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩, have : 0 = d₂, { have := dim_eq_surjective f (linear_map.range_eq_top.1 hf), rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this, exact nat.add_left_cancel this }, refine eq_bot_iff_dim_eq_zero _ _, rw [eq₂, ← this, nat.cast_zero] end end vector_space section vector_space universes u open vector_space set_option class.instance_max_depth 50 local attribute [instance] submodule.module variables {K V : Type u} [field K] [add_comm_group V] [vector_space K V] set_option pp.universes false lemma cardinal_mk_eq_cardinal_mk_field_pow_dim (h : dim K V < cardinal.omega) : cardinal.mk V = cardinal.mk K ^ dim K V := begin rcases exists_is_basis K V with ⟨s, hs⟩, have : nonempty (fintype s), { rwa [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim] }, cases this with hsf, letI := hsf, calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩ ... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_dim_lt_omega [fintype K] (h : dim K V < cardinal.omega) : cardinal.mk V < cardinal.omega := begin rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h], exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h end end vector_space
ad251de94f049d02c95cccbd735cd379d8d91016
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/complex/upper_half_plane/functions_bounded_at_infty.lean
3a6ab5170dd8758944fd7ff67c04f1547f9da1df
[ "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
3,655
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck, David Loeffler -/ import algebra.module.submodule.basic import analysis.complex.upper_half_plane.basic import order.filter.zero_and_bounded_at_filter /-! # Bounded at infinity For complex valued functions on the upper half plane, this file defines the filter `at_im_infty` required for defining when functions are bounded at infinity and zero at infinity. Both of which are relevant for defining modular forms. -/ open complex filter open_locale topological_space upper_half_plane noncomputable theory namespace upper_half_plane /-- Filter for approaching `i∞`. -/ def at_im_infty := filter.at_top.comap upper_half_plane.im lemma at_im_infty_basis : (at_im_infty).has_basis (λ _, true) (λ (i : ℝ), im ⁻¹' set.Ici i) := filter.has_basis.comap upper_half_plane.im filter.at_top_basis lemma at_im_infty_mem (S : set ℍ) : S ∈ at_im_infty ↔ (∃ A : ℝ, ∀ z : ℍ, A ≤ im z → z ∈ S) := begin simp only [at_im_infty, filter.mem_comap', filter.mem_at_top_sets, ge_iff_le, set.mem_set_of_eq, upper_half_plane.coe_im], refine ⟨λ ⟨a, h⟩, ⟨a, (λ z hz, h (im z) hz rfl)⟩, _⟩, rintro ⟨A, h⟩, refine ⟨A, λ b hb x hx, h x _⟩, rwa hx, end /-- A function ` f : ℍ → α` is bounded at infinity if it is bounded along `at_im_infty`. -/ def is_bounded_at_im_infty {α : Type*} [has_norm α] (f : ℍ → α) : Prop := bounded_at_filter at_im_infty f /-- A function ` f : ℍ → α` is zero at infinity it is zero along `at_im_infty`. -/ def is_zero_at_im_infty {α : Type*} [has_zero α] [topological_space α] (f : ℍ → α) : Prop := zero_at_filter at_im_infty f lemma zero_form_is_bounded_at_im_infty {α : Type*} [normed_field α] : is_bounded_at_im_infty (0 : ℍ → α) := const_bounded_at_filter at_im_infty (0:α) /-- Module of functions that are zero at infinity. -/ def zero_at_im_infty_submodule (α : Type*) [normed_field α] : submodule α (ℍ → α) := zero_at_filter_submodule at_im_infty /-- ubalgebra of functions that are bounded at infinity. -/ def bounded_at_im_infty_subalgebra (α : Type*) [normed_field α] : subalgebra α (ℍ → α) := bounded_filter_subalgebra at_im_infty lemma is_bounded_at_im_infty.mul {f g : ℍ → ℂ} (hf : is_bounded_at_im_infty f) (hg : is_bounded_at_im_infty g) : is_bounded_at_im_infty (f * g) := by simpa only [pi.one_apply, mul_one, norm_eq_abs] using hf.mul hg lemma bounded_mem (f : ℍ → ℂ) : is_bounded_at_im_infty f ↔ ∃ (M A : ℝ), ∀ z : ℍ, A ≤ im z → abs (f z) ≤ M := by simp [is_bounded_at_im_infty, bounded_at_filter, asymptotics.is_O_iff, filter.eventually, at_im_infty_mem] lemma zero_at_im_infty (f : ℍ → ℂ) : is_zero_at_im_infty f ↔ ∀ ε : ℝ, 0 < ε → ∃ A : ℝ, ∀ z : ℍ, A ≤ im z → abs (f z) ≤ ε := begin rw [is_zero_at_im_infty, zero_at_filter, tendsto_iff_forall_eventually_mem], split, { simp_rw [filter.eventually, at_im_infty_mem], intros h ε hε, simpa using (h (metric.closed_ball (0 : ℂ) ε) (metric.closed_ball_mem_nhds (0 : ℂ) hε))}, { simp_rw metric.mem_nhds_iff, intros h s hs, simp_rw [filter.eventually, at_im_infty_mem], obtain ⟨ε, h1, h2⟩ := hs, have h11 : 0 < (ε/2), by {linarith,}, obtain ⟨A, hA⟩ := (h (ε/2) h11), use A, intros z hz, have hzs : f z ∈ s, { apply h2, simp only [mem_ball_zero_iff, norm_eq_abs], apply lt_of_le_of_lt (hA z hz), linarith }, apply hzs,} end end upper_half_plane
007f88cd22c6919115a92fed8846f69c2e03b5f4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/mapTR.lean
bc6fac40f5ecfbf0920e48609587a0c75997a304
[ "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
46
lean
#eval (List.range 100000).map (.+1) |>.length
3d423fc9b3c344362c831d3e3c5cf500b4974703
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/matrix/to_linear_equiv.lean
b56831b9bb21cce8d5182bdaffa932a52dd7c713
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
2,906
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.to_lin /-! # Matrices and linear equivalences This file gives the map `matrix.to_linear_equiv` from matrices with invertible determinant, to linear equivs. ## Main definitions * `matrix.to_linear_equiv`: a matrix with an invertible determinant forms a linear equiv ## Tags matrix, linear_equiv, determinant, inverse -/ namespace matrix open linear_map variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables {n : Type*} [fintype n] section to_linear_equiv' variables [decidable_eq n] /-- An invertible matrix yields a linear equivalence from the free module to itself. See `matrix.to_linear_equiv` for the same map on arbitrary modules. -/ noncomputable def to_linear_equiv' (P : matrix n n R) (h : is_unit P) : (n → R) ≃ₗ[R] (n → R) := have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h, { inv_fun := P⁻¹.to_lin', left_inv := λ v, show (P⁻¹.to_lin'.comp P.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.nonsing_inv_mul h', matrix.to_lin'_one, linear_map.id_apply], right_inv := λ v, show (P.to_lin'.comp P⁻¹.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.mul_nonsing_inv h', matrix.to_lin'_one, linear_map.id_apply], ..P.to_lin' } @[simp] lemma to_linear_equiv'_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv' h) : module.End R (n → R)) = P.to_lin' := rfl @[simp] lemma to_linear_equiv'_symm_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv' h).symm : module.End R (n → R)) = P⁻¹.to_lin' := rfl end to_linear_equiv' section to_linear_equiv variables (b : basis n R M) include b /-- Given `hA : is_unit A.det` and `b : basis R b`, `A.to_linear_equiv b hA` is the `linear_equiv` arising from `to_lin b b A`. See `matrix.to_linear_equiv'` for this result on `n → R`. -/ @[simps apply] noncomputable def to_linear_equiv [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : M ≃ₗ[R] M := begin refine ⟨to_lin b b A, linear_map.map_add _, linear_map.map_smul _, to_lin b b A⁻¹, λ x, _, λ x, _⟩; simp only [← linear_map.comp_apply, ← matrix.to_lin_mul b b b, matrix.nonsing_inv_mul _ hA, matrix.mul_nonsing_inv _ hA, to_lin_one, linear_map.id_apply] end lemma ker_to_lin_eq_bot [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : (to_lin b b A).ker = ⊥ := ker_eq_bot.mpr (to_linear_equiv b A hA).injective lemma range_to_lin_eq_top [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : (to_lin b b A).range = ⊤ := range_eq_top.mpr (to_linear_equiv b A hA).surjective end to_linear_equiv end matrix
149aba76d35ab861bdc152ced29f3c1a03bf8896
d1bbf1801b3dcb214451d48214589f511061da63
/src/analysis/normed_space/multilinear.lean
a2da86a8a20e9d2286dce930e1417d4346a51c35
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,795
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.operator_norm import topology.algebra.multilinear /-! # Operator norm on the space of continuous multilinear maps When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that it is indeed a norm, and prove its basic properties. ## Main results Let `f` be a multilinear map in finitely many variables. * `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0` with `∥f m∥ ≤ C * ∏ i, ∥m i∥` for all `m`. * `continuous_of_bound`, conversely, asserts that this bound implies continuity. * `mk_continuous` constructs the associated continuous multilinear map. Let `f` be a continuous multilinear map in finitely many variables. * `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. * `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥`. * `norm_image_sub_le_of_bound f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of `∥f∥` and `∥m₁ - m₂∥`. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a continuous multilinear function `f` in `n+1` variables into a continuous linear function taking values in continuous multilinear functions in `n` variables, and also into a continuous multilinear function in `n` variables taking values in continuous linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). They induce continuous linear equivalences between spaces of continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n` variables taking values in continuous linear functions), called respectively `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. ## Implementation notes We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity that we should deal with multilinear maps in several variables. The currying/uncurrying constructions are based on those in `multilinear.lean`. From the mathematical point of view, all the results follow from the results on operator norm in one variable, by applying them to one variable after the other through currying. However, this is only well defined when there is an order on the variables (for instance on `fin n`) although the final result is independent of the order. While everything could be done following this approach, it turns out that direct proofs are easier and more efficient. -/ noncomputable theory open_locale classical big_operators open finset local attribute [instance, priority 1001] add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_semimodule universes u v w w₁ w₂ wG variables {𝕜 : Type u} {ι : Type v} {n : ℕ} {G : Type wG} {E : fin n.succ → Type w} {E₁ : ι → Type w₁} {E₂ : Type w₂} [decidable_eq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group G] [∀i, normed_group (E i)] [∀i, normed_group (E₁ i)] [normed_group E₂] [normed_space 𝕜 G] [∀i, normed_space 𝕜 (E i)] [∀i, normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] /-! ### Continuity properties of multilinear maps We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, in both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`. -/ namespace multilinear_map variable (f : multilinear_map 𝕜 E₁ E₂) /-- If a multilinear map in finitely many variables on normed spaces is continuous, then it satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, for some `C` which can be chosen to be positive. -/ theorem exists_bound_of_continuous (hf : continuous f) : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := begin /- The proof only uses the continuity at `0`. Then, given a general point `m`, rescale each of its coordinates to bring them to a shell of fixed width around `0`, on which one knows that `f` is bounded, and then use the multiplicativity of `f` along each coordinate to deduce the desired bound.-/ obtain ⟨ε, ε_pos, hε⟩ : ∃ ε > 0, ∀{m}, dist m 0 < ε → dist (f m) (f 0) < 1 := metric.tendsto_nhds_nhds.1 hf.continuous_at 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, /- On points of size at most `δ`, `f` is bounded (by `1 + ∥f 0∥`). -/ have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1 + ∥f 0∥, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, calc ∥f a∥ = dist (f a) 0 : (dist_zero_right _).symm ... ≤ dist (f a) (f 0) + dist (f 0) 0 : dist_triangle _ _ _ ... ≤ 1 + ∥f 0∥ : by { rw dist_zero_right, exact add_le_add_right this _ } }, obtain ⟨c, hc⟩ : ∃c : 𝕜, 1 < ∥c∥ := normed_field.exists_one_lt_norm 𝕜, set C := (1 + ∥f 0∥) * ∏ i : ι, (δ⁻¹ * ∥c∥), have C_pos : 0 < C := mul_pos (lt_of_lt_of_le zero_lt_one (by simp)) (prod_pos (λi hi, mul_pos (inv_pos.2 δ_pos) (lt_of_le_of_lt zero_le_one hc))), refine ⟨C, C_pos, λm, _⟩, /- Given a general point `m`, rescale each coordinate to bring it to `[δ/∥c∥, δ]` by multiplication by a power of a scalar `c` with norm `∥c∥ > 1`.-/ by_cases h : ∃i, m i = 0, { rcases h with ⟨i, hi⟩, rw [f.map_coord_zero i hi, norm_zero], exact mul_nonneg (le_of_lt C_pos) (prod_nonneg (λi hi, norm_nonneg _)) }, { push_neg at h, have : ∀i, ∃d:𝕜, d ≠ 0 ∧ ∥d • m i∥ < δ ∧ (δ/∥c∥ ≤ ∥d • m i∥) ∧ (∥d∥⁻¹ ≤ δ⁻¹ * ∥c∥ * ∥m i∥) := λi, rescale_to_shell hc δ_pos (h i), choose d hd using this, have A : 0 ≤ 1 + ∥f 0∥ := add_nonneg zero_le_one (norm_nonneg _), have B : ∀ (i : ι), i ∈ univ → 0 ≤ ∥d i∥⁻¹ := λi hi, by simp, -- use the bound on `f` on the ball of size `δ` to conclude. calc ∥f m∥ = ∥f (λi, (d i)⁻¹ • (d i • m i))∥ : by { unfold_coes, congr' with i, rw [← mul_smul, inv_mul_cancel (hd i).1, one_smul] } ... = ∥(∏ i, (d i)⁻¹) • f (λi, d i • m i)∥ : by rw f.map_smul_univ ... = (∏ i, ∥d i∥⁻¹) * ∥f (λi, d i • m i)∥ : by { rw [norm_smul, normed_field.norm_prod], congr' with i, rw normed_field.norm_inv } ... ≤ (∏ i, ∥d i∥⁻¹) * (1 + ∥f 0∥) : mul_le_mul_of_nonneg_left (H ((pi_norm_le_iff (le_of_lt δ_pos)).2 (λi, (hd i).2.1.le))) (prod_nonneg B) ... ≤ (∏ i, δ⁻¹ * ∥c∥ * ∥m i∥) * (1 + ∥f 0∥) : mul_le_mul_of_nonneg_right (prod_le_prod B (λi hi, (hd i).2.2.2)) A ... = (∏ i : ι, δ⁻¹ * ∥c∥) * (∏ i, ∥m i∥) * (1 + ∥f 0∥) : by rw prod_mul_distrib ... = C * (∏ i, ∥m i∥) : by rw [mul_comm, ← mul_assoc] } end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a precise but hard to use version. See `norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads `∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`. -/ lemma norm_image_sub_le_of_bound' {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := begin have A : ∀(s : finset ι), ∥f m₁ - f (s.piecewise m₂ m₁)∥ ≤ C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { refine finset.induction (by simp) _, assume i s his Hrec, have I : ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ ≤ C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { have A : ((insert i s).piecewise m₂ m₁) = function.update (s.piecewise m₂ m₁) i (m₂ i) := s.piecewise_insert _ _ _, have B : s.piecewise m₂ m₁ = function.update (s.piecewise m₂ m₁) i (m₁ i), { ext j, by_cases h : j = i, { rw h, simp [his] }, { simp [h] } }, rw [B, A, ← f.map_sub], apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC), refine prod_le_prod (λj hj, norm_nonneg _) (λj hj, _), by_cases h : j = i, { rw h, simp }, { by_cases h' : j ∈ s; simp [h', h, le_refl] } }, calc ∥f m₁ - f ((insert i s).piecewise m₂ m₁)∥ ≤ ∥f m₁ - f (s.piecewise m₂ m₁)∥ + ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ : by { rw [← dist_eq_norm, ← dist_eq_norm, ← dist_eq_norm], exact dist_triangle _ _ _ } ... ≤ (C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) + C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : add_le_add Hrec I ... = C * ∑ i in insert i s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : by simp [his, add_comm, left_distrib] }, convert A univ, simp end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a usable but not very precise version. See `norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is `∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/ lemma norm_image_sub_le_of_bound {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := begin have A : ∀ (i : ι), ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1), { assume i, calc ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∏ j : ι, function.update (λ j, max ∥m₁∥ ∥m₂∥) i (∥m₁ - m₂∥) j : begin apply prod_le_prod, { assume j hj, by_cases h : j = i; simp [h, norm_nonneg] }, { assume j hj, by_cases h : j = i, { rw h, simp, exact norm_le_pi_norm (m₁ - m₂) i }, { simp [h, max_le_max, norm_le_pi_norm] } } end ... = ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } }, calc ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : f.norm_image_sub_le_of_bound' hC H m₁ m₂ ... ≤ C * ∑ i, ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : mul_le_mul_of_nonneg_left (sum_le_sum (λi hi, A i)) hC ... = C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ : by { rw [sum_const, card_univ, nsmul_eq_mul], ring } end /-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, then it is continuous. -/ theorem continuous_of_bound (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous f := begin let D := max C 1, have D_pos : 0 ≤ D := le_trans zero_le_one (le_max_right _ _), replace H : ∀ m, ∥f m∥ ≤ D * ∏ i, ∥m i∥, { assume m, apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _), exact prod_nonneg (λ(i : ι) hi, norm_nonneg (m i)) }, refine continuous_iff_continuous_at.2 (λm, _), refine continuous_at_of_locally_lipschitz zero_lt_one (D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1)) (λm' h', _), rw [dist_eq_norm, dist_eq_norm], have : 0 ≤ (max ∥m'∥ ∥m∥), by simp, have : (max ∥m'∥ ∥m∥) ≤ ∥m∥ + 1, by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm], calc ∥f m' - f m∥ ≤ D * (fintype.card ι) * (max ∥m'∥ ∥m∥) ^ (fintype.card ι - 1) * ∥m' - m∥ : f.norm_image_sub_le_of_bound D_pos H m' m ... ≤ D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1) * ∥m' - m∥ : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left] end /-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness condition. -/ def mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous_multilinear_map 𝕜 E₁ E₂ := { cont := f.continuous_of_bound C H, ..f } /-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on the other coordinates, then the resulting restricted function satisfies an inequality `∥f.restr v∥ ≤ C * ∥z∥^(n-k) * Π ∥v i∥` if the original function satisfies `∥f v∥ ≤ C * Π ∥v i∥`. -/ lemma restr_norm_le {k n : ℕ} (f : (multilinear_map 𝕜 (λ i : fin n, G) E₂ : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (v : fin k → G) : ∥f.restr s hk z v∥ ≤ C * ∥z∥ ^ (n - k) * ∏ i, ∥v i∥ := begin rw [mul_right_comm, mul_assoc], convert H _ using 2, simp only [apply_dite norm, fintype.prod_dite, prod_const (∥z∥), finset.card_univ, fintype.card_of_subtype sᶜ (λ x, mem_compl), card_compl, fintype.card_fin, hk, mk_coe, ← (s.order_iso_of_fin hk).symm.bijective.prod_comp (λ x, ∥v x∥)], refl end end multilinear_map /-! ### Continuous multilinear maps We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that this defines a normed space structure on `continuous_multilinear_map 𝕜 E₁ E₂`. -/ namespace continuous_multilinear_map variables (c : 𝕜) (f g : continuous_multilinear_map 𝕜 E₁ E₂) (m : Πi, E₁ i) theorem bound : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := f.to_multilinear_map.exists_bound_of_continuous f.2 open real /-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} instance has_op_norm : has_norm (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : continuous_multilinear_map 𝕜 E₁ E₂} : ∃ c, c ∈ {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : continuous_multilinear_map 𝕜 E₁ E₂} : bdd_below {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/ theorem le_op_norm : ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := begin have A : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), by_cases h : ∏ i, ∥m i∥ = 0, { rcases prod_eq_zero_iff.1 h with ⟨i, _, hi⟩, rw norm_eq_zero at hi, have : f m = 0 := f.map_coord_zero i hi, rw [this, norm_zero], exact mul_nonneg (op_norm_nonneg f) A }, { have hlt : 0 < ∏ i, ∥m i∥ := lt_of_le_of_ne A (ne.symm h), rw [← div_le_iff hlt], apply (le_Inf _ bounds_nonempty bounds_bdd_below).2, rintro c ⟨_, hc⟩, rw [div_le_iff hlt], apply hc } end lemma ratio_le_op_norm : ∥f m∥ / ∏ i, ∥m i∥ ≤ ∥f∥ := begin have : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), cases eq_or_lt_of_le this with h h, { simp [h.symm, op_norm_nonneg f] }, { rw div_le_iff h, exact le_op_norm f m } end /-- The image of the unit ball under a continuous multilinear map is bounded. -/ lemma unit_le_op_norm (h : ∥m∥ ≤ 1) : ∥f m∥ ≤ ∥f∥ := calc ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ : f.le_op_norm m ... ≤ ∥f∥ * ∏ i : ι, 1 : mul_le_mul_of_nonneg_left (prod_le_prod (λi hi, norm_nonneg _) (λi hi, le_trans (norm_le_pi_norm _ _) h)) (op_norm_nonneg f) ... = ∥f∥ : by simp /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ m, ∥f m∥ ≤ M * ∏ i, ∥m i∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := Inf_le _ bounds_bdd_below ⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul, exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩ /-- A continuous linear map is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := begin split, { assume h, ext m, simpa [h] using f.le_op_norm m }, { rintro rfl, apply le_antisymm (op_norm_le_bound 0 le_rfl (λm, _)) (op_norm_nonneg _), simp } end variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' E₂] [is_scalar_tower 𝕜' 𝕜 E₂] lemma op_norm_smul_le (c : 𝕜') : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := (c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) begin intro m, erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous multilinear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (continuous_multilinear_map 𝕜 E₁ E₂) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜' (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨λ c f, f.op_norm_smul_le c⟩ section restrict_scalars variables [Π i, normed_space 𝕜' (E₁ i)] [∀ i, is_scalar_tower 𝕜' 𝕜 (E₁ i)] @[simp] lemma norm_restrict_scalars : ∥f.restrict_scalars 𝕜'∥ = ∥f∥ := by simp only [norm_def, coe_restrict_scalars] variable (𝕜') /-- `continuous_multilinear_map.restrict_scalars` as a `continuous_multilinear_map`. -/ def restrict_scalars_linear : continuous_multilinear_map 𝕜 E₁ E₂ →L[𝕜'] continuous_multilinear_map 𝕜' E₁ E₂ := linear_map.mk_continuous { to_fun := restrict_scalars 𝕜', map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } 1 $ λ f, by simp variable {𝕜'} lemma continuous_restrict_scalars : continuous (restrict_scalars 𝕜' : continuous_multilinear_map 𝕜 E₁ E₂ → continuous_multilinear_map 𝕜' E₁ E₂) := (restrict_scalars_linear 𝕜').continuous end restrict_scalars /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version. For a less precise but more usable version, see `norm_image_sub_le_of_bound`. The bound reads `∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`.-/ lemma norm_image_sub_le_of_bound' (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise version. For a more precise but less usable version, see `norm_image_sub_le_of_bound'`. The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/ lemma norm_image_sub_le_of_bound (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _ /-- Applying a multilinear map to a vector is continuous in both coordinates. -/ lemma continuous_eval : continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂ × (Πi, E₁ i))), p.1 p.2) := begin apply continuous_iff_continuous_at.2 (λp, _), apply continuous_at_of_locally_lipschitz zero_lt_one ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + ∏ i, ∥p.2 i∥) (λq hq, _), have : 0 ≤ (max ∥q.2∥ ∥p.2∥), by simp, have : 0 ≤ ∥p∥ + 1, by simp [le_trans zero_le_one], have A : ∥q∥ ≤ ∥p∥ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq), have : (max ∥q.2∥ ∥p.2∥) ≤ ∥p∥ + 1 := le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]), have : ∀ (i : ι), i ∈ univ → 0 ≤ ∥p.2 i∥ := λ i hi, norm_nonneg _, calc dist (q.1 q.2) (p.1 p.2) ≤ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _ ... = ∥q.1 q.2 - q.1 p.2∥ + ∥q.1 p.2 - p.1 p.2∥ : by rw [dist_eq_norm, dist_eq_norm] ... ≤ ∥q.1∥ * (fintype.card ι) * (max ∥q.2∥ ∥p.2∥) ^ (fintype.card ι - 1) * ∥q.2 - p.2∥ + ∥q.1 - p.1∥ * ∏ i, ∥p.2 i∥ : add_le_add (norm_image_sub_le_of_bound _ _ _) ((q.1 - p.1).le_op_norm p.2) ... ≤ (∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) * ∥q - p∥ + ∥q - p∥ * ∏ i, ∥p.2 i∥ : by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg, mul_nonneg, pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg, norm_fst_le (q - p), prod_nonneg] ... = ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + (∏ i, ∥p.2 i∥)) * dist q p : by { rw dist_eq_norm, ring } end lemma continuous_eval_left (m : Π i, E₁ i) : continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂)), (p : (Π i, E₁ i) → E₂) m) := continuous_eval.comp (continuous.prod_mk continuous_id continuous_const) lemma has_sum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E₁ E₂} {q : continuous_multilinear_map 𝕜 E₁ E₂} (h : has_sum p q) (m : Π i, E₁ i) : has_sum (λ a, p a m) (q m) := begin dsimp [has_sum] at h ⊢, convert ((continuous_eval_left m).tendsto _).comp h, ext s, simp end open_locale topological_space open filter /-- If the target space is complete, the space of continuous multilinear maps with its norm is also complete. The proof is essentially the same as for the space of continuous linear maps (modulo the addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear case from the multilinear case via a currying isomorphism. However, this would mess up imports, and it is more satisfactory to have the simplest case as a standalone proof. -/ instance [complete_space E₂] : complete_space (continuous_multilinear_map 𝕜 E₁ E₂) := begin have nonneg : ∀ (v : Π i, E₁ i), 0 ≤ ∏ i, ∥v i∥ := λ v, finset.prod_nonneg (λ i hi, norm_nonneg _), -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, -- and establish that the evaluation at any point `v : Π i, E₁ i` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∏ i, ∥v i∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (nonneg v) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `E₂` is complete) -- into a function which we call `F`. choose F hF using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `F` is multilinear, let Fmult : multilinear_map 𝕜 E₁ E₂ := { to_fun := F, map_add' := λ v i x y, begin have A := hF (function.update v i (x + y)), have B := (hF (function.update v i x)).add (hF (function.update v i y)), simp at A B, exact tendsto_nhds_unique A B end, map_smul' := λ v i c x, begin have A := hF (function.update v i (c • x)), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hF (function.update v i x)), simp at A B, exact tendsto_nhds_unique A B end }, -- and that `F` has norm at most `(b 0 + ∥f 0∥)`. have Fnorm : ∀ v, ∥F v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hF v).norm (eventually_of_forall A) }, -- Thus `F` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Fcont := Fmult.mk_continuous _ Fnorm, use Fcont, -- Our last task is to establish convergence to `F` in norm. have : ∀ n, ∥f n - Fcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∏ i, ∥v i∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Fcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hF v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end continuous_multilinear_map /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ∥f.mk_continuous C H∥ ≤ C := continuous_multilinear_map.op_norm_le_bound _ hC (λm, H m) namespace continuous_multilinear_map /-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : (G [×n]→L[𝕜] E₂ : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) : G [×k]→L[𝕜] E₂ := (f.to_multilinear_map.restr s hk z).mk_continuous (∥f∥ * ∥z∥^(n-k)) $ λ v, multilinear_map.restr_norm_le _ _ _ _ f.le_op_norm _ lemma norm_restr {k n : ℕ} (f : G [×n]→L[𝕜] E₂) (s : finset (fin n)) (hk : s.card = k) (z : G) : ∥f.restr s hk z∥ ≤ ∥f∥ * ∥z∥ ^ (n - k) := begin apply multilinear_map.mk_continuous_norm_le, exact mul_nonneg (norm_nonneg _) (pow_nonneg (norm_nonneg _) _) end section variables (𝕜 ι) (A : Type*) [normed_comm_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra : continuous_multilinear_map 𝕜 (λ i : ι, A) A := @multilinear_map.mk_continuous 𝕜 ι (λ i : ι, A) A _ _ _ _ _ _ _ (multilinear_map.mk_pi_algebra 𝕜 ι A) (if nonempty ι then 1 else ∥(1 : A)∥) $ begin intro m, by_cases hι : nonempty ι, { resetI, simp [hι, norm_prod_le' univ univ_nonempty] }, { simp [eq_empty_of_not_nonempty hι univ, hι] } end variables {A 𝕜 ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : continuous_multilinear_map.mk_pi_algebra 𝕜 ι A m = ∏ i, m i := rfl lemma norm_mk_pi_algebra_le [nonempty ι] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ 1 := calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = _ : if_pos ‹_› lemma norm_mk_pi_algebra_of_empty (h : ¬nonempty ι) : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = ∥(1 : A)∥ := begin apply le_antisymm, calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = ∥(1 : A)∥ : if_neg ‹_›, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp [eq_empty_of_not_nonempty h univ] end @[simp] lemma norm_mk_pi_algebra [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = 1 := begin by_cases hι : nonempty ι, { resetI, refine le_antisymm norm_mk_pi_algebra_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp }, { simp [norm_mk_pi_algebra_of_empty hι] } end end section variables (𝕜 n) (A : Type*) [normed_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin : continuous_multilinear_map 𝕜 (λ i : fin n, A) A := @multilinear_map.mk_continuous 𝕜 (fin n) (λ i : fin n, A) A _ _ _ _ _ _ _ (multilinear_map.mk_pi_algebra_fin 𝕜 n A) (nat.cases_on n ∥(1 : A)∥ (λ _, 1)) $ begin intro m, cases n, { simp }, { have : @list.of_fn A n.succ m ≠ [] := by simp, simpa [← fin.prod_of_fn] using list.norm_prod_le' this } end variables {A 𝕜 n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A m = (list.of_fn m).prod := rfl lemma norm_mk_pi_algebra_fin_succ_le : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n.succ A∥ ≤ 1 := multilinear_map.mk_continuous_norm_le _ zero_le_one _ lemma norm_mk_pi_algebra_fin_le_of_pos (hn : 0 < n) : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ ≤ 1 := by cases n; [exact hn.false.elim, exact norm_mk_pi_algebra_fin_succ_le] lemma norm_mk_pi_algebra_fin_zero : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 0 A∥ = ∥(1 : A)∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, convert ratio_le_op_norm _ (λ _, 1); [simp, apply_instance] end lemma norm_mk_pi_algebra_fin [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ = 1 := begin cases n, { simp [norm_mk_pi_algebra_fin_zero] }, { refine le_antisymm norm_mk_pi_algebra_fin_succ_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp } end end variables (𝕜 ι) /-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_field (z : E₂) : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂ := @multilinear_map.mk_continuous 𝕜 ι (λ(i : ι), 𝕜) E₂ _ _ _ _ _ _ _ (multilinear_map.mk_pi_ring 𝕜 ι z) (∥z∥) (λ m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod, mul_comm]) variables {𝕜 ι} @[simp] lemma mk_pi_field_apply (z : E₂) (m : ι → 𝕜) : (continuous_multilinear_map.mk_pi_field 𝕜 ι z : (ι → 𝕜) → E₂) m = (∏ i, m i) • z := rfl lemma mk_pi_field_apply_one_eq_self (f : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) : continuous_multilinear_map.mk_pi_field 𝕜 ι (f (λi, 1)) = f := to_multilinear_map_inj f.to_multilinear_map.mk_pi_ring_apply_one_eq_self variables (𝕜 ι E₂) /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv_aux : E₂ ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) := { to_fun := λ z, continuous_multilinear_map.mk_pi_field 𝕜 ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_field_apply_one_eq_self } /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a continuous linear equivalence in `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv : E₂ ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) := { continuous_to_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λz, _), rw one_mul, change ∥continuous_multilinear_map.mk_pi_field 𝕜 ι z∥ ≤ ∥z∥, exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end, continuous_inv_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, _), rw one_mul, change ∥f (λi, 1)∥ ≤ ∥f∥, apply @continuous_multilinear_map.unit_le_op_norm 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _ f, simp [pi_norm_le_iff zero_le_one, le_refl] end, .. continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂ } end continuous_multilinear_map section currying /-! ### Currying We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`). The inverse operations are called `uncurry_left` and `uncurry_right`. We also register continuous linear equiv versions of these correspondences, in `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. -/ open fin function lemma continuous_linear_map.norm_map_tail_le (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) : ∥f (m 0) (tail m)∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (m 0) (tail m)∥ ≤ ∥f (m 0)∥ * ∏ i, ∥(tail m) i∥ : (f (m 0)).le_op_norm _ ... ≤ (∥f∥ * ∥m 0∥) * ∏ i, ∥(tail m) i∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (λi hi, norm_nonneg _)) ... = ∥f∥ * (∥m 0∥ * ∏ i, ∥(tail m) i∥) : by ring ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_succ, refl } lemma continuous_multilinear_map.norm_map_init_le (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) : ∥f (init m) (m (last n))∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (init m) (m (last n))∥ ≤ ∥f (init m)∥ * ∥m (last n)∥ : (f (init m)).le_op_norm _ ... ≤ (∥f∥ * (∏ i, ∥(init m) i∥)) * ∥m (last n)∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _) ... = ∥f∥ * ((∏ i, ∥(init m) i∥) * ∥m (last n)∥) : mul_assoc _ _ _ ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_cast_succ, refl } lemma continuous_multilinear_map.norm_map_cons_le (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) : ∥f (cons x m)∥ ≤ ∥f∥ * ∥x∥ * ∏ i, ∥m i∥ := calc ∥f (cons x m)∥ ≤ ∥f∥ * ∏ i, ∥cons x m i∥ : f.le_op_norm _ ... = (∥f∥ * ∥x∥) * ∏ i, ∥m i∥ : by { rw prod_univ_succ, simp [mul_assoc] } lemma continuous_multilinear_map.norm_map_snoc_le (f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) : ∥f (snoc m x)∥ ≤ ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ := calc ∥f (snoc m x)∥ ≤ ∥f∥ * ∏ i, ∥snoc m x i∥ : f.le_op_norm _ ... = ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ : by { rw prod_univ_cast_succ, simp [mul_assoc] } /-! #### Left currying -/ /-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def continuous_linear_map.uncurry_left (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : continuous_multilinear_map 𝕜 E E₂ := (@linear_map.uncurry_left 𝕜 n E E₂ _ _ _ _ _ (continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous (∥f∥) (λm, continuous_linear_map.norm_map_tail_le f m) @[simp] lemma continuous_linear_map.uncurry_left_apply (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain a continuous linear map into continuous multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def continuous_multilinear_map.curry_left (f : continuous_multilinear_map 𝕜 E E₂) : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂) := linear_map.mk_continuous { -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear -- map to_fun := λx, (f.to_multilinear_map.curry_left x).mk_continuous (∥f∥ * ∥x∥) (f.norm_map_cons_le x), map_add' := λx y, by { ext m, exact f.cons_add m x y }, map_smul' := λc x, by { ext m, exact f.cons_smul m c x } } -- then register its continuity thanks to its boundedness properties. (∥f∥) (λx, multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _) @[simp] lemma continuous_multilinear_map.curry_left_apply (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma continuous_linear_map.curry_uncurry_left (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, continuous_linear_map.uncurry_left_apply, continuous_multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma continuous_multilinear_map.uncurry_curry_left (f : continuous_multilinear_map 𝕜 E E₂) : f.curry_left.uncurry_left = f := by { ext m, simp } @[simp] lemma continuous_multilinear_map.curry_left_norm (f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_left∥ = ∥f∥ := begin apply le_antisymm (linear_map.mk_continuous_norm_le _ (norm_nonneg _) _), have : ∥f.curry_left.uncurry_left∥ ≤ ∥f.curry_left∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end @[simp] lemma continuous_linear_map.uncurry_left_norm (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : ∥f.uncurry_left∥ = ∥f∥ := begin apply le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _), have : ∥f.uncurry_left.curry_left∥ ≤ ∥f.uncurry_left∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end variables (𝕜 E E₂) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_left_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_left_equiv_aux : (E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { to_fun := continuous_linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_left, left_inv := continuous_linear_map.curry_uncurry_left, right_inv := continuous_multilinear_map.uncurry_curry_left } /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_left_equiv : (E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { continuous_to_fun := begin refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.uncurry_left_norm end, continuous_inv_fun := begin refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.curry_left_norm end, .. continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂ } variables {𝕜 E E₂} @[simp] lemma continuous_multilinear_curry_left_equiv_apply (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (v : Π i, E i) : continuous_multilinear_curry_left_equiv 𝕜 E E₂ f v = f (v 0) (tail v) := rfl @[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (v : Π (i : fin n), E i.succ) : (continuous_multilinear_curry_left_equiv 𝕜 E E₂).symm f x v = f (cons x v) := rfl /-! #### Right currying -/ /-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/ def continuous_multilinear_map.uncurry_right (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : continuous_multilinear_map 𝕜 E E₂ := let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →ₗ[𝕜] E₂) := { to_fun := λ m, (f m).to_linear_map, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in (@multilinear_map.uncurry_right 𝕜 n E E₂ _ _ _ _ _ f').mk_continuous (∥f∥) (λm, f.norm_map_init_le m) @[simp] lemma continuous_multilinear_map.uncurry_right_apply (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain a continuous multilinear map in `n` variables into continuous linear maps, given by `m ↦ (x ↦ f (snoc m x))`. -/ def continuous_multilinear_map.curry_right (f : continuous_multilinear_map 𝕜 E E₂) : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) := let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) := { to_fun := λm, (f.to_multilinear_map.curry_right m).mk_continuous (∥f∥ * ∏ i, ∥m i∥) $ λx, f.norm_map_snoc_le m x, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in f'.mk_continuous (∥f∥) (λm, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (prod_nonneg (λj hj, norm_nonneg _))) _) @[simp] lemma continuous_multilinear_map.curry_right_apply (f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma continuous_multilinear_map.curry_uncurry_right (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, continuous_multilinear_map.curry_right_apply, continuous_multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma continuous_multilinear_map.uncurry_curry_right (f : continuous_multilinear_map 𝕜 E E₂) : f.curry_right.uncurry_right = f := by { ext m, simp } @[simp] lemma continuous_multilinear_map.curry_right_norm (f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_right∥ = ∥f∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, have : ∥f.curry_right.uncurry_right∥ ≤ ∥f.curry_right∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end @[simp] lemma continuous_multilinear_map.uncurry_right_norm (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : ∥f.uncurry_right∥ = ∥f∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, have : ∥f.uncurry_right.curry_right∥ ≤ ∥f.uncurry_right∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end variables (𝕜 E E₂) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a linear equiv in `continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_right_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_right_equiv_aux : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { to_fun := continuous_multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_right, left_inv := continuous_multilinear_map.curry_uncurry_right, right_inv := continuous_multilinear_map.uncurry_curry_right } /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_right_equiv : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { continuous_to_fun := begin refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.uncurry_right_norm end, continuous_inv_fun := begin refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.curry_right_norm end, .. continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂ } variables (n G) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), G` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), G` with values in the space of continuous linear maps on `G`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv' 𝕜 n G E₂`. For a version allowing dependent types, see `continuous_multilinear_curry_right_equiv`. When there are no dependent types, use the primed version as it helps Lean a lot for unification. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_right_equiv' : (continuous_multilinear_map 𝕜 (λ(i : fin n), G) (G →L[𝕜] E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n.succ), G) E₂) := continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin n.succ), G) E₂ variables {n 𝕜 G E E₂} @[simp] lemma continuous_multilinear_curry_right_equiv_apply (f : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂))) (v : Π i, E i) : (continuous_multilinear_curry_right_equiv 𝕜 E E₂) f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply (f : continuous_multilinear_map 𝕜 E E₂) (v : Π (i : fin n), E i.cast_succ) (x : E (last n)) : (continuous_multilinear_curry_right_equiv 𝕜 E E₂).symm f v x = f (snoc v x) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_apply' (f : (continuous_multilinear_map 𝕜 (λ(i : fin n), G) (G →L[𝕜] E₂))) (v : Π (i : fin n.succ), G) : (continuous_multilinear_curry_right_equiv' 𝕜 n G E₂) f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply' (f : continuous_multilinear_map 𝕜 (λ(i : fin n.succ), G) E₂) (v : Π (i : fin n), G) (x : G) : (continuous_multilinear_curry_right_equiv' 𝕜 n G E₂).symm f v x = f (snoc v x) := rfl /-! #### Currying with `0` variables The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!). Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated derivatives, we register this isomorphism. -/ variables {𝕜 G E₂} /-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/ def continuous_multilinear_map.uncurry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : E₂ := f 0 variables (𝕜 G) /-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0` variables taking the (unique) value `x` -/ def continuous_multilinear_map.curry0 (x : E₂) : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂ := { to_fun := λm, x, map_add' := λ m i, fin.elim0 i, map_smul' := λ m i, fin.elim0 i, cont := continuous_const } variable {G} @[simp] lemma continuous_multilinear_map.curry0_apply (x : E₂) (m : (fin 0) → G) : (continuous_multilinear_map.curry0 𝕜 G x : ((fin 0) → G) → E₂) m = x := rfl variable {𝕜} @[simp] lemma continuous_multilinear_map.uncurry0_apply (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : f.uncurry0 = f 0 := rfl @[simp] lemma continuous_multilinear_map.apply_zero_curry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} : continuous_multilinear_map.curry0 𝕜 G (f x) = f := by { ext m, simp [(subsingleton.elim _ _ : x = m)] } lemma continuous_multilinear_map.uncurry0_curry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : continuous_multilinear_map.curry0 𝕜 G (f.uncurry0) = f := by simp variables (𝕜 G) @[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : E₂) : (continuous_multilinear_map.curry0 𝕜 G x).uncurry0 = x := rfl @[simp] lemma continuous_multilinear_map.uncurry0_norm (x : E₂) : ∥continuous_multilinear_map.curry0 𝕜 G x∥ = ∥x∥ := begin apply le_antisymm, { exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp) }, { simpa using (continuous_multilinear_map.curry0 𝕜 G x).le_op_norm 0 } end variables {𝕜 G} @[simp] lemma continuous_multilinear_map.fin0_apply_norm (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} : ∥f x∥ = ∥f∥ := begin have : x = 0 := subsingleton.elim _ _, subst this, refine le_antisymm (by simpa using f.le_op_norm 0) _, have : ∥continuous_multilinear_map.curry0 𝕜 G (f.uncurry0)∥ ≤ ∥f.uncurry0∥ := continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp [-continuous_multilinear_map.apply_zero_curry0]), simpa end lemma continuous_multilinear_map.curry0_norm (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : ∥f.uncurry0∥ = ∥f∥ := by simp variables (𝕜 G E₂) /-- The linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The continuous version is given in `continuous_multilinear_curry_fin0`. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_fin0_aux : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃ₗ[𝕜] E₂ := { to_fun := λf, continuous_multilinear_map.uncurry0 f, inv_fun := λf, continuous_multilinear_map.curry0 𝕜 G f, map_add' := λf g, rfl, map_smul' := λc f, rfl, left_inv := continuous_multilinear_map.uncurry0_curry0, right_inv := continuous_multilinear_map.curry0_uncurry0 𝕜 G } /-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_fin0 : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃L[𝕜] E₂ := { continuous_to_fun := begin change continuous (λ (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂), (f : ((fin 0) → G) → E₂) 0), exact continuous_multilinear_map.continuous_eval.comp (continuous_id.prod_mk continuous_const) end, continuous_inv_fun := begin refine (continuous_multilinear_curry_fin0_aux 𝕜 G E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact continuous_multilinear_map.uncurry0_norm _ _ _ end, .. continuous_multilinear_curry_fin0_aux 𝕜 G E₂ } variables {𝕜 G E₂} @[simp] lemma continuous_multilinear_curry_fin0_apply (f : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂)) : continuous_multilinear_curry_fin0 𝕜 G E₂ f = f 0 := rfl @[simp] lemma continuous_multilinear_curry_fin0_symm_apply (x : E₂) (v : (fin 0) → G) : (continuous_multilinear_curry_fin0 𝕜 G E₂).symm x v = x := rfl /-! #### With 1 variable -/ variables (𝕜 G E₂) /-- Continuous multilinear maps from `G^1` to `E₂` are isomorphic with continuous linear maps from `G` to `E₂`. -/ def continuous_multilinear_curry_fin1 : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂) ≃L[𝕜] (G →L[𝕜] E₂) := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin 1), G) E₂).symm.trans (continuous_multilinear_curry_fin0 𝕜 G (G →L[𝕜] E₂)) variables {𝕜 G E₂} @[simp] lemma continuous_multilinear_curry_fin1_apply (f : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂)) (x : G) : continuous_multilinear_curry_fin1 𝕜 G E₂ f x = f (fin.snoc 0 x) := rfl @[simp] lemma continuous_multilinear_curry_fin1_symm_apply (f : G →L[𝕜] E₂) (v : (fin 1) → G) : (continuous_multilinear_curry_fin1 𝕜 G E₂).symm f v = f (v 0) := rfl end currying
a174eddaaa49db38fb7f0804ec32878bdf38bd76
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/tactic/transport.lean
ba68b7269771461e6dc70491932de9a524f9d32f
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
5,383
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Simon Hudon, Scott Morrison -/ import tactic.equiv_rw /-! ## The `transport` tactic `transport` attempts to move an `s : S α` expression across an equivalence `e : α ≃ β` to solve a goal of the form `S β`, by building the new object field by field, taking each field of `s` and rewriting it along `e` using the `equiv_rw` tactic. We try to ensure good definitional properties, so that, for example, when we transport a `monoid α` to a `monoid β`, the new multiplication is definitionally `λ x y, e (e.symm a * e.symm b)`. -/ namespace tactic open tactic.interactive mk_simp_attribute transport_simps "The simpset `transport_simps` is used by the tactic `transport` to simplify certain expressions involving application of equivalences, and trivial `eq.rec` or `ep.mpr` conversions. It's probably best not to adjust it without understanding the algorithm used by `transport`." attribute [transport_simps] eq_rec_constant eq_mpr_rfl equiv.to_fun_as_coe equiv.arrow_congr'_apply equiv.symm_apply_apply -- we use `apply_eq_iff_eq_symm_apply` rather than `apply_eq_iff_eq`, -- as many axioms have a constant on the right-hand-side equiv.apply_eq_iff_eq_symm_apply /-- Given `s : S α` for some structure `S` depending on a type `α`, and an equivalence `e : α ≃ β`, try to produce an `S β`, by transporting data and axioms across `e` using `equiv_rw`. -/ @[nolint unused_arguments] -- At present we don't actually use `s`; it's inferred in the `mk_app` call. meta def transport (s e : expr) : tactic unit := do (_, α, β) ← infer_type e >>= relation_lhs_rhs <|> fail format!"second argument to `transport` was not an equivalence-type relation", -- We explode the goal into individual fields using `refine_struct`. -- Later we'll want to also consider falling back to `fconstructor`, -- but for now this suffices. seq' `[refine_struct { .. }] -- We now deal with each field sequentially. -- Since we may pass goals through to the user if the heuristics here fail, -- we wrap everything in `propagate_tags`. (propagate_tags (try (do -- Look up the name of the current field being processed f ← get_current_field, -- Note the value in the original structure. -- (This `mk_mapp` call with second argument inferred only works for typeclasses!) mk_mapp f [α, none] >>= note f none, -- We now run different algorithms, -- depending on whether we're transporting data or a proposition. b ← target >>= is_prop, -- In order to achieve good definitional properties, -- we use `simp_result` to intercept the synthesized term and simplify it, -- in particular simplifying along `eq_rec_constant`. if ¬ b then simp_result (do -- For data fields, simply rewrite them using `equiv_rw`. equiv_rw_hyp f e, get_local f >>= exact) else try (do -- The goal probably has messy expressions produced by `equiv_rw` acting on early data fields, -- so we clean up a little. try unfold_projs_target, `[simp only with transport_simps], -- If the field is an equation in `β`, try to use injectivity of the equivalence -- to turn it into an equation in `α`. -- (If the left hand side of the equation involved an operation we've already transported, -- this step has already been achieved by the `transport_simps`, so we `try` this step.) try $ under_binders $ to_expr ``((%%e).symm.injective) >>= apply, -- Finally, rewrite the original field value using the equivalence `e`, and try to close -- the goal using equiv_rw_hyp f e, get_local f >>= exact)))) namespace interactive setup_tactic_parser /-- Given a goal `⊢ S β` for some type class `S`, and an equivalence `e : α ≃ β`. `transport using e` will look for a hypothesis `s : S α`, and attempt to close the goal by transporting `s` across the equivalence `e`. ```lean example {α : Type} [ring α] {β : Type} (e : α ≃ β) : ring β := by transport using e. ``` You can specify the object to transport using `transport s using e`. `transport` works by attempting to copy each of the operations and axiom fields of `s`, rewriting them using `equiv_rw e` and defining a new structure using these rewritten fields. If it fails to fill in all the new fields, `transport` will produce new subgoals. It's probably best to think about which missing `simp` lemmas would have allowed `transport` to finish, rather than solving these goals by hand. (This may require looking at the implementation of `tranport` to understand its algorithm; there are several examples of "transport-by-hand" at the end of `test/equiv_rw.lean`, which `transport` is an abstraction of.) -/ meta def transport (s : parse texpr?) (e : parse $ (tk "using" *> texpr)) : itactic := do s ← match s with | some s := to_expr s | none := (do t ← target, let n := t.get_app_fn.const_name, ctx ← local_context, ctx.any_of (λ e, (do t ← infer_type e, guard (t.get_app_fn.const_name = n), return e))) <|> fail "`transport` could not find an appropriate source object. Try `transport s using e`." end, e ← to_expr e, tactic.transport s e end interactive end tactic
faba0ff3fe8fac4f64c6121286972954fe7b2a9e
827a8a5c2041b1d7f55e128581f583dfbd65ecf6
/spectral/scratch2.hlean
a7b2bdc51a1d2a452f9fe794a6064f3d7c9dada1
[ "Apache-2.0" ]
permissive
fpvandoorn/leansnippets
6af0499f6f3fd2c07e4b580734d77b67574e7c27
601bafbe07e9534af76f60994d6bdf741996ef93
refs/heads/master
1,590,063,910,882
1,545,093,878,000
1,545,093,878,000
36,044,957
2
2
null
1,442,619,708,000
1,432,256,875,000
Lean
UTF-8
Lean
false
false
8,961
hlean
import cohomology.basic open cohomology algebra int fwedge choice set_option pp.universes true set_option pp.abbreviations false print unreduced_ordinary_cohomology print is_contr_ordinary_cohomology print unreduced_ordinary_cohomology_sphere_of_neq print unreduced_ordinary_cohomology_nonzero print unreduced_cohomology_split print cohomology_wedge print wedge.wedge_pequiv print cohomology_fwedge print fwedge.trunc_fwedge_pmap_equiv print fwedge_pmap_equiv print choice_equiv exit import .pointed_pi import algebra.product_group open fiber eq is_trunc is_conn trunc susp equiv is_equiv pointed algebra group nat function sigma sigma.ops open int prod prod.ops set_option pp.coercions true definition add_ab_group_coercion [instance] (A : AddAbGroup) : add_ab_group (algebra._trans_of_Group_of_AbGroup_2 A) := AbGroup.struct A exit open trunc_index prod fin universe variable u definition ppi_functor [constructor] {A' A : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A' →* A) (g : Πa', B (f a') → B' a') (p : g pt (transport B (respect_pt f)⁻¹ b) = b') (h : ppi B b) : ppi B' b' := proof ppi.mk (λa', g a' (h (f a'))) (ap (λx, g pt x) (eq_tr_of_pathover (apd h (respect_pt f) ⬝op respect_pt h)) ⬝ p) qed definition ppi_functor_left [constructor] {A' A : Type*} {B : A → Type} (f : A' →* A) {b : B pt} {b' : B (f pt)} (p : b' =[respect_pt f] b) (g : ppi B b) : ppi (B ∘ f) b' := proof ppi_functor f (λa, id) (tr_eq_of_pathover p⁻¹ᵒ) g qed -- definition ppi_functor_left_ppi_const [constructor] {A' A : Type*} {B : A → Type} -- (f : A' →* A) {b : B pt} {b' : B (f pt)} (p : b' =[respect_pt f] b) : ppi_functor_left_ppi_const _ _ ~* ppi_const (B ∘ f) := -- phomotopy.mk homotopy.rfl proof !eq_tr_of_pathover_con_tr_eq_of_pathover⁻¹ ⬝ whisker_right _ !ap_id⁻¹ qed definition respect_pt_ppi_functor_left [constructor] {A' : Type*} {A : Type} {B : A → Type} (f : A' → A) {b : B (f pt)} (g : ppi B b) : respect_pt (@ppi_functor_left A' (pointed.MK A (f pt)) B (pmap_of_map_pt f) _ _ idpo g) = respect_pt g := sorry definition ppi_compose_pmap [constructor] {A' A : Type*} {B : A → Type*} (f : A' →* A) (g : Π*(a : A), B a) : Π*(a' : A'), B (f a') := ppi_functor_left f (apd (λa, Point (B a)) (respect_pt f)) g definition ppi_compose_pmap_ppi_const [constructor] {A' A : Type*} (B : A → Type*) (f : A' →* A) : ppi_compose_pmap f (ppi_const B) ~* ppi_const (B ∘ f) := phomotopy.mk homotopy.rfl proof !eq_tr_of_pathover_con_tr_eq_of_pathover⁻¹ ⬝ whisker_right _ !ap_id⁻¹ qed definition ppi_compose_right [constructor] {A' A : Type*} (B : A → Type*) (f : A' →* A) : (Π*(a : A), B a) →* Π*(a' : A'), B (f a') := pmap.mk (ppi_compose_pmap f) (eq_of_phomotopy (ppi_compose_pmap_ppi_const B f)) definition ppi_eq_equiv_natural_left_gen_lem {A' A : Type*} {B : A → Type} {f : A' →* A} {b₀ : B pt} {b₀' : B (f pt)} {k l : ppi B b₀} {k' l' : ppi (B ∘ f) b₀'} (p : b₀' =[respect_pt f] b₀) (q : ppi_functor_left f p k ~* k') (r : ppi_functor_left f p l ~* l') : (q pt)⁻¹ ⬝ transport (λx, k x = l x) (respect_pt f)⁻¹ (respect_pt k ⬝ (respect_pt l)⁻¹) ⬝ r pt = respect_pt k' ⬝ (respect_pt l')⁻¹ := begin exact sorry end definition ppi_eq_equiv_natural_left_gen {A' A : Type*} {B : A → Type} {f : A' →* A} {b₀ : B pt} {b₀' : B (f pt)} {k l : ppi B b₀} {k' l' : ppi (B ∘ f) b₀'} (p : b₀' =[respect_pt f] b₀) (q : ppi_functor_left f p k ~* k') (r : ppi_functor_left f p l ~* l') : hsquare (ap1_gen (ppi_functor_left f p) (eq_of_phomotopy q) (eq_of_phomotopy r)) (ppi_functor f (λa' s, (q a')⁻¹ ⬝ s ⬝ r a') (ppi_eq_equiv_natural_left_gen_lem p q r)) phomotopy_of_eq phomotopy_of_eq := begin intro r, induction r, induction f with f f₀, induction A with A a₀, esimp at * ⊢, induction p, induction k with k k₀, induction k₀, revert l' r, refine phomotopy_rec_idp' _ _, revert k' q, refine phomotopy_rec_idp' _ _, --reflexivity, exact sorry, end definition ppi_eq_equiv_natural_left_gen_sigma {A' A : Type*} {B : A → Type} {f : A' →* A} {b₀ : B pt} {b₀' : B (f pt)} {k l : ppi B b₀} {k' l' : ppi (B ∘ f) b₀'} (p : b₀' =[respect_pt f] b₀) (q : ppi_functor_left f p k ~* k') (r : ppi_functor_left f p l ~* l') : Σ(t : (q pt)⁻¹ ⬝ transport (λx, k x = l x) (respect_pt f)⁻¹ (respect_pt k ⬝ (respect_pt l)⁻¹) ⬝ r pt = respect_pt k' ⬝ (respect_pt l')⁻¹), hsquare (ap1_gen (ppi_functor_left f p) (eq_of_phomotopy q) (eq_of_phomotopy r)) (ppi_functor f (λa' s, (q a')⁻¹ ⬝ s ⬝ r a') t) phomotopy_of_eq phomotopy_of_eq := begin induction f with f f₀, induction A with A a₀, esimp at * ⊢, induction p, induction k with k k₀, induction k₀, revert l' r, refine phomotopy_rec_idp' _ _, revert k' q, refine phomotopy_rec_idp' _ _, fconstructor, exact !con_idp ⬝ !idp_con ⬝ !idp_con ⬝ !idp_con⁻¹ ⬝ !respect_pt_ppi_functor_left⁻¹ ◾ !respect_pt_ppi_functor_left⁻¹⁻², intro r, induction r, transitivity phomotopy.rfl, reflexivity, exact sorry, --transitivity (ppi_functor_left (pmap.mk f idp) ppi.mk k idp ~* ppi.mk k idp), -- exact _ ⬝ _ ◾ _ end definition loop_pppi_pequiv_natural_left {A' A : Type*} (X : A → Type*) (f : A' →* A) : psquare (Ω→ (ppi_compose_right X f)) (ppi_compose_right (Ω ∘ X) f) (loop_pppi_pequiv X) (loop_pppi_pequiv (X ∘ f)) := begin induction A with A a, induction f with f f₀, esimp at (f, f₀), induction f₀, fapply phomotopy.mk, -- do 2 exact sorry --(pmap_compose_ppi_ppi_const (λa, pmap_of_map (f a) pt))(pmap_compose_ppi_ppi_const (λa, pmap_of_map (f a) pt)) { note z := ppi_eq_equiv_natural_left_gen _ (ppi_compose_pmap_ppi_const X (pmap.mk f idp)) (ppi_compose_pmap_ppi_const X (pmap.mk f idp)), exact sorry --exact hvconcat z _ }, { exact sorry /-exact !ppi_eq_equiv_natural_gen_refl ◾ (!idp_con ⬝ !ppi_eq_refl)-/ } end definition loop_ppmap_pequiv2 [constructor] (A B : Type*) : Ω (ppmap A B) ≃* ppmap A (Ω B) := loop_pequiv_loop (pppi_pequiv_ppmap A B)⁻¹ᵉ* ⬝e* loop_pppi_pequiv (λa, B) ⬝e* pppi_pequiv_ppmap A (Ω B) definition loop_ppmap_pequiv2_natural_left {A' A : Type*} (B : Type*) (f : A' →* A) : psquare (Ω→ (ppcompose_right f)) (ppcompose_right f) (loop_ppmap_pequiv2 A B) (loop_ppmap_pequiv2 A' B) := begin exact sorry end definition loop_ppmap_pequiv2_natural_right (A : Type*) {B B' : Type*} (f : B →* B') : psquare (Ω→ (ppcompose_left f)) (ppcompose_left (Ω→ f)) (loop_ppmap_pequiv2 A B) (loop_ppmap_pequiv2 A B') := begin exact sorry end /- Template for defining an equivalence: variables {} definition nar_of_noo [unfold ] (x : foo) : bar := begin induction x, { }, { }, { }, { } end definition noo_of_nar [unfold ] (x : bar) : foo := begin induction x, { }, { }, { }, { } end variables () definition noo_equiv_nar [constructor] : foo ≃ bar := equiv.MK nar_of_noo noo_of_nar abstract begin intro x, induction x, { }, { }, { }, { } end end abstract begin intro x, induction x, { }, { }, { }, { } end end -- apply eq_pathover_id_right, refine ap_compose nar_of_noo _ _ ⬝ ap02 _ !elim_glue ⬝ph _ -- apply eq_pathover_id_right, refine ap_compose noo_of_nar _ _ ⬝ ap02 _ !elim_glue ⬝ph _ ---------------------------------------------------------------------------------------------------- Template for defining a pointed equivalence: variables {} definition nar_of_noo' [unfold ] (x : foo) : bar := begin induction x, { }, { }, { }, { } end definition noo_of_nar' [unfold ] (x : bar) : foo := begin induction x, { }, { }, { }, { } end variables () definition nar_of_noo [constructor] : foo →* bar := pmap.mk nar_of_noo' idp definition noo_of_nar [constructor] : bar →* foo := pmap.mk noo_of_nar' idp definition noo_pequiv_nar [constructor] : foo ≃* bar := pequiv.MK (nar_of_noo _) (noo_of_nar _) abstract begin end end abstract begin end end -- apply eq_pathover_id_right, refine ap_compose nar_of_noo _ _ ⬝ ap02 _ !elim_glue ⬝ph _ -- apply eq_pathover_id_right, refine ap_compose noo_of_nar _ _ ⬝ ap02 _ !elim_glue ⬝ph _ -/ /- begin fapply pequiv_of_equiv, { fapply equiv.MK, { }, { }, { }, { }}, { } end begin induction x, { }, { }, { }, { } end induction x, { }, { }, { }, { } -/
e7d79dd1e52b24e765b5374becd5aae91592ece4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group_with_zero/basic.lean
c15273533447b5b8a0e214c61971dbf278a43074
[]
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
51,241
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.logic.nontrivial import Mathlib.algebra.group.units_hom import Mathlib.algebra.group.inj_surj import Mathlib.algebra.group_with_zero.defs import Mathlib.PostPort universes u_1 u_3 u u_2 u_4 u_5 namespace Mathlib /-! # 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 Various lemmas about `group_with_zero` and `comm_group_with_zero`. To reduce import dependencies, the type-classes themselves are in `algebra.group_with_zero.defs`. ## Implementation details As is usual in mathlib, we extend the inverse function to the zero element, and require `0⁻¹ = 0`. -/ /-- Pullback a `mul_zero_class` instance along an injective function. -/ protected def function.injective.mul_zero_class {M₀ : Type u_1} {M₀' : Type u_3} [mul_zero_class M₀] [Mul M₀'] [HasZero M₀'] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (mul : ∀ (a b : M₀'), f (a * b) = f a * f b) : mul_zero_class M₀' := mul_zero_class.mk Mul.mul 0 sorry sorry /-- Pushforward a `mul_zero_class` instance along an surjective function. -/ protected def function.surjective.mul_zero_class {M₀ : Type u_1} {M₀' : Type u_3} [mul_zero_class M₀] [Mul M₀'] [HasZero M₀'] (f : M₀ → M₀') (hf : function.surjective f) (zero : f 0 = 0) (mul : ∀ (a b : M₀), f (a * b) = f a * f b) : mul_zero_class M₀' := mul_zero_class.mk Mul.mul 0 sorry sorry theorem mul_eq_zero_of_left {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} (h : a = 0) (b : M₀) : a * b = 0 := Eq.symm h ▸ zero_mul b theorem mul_eq_zero_of_right {M₀ : Type u_1} [mul_zero_class M₀] {b : M₀} (a : M₀) (h : b = 0) : a * b = 0 := Eq.symm h ▸ mul_zero a theorem left_ne_zero_of_mul {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} : a * b ≠ 0 → a ≠ 0 := mt fun (h : a = 0) => mul_eq_zero_of_left h b theorem right_ne_zero_of_mul {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a) theorem ne_zero_and_ne_zero_of_mul {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := { left := left_ne_zero_of_mul h, right := right_ne_zero_of_mul h } theorem mul_eq_zero_of_ne_zero_imp_eq_zero {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} (h : a ≠ 0 → b = 0) : a * b = 0 := sorry /-- Pushforward a `no_zero_divisors` instance along an injective function. -/ protected theorem function.injective.no_zero_divisors {M₀ : Type u_1} {M₀' : Type u_3} [Mul M₀] [HasZero M₀] [Mul M₀'] [HasZero M₀'] [no_zero_divisors M₀'] (f : M₀ → M₀') (hf : function.injective f) (zero : f 0 = 0) (mul : ∀ (x y : M₀), f (x * y) = f x * f y) : no_zero_divisors M₀ := sorry theorem eq_zero_of_mul_self_eq_zero {M₀ : Type u_1} [Mul M₀] [HasZero M₀] [no_zero_divisors M₀] {a : M₀} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) id id /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem mul_eq_zero {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b = 0 ↔ a = 0 ∨ b = 0 := { mp := eq_zero_or_eq_zero_of_mul_eq_zero, mpr := fun (o : a = 0 ∨ b = 0) => or.elim o (fun (h : a = 0) => mul_eq_zero_of_left h b) (mul_eq_zero_of_right a) } /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem zero_eq_mul {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : 0 = a * b ↔ a = 0 ∨ b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 = a * b ↔ a = 0 ∨ b = 0)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b = 0 ↔ a = 0 ∨ b = 0)) (propext mul_eq_zero))) (iff.refl (a = 0 ∨ b = 0))) /-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them are nonzero. -/ theorem mul_ne_zero_iff {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := iff.trans (not_congr mul_eq_zero) not_or_distrib theorem mul_ne_zero {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := iff.mpr mul_ne_zero_iff { left := ha, right := hb } /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is `b * a`. -/ theorem mul_eq_zero_comm {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b = 0 ↔ b * a = 0 := iff.trans mul_eq_zero (iff.trans (or_comm (a = 0) (b = 0)) (iff.symm mul_eq_zero)) /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is `b * a`. -/ theorem mul_ne_zero_comm {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b ≠ 0 ↔ b * a ≠ 0 := not_congr mul_eq_zero_comm theorem mul_self_eq_zero {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} : a * a = 0 ↔ a = 0 := sorry theorem zero_eq_mul_self {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} : 0 = a * a ↔ a = 0 := sorry /-- In a nontrivial monoid with zero, zero and one are different. -/ @[simp] theorem zero_ne_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] : 0 ≠ 1 := sorry @[simp] theorem one_ne_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] : 1 ≠ 0 := ne.symm zero_ne_one theorem ne_zero_of_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} (h : a = 1) : a ≠ 0 := trans_rel_right ne h one_ne_zero theorem left_ne_zero_of_mul_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} {b : M₀} (h : a * b = 1) : a ≠ 0 := left_ne_zero_of_mul (ne_zero_of_eq_one h) theorem right_ne_zero_of_mul_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} {b : M₀} (h : a * b = 1) : b ≠ 0 := right_ne_zero_of_mul (ne_zero_of_eq_one h) /-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/ protected theorem pullback_nonzero {M₀ : Type u_1} {M₀' : Type u_3} [monoid_with_zero M₀] [nontrivial M₀] [HasZero M₀'] [HasOne M₀'] (f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' := sorry /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [monoid_with_zero M₀] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀'), f (x * y) = f x * f y) : monoid_with_zero M₀' := monoid_with_zero.mk monoid.mul sorry monoid.one sorry sorry mul_zero_class.zero sorry sorry /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [monoid_with_zero M₀] (f : M₀ → M₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀), f (x * y) = f x * f y) : monoid_with_zero M₀' := monoid_with_zero.mk monoid.mul sorry monoid.one sorry sorry mul_zero_class.zero sorry sorry /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.comm_monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [comm_monoid_with_zero M₀] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀'), f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := comm_monoid_with_zero.mk comm_monoid.mul sorry comm_monoid.one sorry sorry sorry mul_zero_class.zero sorry sorry /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.comm_monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [comm_monoid_with_zero M₀] (f : M₀ → M₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀), f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := comm_monoid_with_zero.mk comm_monoid.mul sorry comm_monoid.one sorry sorry sorry mul_zero_class.zero sorry sorry namespace units /-- An element of the unit group of a nonzero monoid with zero represented as an element of the monoid is nonzero. -/ @[simp] theorem ne_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] (u : units M₀) : ↑u ≠ 0 := left_ne_zero_of_mul_eq_one (mul_inv u) -- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume -- `nonzero M₀`. @[simp] theorem mul_left_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] (u : units M₀) {a : M₀} : a * ↑u = 0 ↔ a = 0 := sorry @[simp] theorem mul_right_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 := sorry end units namespace is_unit theorem ne_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := (fun (_a : is_unit a) => Exists.dcases_on _a fun (w : units M₀) (h : ↑w = a) => idRhs ((fun (_x : M₀) => _x ≠ 0) a) (h ▸ units.ne_zero w)) ha theorem mul_right_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] {a : M₀} {b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 := sorry theorem mul_left_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] {a : M₀} {b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 := sorry end is_unit /-- In a monoid with zero, if zero equals one, then zero is the only element. -/ theorem eq_zero_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] (h : 0 = 1) (a : M₀) : a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a = 0)) (Eq.symm (mul_one a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = 0)) (Eq.symm h))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 0 = 0)) (mul_zero a))) (Eq.refl 0))) /-- In a monoid with zero, if zero equals one, then zero is the unique element. Somewhat arbitrarily, we define the default element to be `0`. All other elements will be provably equal to it, but not necessarily definitionally equal. -/ def unique_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] (h : 0 = 1) : unique M₀ := unique.mk { default := 0 } (eq_zero_of_zero_eq_one h) /-- In a monoid with zero, zero equals one if and only if all elements of that semiring are equal. -/ theorem subsingleton_iff_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] : 0 = 1 ↔ subsingleton M₀ := { mp := fun (h : 0 = 1) => unique.subsingleton, mpr := fun (h : subsingleton M₀) => subsingleton.elim 0 1 } theorem subsingleton_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] : 0 = 1 → subsingleton M₀ := iff.mp subsingleton_iff_zero_eq_one theorem eq_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] (h : 0 = 1) (a : M₀) (b : M₀) : a = b := subsingleton.elim a b @[simp] theorem is_unit_zero_iff {M₀ : Type u_1} [monoid_with_zero M₀] : is_unit 0 ↔ 0 = 1 := sorry @[simp] theorem not_is_unit_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] : ¬is_unit 0 := mt (iff.mp is_unit_zero_iff) zero_ne_one /-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/ theorem zero_ne_one_or_forall_eq_0 (M₀ : Type u_1) [monoid_with_zero M₀] : 0 ≠ 1 ∨ ∀ (a : M₀), a = 0 := not_or_of_imp eq_zero_of_zero_eq_one protected instance cancel_monoid_with_zero.to_no_zero_divisors {M₀ : Type u_1} [cancel_monoid_with_zero M₀] : no_zero_divisors M₀ := no_zero_divisors.mk fun (a b : M₀) (ab0 : a * b = 0) => dite (a = 0) (fun (h : a = 0) => Or.inl h) fun (h : ¬a = 0) => Or.inr (cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h (eq.mpr (id (Eq._oldrec (Eq.refl (a * b = a * 0)) ab0)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 = a * 0)) (mul_zero a))) (Eq.refl 0)))) theorem mul_left_inj' {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} (hc : c ≠ 0) : a * c = b * c ↔ a = b := { mp := mul_right_cancel' hc, mpr := fun (h : a = b) => h ▸ rfl } theorem mul_right_inj' {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} (ha : a ≠ 0) : a * b = a * c ↔ b = c := { mp := mul_left_cancel' ha, mpr := fun (h : b = c) => h ▸ rfl } @[simp] theorem mul_eq_mul_right_iff {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} : a * c = b * c ↔ a = b ∨ c = 0 := sorry @[simp] theorem mul_eq_mul_left_iff {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} : a * b = a * c ↔ b = c ∨ a = 0 := sorry /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.cancel_monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [cancel_monoid_with_zero M₀] [HasZero M₀'] [Mul M₀'] [HasOne M₀'] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀'), f (x * y) = f x * f y) : cancel_monoid_with_zero M₀' := cancel_monoid_with_zero.mk monoid.mul sorry monoid.one sorry sorry mul_zero_class.zero sorry sorry sorry sorry /-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := classical.by_contradiction fun (ha : ¬a = 0) => h₁ (mul_left_cancel' ha (Eq.symm h₂ ▸ Eq.symm (mul_one a))) /-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := classical.by_contradiction fun (ha : ¬a = 0) => h₁ (mul_right_cancel' ha (Eq.symm h₂ ▸ Eq.symm (one_mul a))) theorem division_def {G : Type u} [div_inv_monoid G] (a : G) (b : G) : a / b = a * (b⁻¹) := div_eq_mul_inv /-- Pullback a `group_with_zero` class along an injective function. -/ protected def function.injective.group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) : group_with_zero G₀' := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry has_inv.inv (div_inv_monoid.div._default monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry has_inv.inv) sorry sorry sorry /-- Pullback a `group_with_zero` class along an injective function. This is a version of `function.injective.group_with_zero` that uses a specified `/` instead of the default `a / b = a * b⁻¹`. -/ protected def function.injective.group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀'), f (x / y) = f x / f y) : group_with_zero G₀' := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry sorry sorry /-- Pushforward a `group_with_zero` class along an surjective function. -/ protected def function.surjective.group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) : group_with_zero G₀' := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry has_inv.inv (div_inv_monoid.div._default monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry has_inv.inv) sorry sorry sorry /-- Pushforward a `group_with_zero` class along a surjective function. This is a version of `function.surjective.group_with_zero` that uses a specified `/` instead of the default `a / b = a * b⁻¹`. -/ protected def function.surjective.group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀), f (x / y) = f x / f y) : group_with_zero G₀' := group_with_zero.mk div_inv_monoid.mul sorry div_inv_monoid.one sorry sorry group_with_zero.zero sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry sorry sorry @[simp] theorem mul_inv_cancel_right' {G₀ : Type u_2} [group_with_zero G₀] {b : G₀} (h : b ≠ 0) (a : G₀) : a * b * (b⁻¹) = a := sorry @[simp] theorem mul_inv_cancel_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) (b : G₀) : a * (a⁻¹ * b) = b := sorry theorem inv_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 := sorry @[simp] theorem inv_mul_cancel {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a⁻¹ * a = 1 := sorry @[simp] theorem inv_mul_cancel_right' {G₀ : Type u_2} [group_with_zero G₀] {b : G₀} (h : b ≠ 0) (a : G₀) : a * (b⁻¹) * b = a := sorry @[simp] theorem inv_mul_cancel_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) (b : G₀) : a⁻¹ * (a * b) = b := sorry @[simp] theorem inv_one {G₀ : Type u_2} [group_with_zero G₀] : 1⁻¹ = 1 := sorry @[simp] theorem inv_inv' {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a⁻¹⁻¹ = a := sorry /-- Multiplying `a` by itself and then by its inverse results in `a` (whether or not `a` is zero). -/ @[simp] theorem mul_self_mul_inv {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a * a * (a⁻¹) = a := sorry /-- Multiplying `a` by its inverse and then by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem mul_inv_mul_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a * (a⁻¹) * a = a := sorry /-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a` is zero). -/ @[simp] theorem inv_mul_mul_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a⁻¹ * a * a = a := sorry /-- Multiplying `a` by itself and then dividing by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem mul_self_div_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a * a / a = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * a / a = a)) (div_eq_mul_inv (a * a) a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * a * (a⁻¹) = a)) (mul_self_mul_inv a))) (Eq.refl a)) /-- Dividing `a` by itself and then multiplying by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem div_self_mul_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / a * a = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / a * a = a)) (div_eq_mul_inv a a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a⁻¹) * a = a)) (mul_inv_mul_self a))) (Eq.refl a)) theorem inv_involutive' {G₀ : Type u_2} [group_with_zero G₀] : function.involutive has_inv.inv := inv_inv' theorem eq_inv_of_mul_right_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a * b = 1) : b = (a⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (b = (a⁻¹))) (Eq.symm (inv_mul_cancel_left' (left_ne_zero_of_mul_eq_one h) b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * (a * b) = (a⁻¹))) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * 1 = (a⁻¹))) (mul_one (a⁻¹)))) (Eq.refl (a⁻¹)))) theorem eq_inv_of_mul_left_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a * b = 1) : a = (b⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (a = (b⁻¹))) (Eq.symm (mul_inv_cancel_right' (right_ne_zero_of_mul_eq_one h) a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (b⁻¹) = (b⁻¹))) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 * (b⁻¹) = (b⁻¹))) (one_mul (b⁻¹)))) (Eq.refl (b⁻¹)))) theorem inv_injective' {G₀ : Type u_2} [group_with_zero G₀] : function.injective has_inv.inv := function.involutive.injective inv_involutive' @[simp] theorem inv_inj' {G₀ : Type u_2} [group_with_zero G₀] {g : G₀} {h : G₀} : g⁻¹ = (h⁻¹) ↔ g = h := function.injective.eq_iff inv_injective' theorem inv_eq_iff {G₀ : Type u_2} [group_with_zero G₀] {g : G₀} {h : G₀} : g⁻¹ = h ↔ h⁻¹ = g := eq.mpr (id (Eq._oldrec (Eq.refl (g⁻¹ = h ↔ h⁻¹ = g)) (Eq.symm (propext inv_inj')))) (eq.mpr (id (Eq._oldrec (Eq.refl (g⁻¹⁻¹ = (h⁻¹) ↔ h⁻¹ = g)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (h⁻¹ = (g⁻¹⁻¹) ↔ h⁻¹ = g)) (inv_inv' g))) (iff.refl (h⁻¹ = g)))) @[simp] theorem inv_eq_one' {G₀ : Type u_2} [group_with_zero G₀] {g : G₀} : g⁻¹ = 1 ↔ g = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (g⁻¹ = 1 ↔ g = 1)) (propext inv_eq_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (1⁻¹ = g ↔ g = 1)) inv_one)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 = g ↔ g = 1)) (propext eq_comm))) (iff.refl (g = 1)))) namespace units /-- 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 {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (ha : a ≠ 0) : units G₀ := mk a (a⁻¹) (mul_inv_cancel ha) (inv_mul_cancel ha) @[simp] theorem coe_mk0 {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : ↑(mk0 a h) = a := rfl @[simp] theorem mk0_coe {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) (h : ↑u ≠ 0) : mk0 (↑u) h = u := ext rfl @[simp] theorem coe_inv' {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) : ↑(u⁻¹) = (↑u⁻¹) := eq_inv_of_mul_left_eq_one (inv_mul u) @[simp] theorem mul_inv' {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) : ↑u * (↑u⁻¹) = 1 := mul_inv_cancel (ne_zero u) @[simp] theorem inv_mul' {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) : ↑u⁻¹ * ↑u = 1 := inv_mul_cancel (ne_zero u) @[simp] theorem mk0_inj {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : mk0 a ha = mk0 b hb ↔ a = b := { mp := fun (h : mk0 a ha = mk0 b hb) => mk.inj_arrow h fun (h_1 : a = b) (h_2 : a⁻¹ = (b⁻¹)) => h_1, mpr := fun (h : a = b) => ext h } @[simp] theorem exists_iff_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} : (∃ (u : units G₀), ↑u = x) ↔ x ≠ 0 := sorry end units theorem is_unit.mk0 {G₀ : Type u_2} [group_with_zero G₀] (x : G₀) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx) theorem is_unit_iff_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} : is_unit x ↔ x ≠ 0 := units.exists_iff_ne_zero protected instance group_with_zero.no_zero_divisors {G₀ : Type u_2} [group_with_zero G₀] : no_zero_divisors G₀ := no_zero_divisors.mk fun (a b : G₀) (h : a * b = 0) => imp_of_not_imp_not (a * b = 0) (a = 0 ∨ b = 0) (eq.mpr (id (imp_congr_eq (push_neg.not_or_eq (a = 0) (b = 0)) (Eq.refl (¬a * b = 0)))) (eq.mpr (id (imp_congr_eq ((fun (a a_1 : Prop) (e_1 : a = a_1) (b b_1 : Prop) (e_2 : b = b_1) => congr (congr_arg And e_1) e_2) (¬a = 0) (a ≠ 0) (propext (push_neg.not_eq a 0)) (¬b = 0) (b ≠ 0) (propext (push_neg.not_eq b 0))) (propext (push_neg.not_eq (a * b) 0)))) fun (h : a ≠ 0 ∧ b ≠ 0) => units.ne_zero (units.mk0 a (and.left h) * units.mk0 b (and.right h)))) h protected instance group_with_zero.cancel_monoid_with_zero {G₀ : Type u_2} [group_with_zero G₀] : cancel_monoid_with_zero G₀ := cancel_monoid_with_zero.mk group_with_zero.mul group_with_zero.mul_assoc group_with_zero.one group_with_zero.one_mul group_with_zero.mul_one group_with_zero.zero group_with_zero.zero_mul group_with_zero.mul_zero sorry sorry theorem mul_inv_rev' {G₀ : Type u_2} [group_with_zero G₀] (x : G₀) (y : G₀) : x * y⁻¹ = y⁻¹ * (x⁻¹) := sorry @[simp] theorem div_self {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a / a = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (a / a = 1)) (div_eq_mul_inv a a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a⁻¹) = 1)) (mul_inv_cancel h))) (Eq.refl 1)) @[simp] theorem div_one {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / 1 = a := sorry @[simp] theorem zero_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : 0 / a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 / a = 0)) (div_eq_mul_inv 0 a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 * (a⁻¹) = 0)) (zero_mul (a⁻¹)))) (Eq.refl 0)) @[simp] theorem div_zero {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / 0 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a / 0 = 0)) (div_eq_mul_inv a 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (0⁻¹) = 0)) inv_zero)) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 0 = 0)) (mul_zero a))) (Eq.refl 0))) @[simp] theorem div_mul_cancel {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (div_eq_mul_inv a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) * b = a)) (inv_mul_cancel_right' h a))) (Eq.refl a)) theorem div_mul_cancel_of_imp {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : b = 0 → a = 0) : a / b * b = a := sorry @[simp] theorem mul_div_cancel {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / b = a)) (div_eq_mul_inv (a * b) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (b⁻¹) = a)) (mul_inv_cancel_right' h a))) (Eq.refl a)) theorem mul_div_cancel_of_imp {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : b = 0 → a = 0) : a * b / b = a := sorry @[simp] theorem div_self_mul_self' {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / (a * a) = (a⁻¹) := sorry theorem div_eq_mul_one_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) : a / b = a * (1 / b) := sorry theorem mul_one_div_cancel {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 := sorry theorem one_div_mul_cancel {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : 1 / a * a = 1 := sorry theorem one_div_one {G₀ : Type u_2} [group_with_zero G₀] : 1 / 1 = 1 := div_self (ne.symm zero_ne_one) theorem one_div_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 := sorry theorem eq_one_div_of_mul_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a * b = 1) : b = 1 / a := sorry theorem eq_one_div_of_mul_eq_one_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : b * a = 1) : b = 1 / a := sorry @[simp] theorem one_div_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) : 1 / (a / b) = b / a := sorry theorem one_div_one_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : 1 / (1 / a) = a := sorry theorem eq_of_one_div_eq_one_div {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : 1 / a = 1 / b) : a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (Eq.symm (one_div_one_div a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 / (1 / a) = b)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 / (1 / b) = b)) (one_div_one_div b))) (Eq.refl b))) @[simp] theorem inv_eq_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} : a⁻¹ = 0 ↔ a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ = 0 ↔ a = 0)) (propext inv_eq_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (0⁻¹ = a ↔ a = 0)) inv_zero)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 = a ↔ a = 0)) (propext eq_comm))) (iff.refl (a = 0)))) @[simp] theorem zero_eq_inv {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} : 0 = (a⁻¹) ↔ 0 = a := iff.trans eq_comm (iff.trans inv_eq_zero eq_comm) theorem one_div_mul_one_div_rev {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) : 1 / a * (1 / b) = 1 / (b * a) := sorry theorem divp_eq_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (u : units G₀) : a /ₚ u = a / ↑u := sorry @[simp] theorem divp_mk0 {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div a (units.mk0 b hb) theorem inv_div {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a / b⁻¹ = b / a := sorry theorem inv_div_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a⁻¹ / b = (b * a⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ / b = (b * a⁻¹))) (mul_inv_rev' b a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ / b = a⁻¹ * (b⁻¹))) (div_eq_mul_inv (a⁻¹) b))) (Eq.refl (a⁻¹ * (b⁻¹)))) theorem div_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a / b ≠ 0)) (div_eq_mul_inv a b))) (mul_ne_zero ha (inv_ne_zero hb)) @[simp] theorem div_eq_zero_iff {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a / b = 0 ↔ a = 0 ∨ b = 0 := sorry theorem div_ne_zero_iff {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := iff.trans (not_congr div_eq_zero_iff) not_or_distrib theorem div_left_inj' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hc : c ≠ 0) : a / c = b / c ↔ a = b := sorry theorem div_eq_iff_mul_eq {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hb : b ≠ 0) : a / b = c ↔ c * b = a := sorry theorem eq_div_iff_mul_eq {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hc : c ≠ 0) : a = b / c ↔ a * c = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b / c ↔ a * c = b)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (b / c = a ↔ a * c = b)) (propext (div_eq_iff_mul_eq hc)))) (iff.refl (a * c = b))) theorem div_eq_of_eq_mul {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} (hx : x ≠ 0) {y : G₀} {z : G₀} (h : y = z * x) : y / x = z := iff.mpr (div_eq_iff_mul_eq hx) (Eq.symm h) theorem eq_div_of_mul_eq {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} (hx : x ≠ 0) {y : G₀} {z : G₀} (h : z * x = y) : z = y / x := Eq.symm (div_eq_of_eq_mul hx (Eq.symm h)) theorem eq_of_div_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a / b = 1) : a = b := sorry theorem div_eq_one_iff_eq {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (hb : b ≠ 0) : a / b = 1 ↔ a = b := { mp := eq_of_div_eq_one, mpr := fun (h : a = b) => Eq.symm h ▸ div_self hb } theorem div_mul_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a := sorry theorem mul_div_mul_right {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) {c : G₀} (hc : c ≠ 0) : a * c / (b * c) = a / b := sorry theorem mul_mul_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) := sorry protected instance comm_group_with_zero.comm_cancel_monoid_with_zero {G₀ : Type u_2} [comm_group_with_zero G₀] : comm_cancel_monoid_with_zero G₀ := comm_cancel_monoid_with_zero.mk cancel_monoid_with_zero.mul sorry cancel_monoid_with_zero.one sorry sorry sorry cancel_monoid_with_zero.zero sorry sorry sorry sorry /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀'), f (x / y) = f x / f y) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry /-- Pushforward a `comm_group_with_zero` class along an surjective function. -/ protected def function.surjective.comm_group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry /-- Pushforward a `comm_group_with_zero` class along a surjective function. -/ protected def function.surjective.comm_group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀), f (x / y) = f x / f y) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry theorem mul_inv' {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} : a * b⁻¹ = a⁻¹ * (b⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (a * b⁻¹ = a⁻¹ * (b⁻¹))) (mul_inv_rev' a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b⁻¹ * (a⁻¹) = a⁻¹ * (b⁻¹))) (mul_comm (b⁻¹) (a⁻¹)))) (Eq.refl (a⁻¹ * (b⁻¹)))) theorem one_div_mul_one_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) : 1 / a * (1 / b) = 1 / (a * b) := eq.mpr (id (Eq._oldrec (Eq.refl (1 / a * (1 / b) = 1 / (a * b))) (one_div_mul_one_div_rev a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 / (b * a) = 1 / (a * b))) (mul_comm b a))) (Eq.refl (1 / (a * b)))) theorem div_mul_right {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / (a * b) = 1 / b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * a) = 1 / b)) (div_mul_left ha))) (Eq.refl (1 / b))) theorem mul_div_cancel_left_of_imp {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} (h : a = 0 → b = 0) : a * b / a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / a = b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / a = b)) (mul_div_cancel_of_imp h))) (Eq.refl b)) theorem mul_div_cancel_left {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b := mul_div_cancel_left_of_imp fun (h : a = 0) => false.elim (ha h) theorem mul_div_cancel_of_imp' {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a := eq.mpr (id (Eq._oldrec (Eq.refl (b * (a / b) = a)) (mul_comm b (a / b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (div_mul_cancel_of_imp h))) (Eq.refl a)) theorem mul_div_cancel' {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a := eq.mpr (id (Eq._oldrec (Eq.refl (b * (a / b) = a)) (mul_comm b (a / b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (div_mul_cancel a hb))) (Eq.refl a)) theorem div_mul_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) (d : G₀) : a / b * (c / d) = a * c / (b * d) := sorry theorem mul_div_mul_left {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) {c : G₀} (hc : c ≠ 0) : c * a / (c * b) = a / b := eq.mpr (id (Eq._oldrec (Eq.refl (c * a / (c * b) = a / b)) (mul_comm c a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * c / (c * b) = a / b)) (mul_comm c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * c / (b * c) = a / b)) (mul_div_mul_right a b hc))) (Eq.refl (a / b)))) theorem div_mul_eq_mul_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : b / c * a = b * a / c := sorry theorem div_mul_eq_mul_div_comm {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : b / c * a = b * (a / c) := sorry theorem mul_eq_mul_of_div_eq_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := sorry theorem div_div_eq_mul_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / (b / c) = a * c / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / (b / c) = a * c / b)) (div_eq_mul_one_div a (b / c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (1 / (b / c)) = a * c / b)) (one_div_div b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (c / b) = a * c / b)) (Eq.symm mul_div_assoc))) (Eq.refl (a * c / b)))) theorem div_div_eq_div_mul {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / b / c = a / (b * c) := eq.mpr (id (Eq._oldrec (Eq.refl (a / b / c = a / (b * c))) (div_eq_mul_one_div (a / b) c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * (1 / c) = a / (b * c))) (div_mul_div a b 1 c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 / (b * c) = a / (b * c))) (mul_one a))) (Eq.refl (a / (b * c))))) theorem div_div_div_div_eq {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) {b : G₀} {c : G₀} {d : G₀} : a / b / (c / d) = a * d / (b * c) := sorry theorem div_mul_eq_div_mul_one_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / (b * c) = a / b * (1 / c) := eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * c) = a / b * (1 / c))) (Eq.symm (div_div_eq_div_mul a b c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b / c = a / b * (1 / c))) (Eq.symm (div_eq_mul_one_div (a / b) c)))) (Eq.refl (a / b / c))) /-- Dividing `a` by the result of dividing `a` by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem div_div_self {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) : a / (a / a) = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / (a / a) = a)) (div_div_eq_mul_div a a a))) (mul_self_div_self a) theorem ne_zero_of_one_div_ne_zero {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 := fun (ha : a = 0) => absurd (Eq.refl 0) (eq.mp (Eq._oldrec (Eq.refl (1 / 0 ≠ 0)) (div_zero 1)) (eq.mp (Eq._oldrec (Eq.refl (1 / a ≠ 0)) ha) h)) theorem eq_zero_of_one_div_eq_zero {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (h : 1 / a = 0) : a = 0 := classical.by_cases (fun (ha : a = 0) => ha) fun (ha : ¬a = 0) => false.elim (one_div_ne_zero ha h) theorem div_helper {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (b : G₀) (h : a ≠ 0) : 1 / (a * b) * a = 1 / b := eq.mpr (id (Eq._oldrec (Eq.refl (1 / (a * b) * a = 1 / b)) (div_mul_eq_mul_div a 1 (a * b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 * a / (a * b) = 1 / b)) (one_mul a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (a * b) = 1 / b)) (div_mul_right b h))) (Eq.refl (1 / b)))) theorem div_eq_inv_mul {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} : a / b = b⁻¹ * a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b = b⁻¹ * a)) (div_eq_mul_inv a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) = b⁻¹ * a)) (mul_comm a (b⁻¹)))) (Eq.refl (b⁻¹ * a))) theorem mul_div_right_comm {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a * b / c = a / c * b := sorry theorem mul_comm_div' {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / b * c = a * (c / b) := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * c = a * (c / b))) (Eq.symm mul_div_assoc))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * c = a * c / b)) (mul_div_right_comm a c b))) (Eq.refl (a / b * c))) theorem div_mul_comm' {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / b * c = c / b * a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * c = c / b * a)) (div_mul_eq_mul_div c a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * c / b = c / b * a)) (mul_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (c * a / b = c / b * a)) (mul_div_right_comm c a b))) (Eq.refl (c / b * a)))) theorem mul_div_comm {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a * (b / c) = b * (a / c) := eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / c) = b * (a / c))) (Eq.symm mul_div_assoc))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b / c = b * (a / c))) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / c = b * (a / c))) mul_div_assoc)) (Eq.refl (b * (a / c))))) theorem div_right_comm {G₀ : Type u_2} [comm_group_with_zero G₀] {b : G₀} {c : G₀} (a : G₀) : a / b / c = a / c / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / b / c = a / c / b)) (div_div_eq_div_mul a b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * c) = a / c / b)) (div_div_eq_div_mul a c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * c) = a / (c * b))) (mul_comm b c))) (Eq.refl (a / (c * b))))) theorem div_div_div_cancel_right {G₀ : Type u_2} [comm_group_with_zero G₀] {b : G₀} {c : G₀} (a : G₀) (hc : c ≠ 0) : a / c / (b / c) = a / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / c / (b / c) = a / b)) (div_div_eq_mul_div (a / c) b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / c * c / b = a / b)) (div_mul_cancel a hc))) (Eq.refl (a / b))) theorem div_mul_div_cancel {G₀ : Type u_2} [comm_group_with_zero G₀] {b : G₀} {c : G₀} (a : G₀) (hc : c ≠ 0) : a / c * (c / b) = a / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / c * (c / b) = a / b)) (Eq.symm mul_div_assoc))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / c * c / b = a / b)) (div_mul_cancel a hc))) (Eq.refl (a / b))) theorem div_eq_div_iff {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := sorry theorem div_eq_iff {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hb : b ≠ 0) : a / b = c ↔ a = c * b := iff.trans (div_eq_iff_mul_eq hb) eq_comm theorem eq_div_iff {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hb : b ≠ 0) : c = a / b ↔ c * b = a := eq_div_iff_mul_eq hb theorem div_div_cancel' {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} (ha : a ≠ 0) : a / (a / b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a / (a / b) = b)) (div_eq_mul_inv a (a / b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a / b⁻¹) = b)) inv_div)) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / a) = b)) (mul_div_cancel' b ha))) (Eq.refl b))) namespace semiconj_by @[simp] theorem zero_right {G₀ : Type u_2} [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 := sorry @[simp] theorem zero_left {G₀ : Type u_2} [mul_zero_class G₀] (x : G₀) (y : G₀) : semiconj_by 0 x y := sorry @[simp] theorem inv_symm_left_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} : semiconj_by (a⁻¹) x y ↔ semiconj_by a y x := sorry theorem inv_symm_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} (h : semiconj_by a x y) : semiconj_by (a⁻¹) y x := iff.mpr inv_symm_left_iff' h theorem inv_right' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} (h : semiconj_by a x y) : semiconj_by a (x⁻¹) (y⁻¹) := sorry @[simp] theorem inv_right_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} : semiconj_by a (x⁻¹) (y⁻¹) ↔ semiconj_by a x y := { mp := fun (h : semiconj_by a (x⁻¹) (y⁻¹)) => inv_inv' x ▸ inv_inv' y ▸ inv_right' h, mpr := inv_right' } theorem div_right {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} {x' : G₀} {y' : G₀} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x / x') (y / y') := eq.mpr (id (Eq._oldrec (Eq.refl (semiconj_by a (x / x') (y / y'))) (div_eq_mul_inv x x'))) (eq.mpr (id (Eq._oldrec (Eq.refl (semiconj_by a (x * (x'⁻¹)) (y / y'))) (div_eq_mul_inv y y'))) (mul_right h (inv_right' h'))) end semiconj_by namespace commute @[simp] theorem zero_right {G₀ : Type u_2} [mul_zero_class G₀] (a : G₀) : commute a 0 := semiconj_by.zero_right a @[simp] theorem zero_left {G₀ : Type u_2} [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a @[simp] theorem inv_left_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : commute (a⁻¹) b ↔ commute a b := semiconj_by.inv_symm_left_iff' theorem inv_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : commute a b) : commute (a⁻¹) b := iff.mpr inv_left_iff' h @[simp] theorem inv_right_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : commute a (b⁻¹) ↔ commute a b := semiconj_by.inv_right_iff' theorem inv_right' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : commute a b) : commute a (b⁻¹) := iff.mpr inv_right_iff' h theorem inv_inv' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : commute a b) : commute (a⁻¹) (b⁻¹) := inv_right' (inv_left' h) @[simp] theorem div_right {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hab : commute a b) (hac : commute a c) : commute a (b / c) := semiconj_by.div_right hab hac @[simp] theorem div_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hac : commute a c) (hbc : commute b c) : commute (a / b) c := eq.mpr (id (Eq._oldrec (Eq.refl (commute (a / b) c)) (div_eq_mul_inv a b))) (mul_left hac (inv_left' hbc)) end commute namespace monoid_with_zero_hom theorem map_ne_zero {M₀ : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [monoid_with_zero M₀] [nontrivial M₀] (f : monoid_with_zero_hom G₀ M₀) {a : G₀} : coe_fn f a ≠ 0 ↔ a ≠ 0 := { mp := fun (hfa : coe_fn f a ≠ 0) (ha : a = 0) => hfa (Eq.symm ha ▸ map_zero f), mpr := fun (ha : a ≠ 0) => is_unit.ne_zero (is_unit.map (to_monoid_hom f) (is_unit.mk0 a ha)) } @[simp] theorem map_eq_zero {M₀ : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [monoid_with_zero M₀] [nontrivial M₀] (f : monoid_with_zero_hom G₀ M₀) {a : G₀} : coe_fn f a = 0 ↔ a = 0 := iff.mp not_iff_not (map_ne_zero f) /-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/ @[simp] theorem map_inv' {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [group_with_zero G₀'] (f : monoid_with_zero_hom G₀ G₀') (a : G₀) : coe_fn f (a⁻¹) = (coe_fn f a⁻¹) := sorry @[simp] theorem map_div {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [group_with_zero G₀'] (f : monoid_with_zero_hom G₀ G₀') (a : G₀) (b : G₀) : coe_fn f (a / b) = coe_fn f a / coe_fn f b := sorry end monoid_with_zero_hom @[simp] theorem monoid_hom.map_units_inv {M : Type u_1} {G₀ : Type u_2} [monoid M] [group_with_zero G₀] (f : M →* G₀) (u : units M) : coe_fn f ↑(u⁻¹) = (coe_fn f ↑u⁻¹) := sorry /-- Constructs a `group_with_zero` structure on a `monoid_with_zero` consisting only of units and 0. -/ def group_with_zero_of_is_unit_or_eq_zero {M : Type u_5} [nontrivial M] [hM : monoid_with_zero M] (h : ∀ (a : M), is_unit a ∨ a = 0) : group_with_zero M := group_with_zero.mk monoid_with_zero.mul monoid_with_zero.mul_assoc monoid_with_zero.one monoid_with_zero.one_mul monoid_with_zero.mul_one monoid_with_zero.zero monoid_with_zero.zero_mul monoid_with_zero.mul_zero (fun (a : M) => dite (a = 0) (fun (h0 : a = 0) => 0) fun (h0 : ¬a = 0) => ↑(is_unit.unit sorry⁻¹)) (div_inv_monoid.div._default monoid_with_zero.mul monoid_with_zero.mul_assoc monoid_with_zero.one monoid_with_zero.one_mul monoid_with_zero.mul_one fun (a : M) => dite (a = 0) (fun (h0 : a = 0) => 0) fun (h0 : ¬a = 0) => ↑(is_unit.unit sorry⁻¹)) nontrivial.exists_pair_ne sorry sorry /-- Constructs a `comm_group_with_zero` structure on a `comm_monoid_with_zero` consisting only of units and 0. -/ def comm_group_with_zero_of_is_unit_or_eq_zero {M : Type u_5} [nontrivial M] [hM : comm_monoid_with_zero M] (h : ∀ (a : M), is_unit a ∨ a = 0) : comm_group_with_zero M := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry comm_monoid_with_zero.mul_comm group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry
bd2986eb6728919f28786e11590267a43956f8de
abbfc359cee49d3c5258b2bbedc2b4d306ec3bdf
/src/data/serial/medium.lean
0a3fa704bf299786025dbfd9155370ac45632b01
[]
no_license
cipher1024/serialean
565b17241ba7edc4ee564bf0ae175dd15b06a28c
47881e4a6bc0a62cd68520564610b75f8a4fef2c
refs/heads/master
1,585,117,575,599
1,535,783,976,000
1,535,783,976,000
143,501,396
0
0
null
null
null
null
UTF-8
Lean
false
false
14,416
lean
import tactic import logic.basic import category.serial import category.liftable import category.liftable.serial universes u v inductive put_m' (α : Type u) | pure : α → put_m' | write : unsigned → (unit → put_m') → put_m' def put_m'.bind {α β} : put_m' α → (α → put_m' β) → put_m' β | (put_m'.pure x) f := f x | (put_m'.write w f) g := put_m'.write w $ λ u, put_m'.bind (f u) g instance : monad put_m' := { pure := λ α, put_m'.pure , bind := @put_m'.bind } instance : is_lawful_monad put_m' := by { refine { .. }; intros; try { refl }; induction x; try { refl }; { dsimp [put_m'.bind] at *, congr, simp * } } @[reducible] def put_m := put_m' punit def put_m.eval : put_m → list unsigned | (put_m'.pure x) := [] | (put_m'.write w f) := w :: put_m.eval (f punit.star) inductive get_m : Type u → Type (u+1) | fail {α} : get_m α | pure {α} : α → get_m α | read {α} : (unsigned → get_m α) → get_m α | loop {α β γ : Type u} : (β → unsigned → get_m (α ⊕ β)) → (α → get_m γ) → β → get_m γ def get_m.bind : Π {α β}, get_m α → (α → get_m β) → get_m β | _ _ (get_m.fail) _ := get_m.fail | _ _ (get_m.pure x) f := f x | _ _ (get_m.read f) g := get_m.read $ λ w, get_m.bind (f w) g | _ _ (get_m.loop f g x₀) h := get_m.loop f (λ r, get_m.bind (g r) h) x₀ def get_m.map : Π {α β : Type u}, (α → β) → get_m α → get_m β | _ _ _ (get_m.fail) := get_m.fail | _ _ f (get_m.pure x) := get_m.pure $ f x | _ _ f (get_m.read g) := get_m.read $ λ w, get_m.map f (g w) | _ _ h (get_m.loop f g x₀) := get_m.loop f (λ r, get_m.map h (g r)) x₀ instance : functor get_m.{u} := { map := @get_m.map } def get_m.seq {α β : Type u} : Π (f : get_m (α → β)) (x : get_m α), get_m β := λ (f : get_m (α → β)) (x : get_m α), get_m.bind f (λ f, f <$> x) -- instance : applicative get_m := -- { to_functor := get_m.functor -- , pure := λ α, get_m.pure -- , seq := @get_m.seq } open function instance : is_lawful_functor.{u} get_m := by { constructor; intros; dsimp [(<$>),get_m.seq]; induction x; try { refl }; simp [get_m.map,*]; ext } instance : monad get_m := { to_functor := get_m.functor , pure := @get_m.pure , bind := @get_m.bind } instance : is_lawful_monad get_m.{u} := { to_is_lawful_functor := get_m.is_lawful_functor, bind_assoc := by { intros, dsimp [(>>=)], induction x; try { refl }; simp [get_m.bind,*], }, bind_pure_comp_eq_map := by { intros, dsimp [(>>=),(<$>)], induction x; try {refl}; simp [get_m.bind,get_m.map,*], }, map_pure := by intros; refl, pure_seq_eq_map := by { intros, dsimp [(>>=),(<$>)], induction x; try {refl}; simp [get_m.bind,get_m.map,*], }, pure_bind := by intros; refl } def get_m.eval {α} : list unsigned → get_m α → option α | [] (get_m.pure x) := pure x | [] _ := none | (w :: ws) (get_m.read f) := get_m.eval ws (f w) | (w :: ws) (get_m.loop f g x₀) := get_m.eval ws $ f x₀ w >>= @sum.rec _ _ (λ _, get_m α) g (get_m.loop f g) | (w :: ws) _ := none def read_write : Π {α}, get_m.{u} α → put_m.{u} → option α | ._ (get_m.pure x) (put_m'.pure _) := some x | _ _ (put_m'.pure _) := none | ._ (get_m.read f) (put_m'.write w g) := read_write (f w) (g punit.star) | α (@get_m.loop α' β γ f g x₀) (put_m'.write w h) := read_write (f x₀ w >>= @sum.rec α' β (λ _, get_m α) g (get_m.loop f g)) (h punit.star) | _ _ (put_m'.write w g) := none def read_write' : Π {α}, get_m α → put_m → option (α × put_m) | _ (get_m.read f) (put_m'.write w g) := read_write' (f w) (g punit.star) | α (@get_m.loop α' β γ f g x₀) (put_m'.write w h) := read_write' (f x₀ w >>= @sum.rec α' β (λ _, get_m α) g (get_m.loop f g)) (h punit.star) -- | _ (get_m.pure x) m@(put_m'.write w g) := some (x,m) | _ (get_m.pure x) m := some (x,m) | _ _ (put_m'.pure _) := none | _ (get_m.fail) (put_m'.write _ _) := none -- | _ _ m := none lemma read_read_write_write {α} (x : get_m α) (m : put_m) (i : α) : read_write x m = some i ↔ read_write' x m = some (i,pure punit.star) := begin induction m generalizing x; cases x; casesm* punit; simp [read_write,read_write',prod.ext_iff,pure,*], end def pipeline {α} (x : get_m α) (y : α → put_m) (i : α) : option α := read_write x (y i) infix ` -<< `:60 := read_write infix ` -<<< `:60 := read_write' infix ` <-< `:60 := pipeline lemma eq_star (x : punit) : x = punit.star := by cases x; refl -- inductive agree : Π {α} (x : α), get_m α → put_m → put_m → Prop -- | pure {α} (x : α) (m : put_m) : agree x (get_m.pure x) m m -- | read_write {α} (x : α) (w : unsigned) -- (f : unsigned → get_m α) (g : punit → put_m) (m : put_m) : -- agree x (f w) (g punit.star) m → -- agree x (get_m.read f) (put_m'.write w g) m -- | loop_write {α} (x : α) {β γ} (σ₀ σ₁ : β) (w : unsigned) -- (f : β → unsigned → get_m (γ ⊕ β)) (f' : γ → get_m α) -- (g : punit → put_m) (m m' : put_m) : -- agree (sum.inr σ₁) (f σ₀ w) (g punit.star) m' → -- agree x (get_m.loop σ₁ f f') m' m → -- agree x (get_m.loop σ₀ f f') (put_m'.write w g) m -- | loop_exit_write {α} (x : α) {β γ} (σ₀ : β) (r : γ) (w : unsigned) -- (f : β → unsigned → get_m (γ ⊕ β)) (f' : γ → get_m α) -- (g : punit → put_m) (m m' : put_m) : -- agree (sum.inl r) (f σ₀ w) (g punit.star) m' → -- agree x (f' r) m' m → -- agree x (get_m.loop σ₀ f f') (put_m'.write w g) m -- lemma agree_spec {α} (g : get_m α) (m : put_m) (x : α) : -- agree x g m (put_m'.pure punit.star) ↔ g -<< m = some x := -- begin -- split; intro h, -- { cases h, -- refl, simp [read_write], } -- end -- lemma loop_bind {α β γ} (i : β) -- (body : β → unsigned → get_m (α ⊕ β)) (f₀ : α → get_m γ) : -- get_m.loop i body f₀ = get_m.read (body i) >>= _ := _ lemma read_write_loop_bind {α β γ φ : Type u} (i : α) (body : α → unsigned → get_m (φ ⊕ α)) (f₀ : φ → get_m β) (f₁ : β → get_m γ) (m : punit → put_m) (w : unsigned) : (get_m.loop body f₀ i >>= f₁) -<<< put_m'.write w m = (body i w >>= @sum.rec φ α (λ _, get_m β) f₀ (get_m.loop body f₀) >>= f₁) -<<< m punit.star := begin rw bind_assoc, simp [(>>=),get_m.bind,read_write'], congr, ext, cases x; simp; refl, end -- lemma read_write_left_overs_bind {α} (i : α) -- (x₀ : get_m α) -- (x₁ x₂ : put_m) : -- x₀ -<<< x₁ = some (i,x₂) → lemma fail_read_write {α} (x₁ : put_m) : get_m.fail -<<< x₁ = @none (α × put_m) := by cases x₁; refl lemma pure_read_write {α} (x₁ : put_m) (i : α) : get_m.pure i -<<< x₁ = some (i, x₁) := by cases x₁; refl lemma read_write_left_overs_bind {α} (f : punit → put_m) (i : α) (x₀ : get_m α) (x₁ x₂ : put_m) : x₀ -<<< x₁ = some (i,x₂) → x₀ -<<< (x₁ >>= f) = some (i,x₂ >>= f) := begin induction x₁ generalizing x₀ x₂, cases x₀; simp [(>>=),put_m'.bind,read_write',pure_read_write], { intros, subst x₂, tauto }, cases x₀; simp [(>>=),put_m'.bind,read_write'], { intros, substs x₂ i, split; refl }, { apply x₁_ih, }, { apply x₁_ih, }, end lemma option_eq_forall_some {α} (x y : option α) : x = y ↔ ∀ z, x = some z ↔ y = some z := begin split; intro h, { rw h; intro, refl }, { cases y, cases x, refl, symmetry, rw ← h, rw h, }, end lemma read_write_weakening {α} (x₀ x₁ : put_m) (y₀ y₁ : get_m α) (h : y₀ -<<< x₀ = y₁ -<<< x₁) : y₀ -<< x₀ = y₁ -<< x₁ := begin rw option_eq_forall_some, intro, simp [read_read_write_write,h], end lemma read_write_mono' {α β} (i : α) (x₀ : get_m α) (f₀ : α → get_m β) (x₁ x₂ : put_m) (h : x₀ -<<< x₁ = some (i,x₂)) : (x₀ >>= f₀) -<<< x₁ = f₀ i -<<< x₂ := begin -- simp [(>>=)], induction x₁ generalizing x₀ f₀; try { cases x₀; cases h }, { simp [(>>=),read_write',get_m.bind] }, { cases x₀; try { cases h }, simp [(>>=),read_write',get_m.bind] at h ⊢, simp [(>>=),read_write',get_m.bind] at h ⊢, { apply x₁_ih, assumption }, simp [read_write_loop_bind,x₁_ih], rw [x₁_ih _ _ _ h], } end lemma read_write_mono {α β} {i : α} {x₀ : get_m α} {f₀ : α → get_m β} {x₁ : put_m} {f₁ : punit → put_m} (h : x₀ -<< x₁ = some i) : (x₀ >>= f₀) -<< (x₁ >>= f₁) = f₀ i -<< f₁ punit.star := begin apply read_write_weakening, apply read_write_mono', rw [read_read_write_write] at h, replace h := read_write_left_overs_bind f₁ _ _ _ _ h, simp [h], end lemma read_write_mono_left {α β} {i : α} {x₀ : get_m α} {f₀ : α → get_m β} {x₁ : put_m} (h : x₀ -<< x₁ = some i) : (x₀ >>= f₀) -<< x₁ = f₀ i -<< pure punit.star := by rw ← read_write_mono h; simp lemma read_write_eq_eval_eval {α} (x₀ : get_m α) (x₁ : put_m) : x₀ -<< x₁ = x₀.eval x₁.eval := begin induction x₁ generalizing x₀; cases x₀; try { refl }, simp! [*,read_write], simp! [*,read_write], end open ulift lemma get_m.fold_bind {α β} (x : get_m α) (f : α → get_m β) : get_m.bind x f = x >>= f := rfl lemma map_read_write {α β} (f : α → β) (x : get_m α) (y : put_m) : (f <$> x) -<< y = f <$> (x -<< y) := begin rw [← bind_pure_comp_eq_map,← bind_pure_comp_eq_map], symmetry, simp [(>>=)], induction y generalizing x, { cases x; refl }, { cases x; simp [read_write]; try { refl }; simp [get_m.bind,read_write,y_ih], congr' 1, cases h : x_a x_a_2 y_a, refl, cases a; refl, dsimp [(>>=),get_m.bind], congr, ext, simp [get_m.fold_bind], rw bind_assoc, congr, ext z, cases z; refl, simp [get_m.fold_bind], rw bind_assoc, congr, ext x, cases x; refl, } end def sum_ulift (α β : Type u) : (α ⊕ β) ≃ (ulift.{v} α ⊕ ulift.{v} β) := (equiv.sum_congr equiv.ulift.symm equiv.ulift.symm) -- def get_m.up : Π {α : Type u} {β : Type.{max u v}} (Heq : α ≃ β), get_m α → get_m β -- | _ _ Heq (get_m.pure x) := get_m.pure $ Heq x -- | _ _ Heq (get_m.fail) := get_m.fail -- | _ _ Heq (get_m.read f) := get_m.read (λ w, get_m.up Heq (f w)) -- | _ β' Heq (@get_m.loop α β γ f g x) := -- get_m.loop -- (λ a b, get_m.up (sum_ulift α β) (f (down.{v} a) b)) -- (λ w, get_m.up Heq (g $ down w)) -- (up.{v} x) def get_m.up : Π {α : Type u} {β : Type.{max u v}} (Heq : α → β), get_m α → get_m β := λ α β f x, (@get_m.rec_on (λ α _, Π β, (α → β) → get_m β) α x (λ α β f, get_m.fail) (λ α x β f, get_m.pure $ f x) (λ α next get_m_up β f, get_m.read $ λ w, get_m_up w _ f) (λ α β γ body rest x₀ get_m_up₀ get_m_up₁ β' f, get_m.loop (λ a b, get_m_up₀ (down a) b (ulift.{v} α ⊕ ulift.{v} β) (sum_ulift α β)) (λ r, get_m_up₁ (down r) _ f) (up x₀)) β f) section eqns variables {α β' γ : Type u} {β : Type.{max u v}} (Heq : α → β) (x : get_m α) variables {i : α} {f : unsigned → get_m α} variables {f' : β' → unsigned → get_m (γ ⊕ β')} variables {g' : γ → get_m α} {j : β'} @[simp] lemma get_m.up.eqn_1 : get_m.up Heq (get_m.pure i) = get_m.pure (Heq i) := rfl @[simp] lemma get_m.up.eqn_2 : get_m.up Heq (get_m.fail) = get_m.fail := rfl @[simp] lemma get_m.up.eqn_3 : get_m.up Heq (get_m.read f) = get_m.read (λ w, get_m.up Heq (f w)) := rfl @[simp] lemma get_m.up.eqn_4 : get_m.up Heq (get_m.loop f' g' j) = get_m.loop (λ a b, get_m.up (sum_ulift γ β') (f' (down.{v} a) b)) (λ w, get_m.up Heq (g' $ down w)) (up.{v} j) := rfl end eqns def put_m.up {α : Type u} {β : Type v} (Heq : α → β) : put_m' α → put_m' β | (put_m'.pure x) := put_m'.pure $ Heq x | (put_m'.write w f) := put_m'.write w $ λ u, put_m.up $ f u instance : liftable1 put_m'.{u} put_m'.{v} := { up := λ α β (eq : α ≃ β) x, put_m.up eq x , down := λ α β (eq : α ≃ β) x, put_m.up eq.symm x , down_up := by intros; induction x; simp [put_m.up,*] , up_down := by intros; induction x; simp [put_m.up,*] } open pliftable (up') lemma up_bind {α β : Type u} {β' : Type (max u v)} (x : get_m α) (g : α → get_m β) (f : β → β') : (x >>= g).up f = x.up up.{v} >>= (λ i : ulift α, (g $ down i).up f) := begin dsimp [(>>=)], induction x generalizing f g; try { refl }; simp [get_m.bind,*] end lemma equiv_bind {m} [monad m] [is_lawful_monad m] {α α' β} (Heq : α ≃ α') (x : m α) (f : α → m β) : x >>= f = (Heq <$> x) >>= f ∘ Heq.symm := by simp [(∘)] with functor_norm def sum.map {α α' β β'} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' | (sum.inr x) := sum.inr $ g x | (sum.inl x) := sum.inl $ f x def equiv.ulift_sum {α β} : (ulift $ α ⊕ β) ≃ (ulift α ⊕ ulift β) := { to_fun := λ x, sum.map up up (down x), inv_fun := λ x, up $ sum.map down down x, right_inv := by intro; casesm* [_ ⊕ _,ulift _]; refl, left_inv := by intro; casesm* [_ ⊕ _,ulift _]; refl } lemma map_get_m_up {α : Type u} {β γ} (x : get_m α) (f : α → β) (g : β → γ) : g <$> get_m.up f x = get_m.up (g ∘ f) x := begin dsimp [(<$>)], induction x; simp [get_m.map,*]; refl, end lemma up_read_write {α : Type u} {α' : Type (max u v)} (x : get_m α) (y : put_m) (f : α ≃ α') : x.up f -<< up' y = liftable1.up f (x -<< y) := begin dsimp [up',liftable1.up], induction y generalizing x f, cases x; simp; refl, cases x; simp [up',liftable.up',liftable1.up,read_write,put_m.up,*], refl, refl, refl, rw [read_write,← y_ih,up_bind], apply congr, { apply congr_arg, rw equiv_bind (@equiv.ulift_sum.{u u v v v} x_α x_β) , congr, { rw map_get_m_up, congr, ext, cases x; refl }, simp [(∘)], ext, cases x; dsimp [equiv.ulift_sum,sum.map], refl, cases x, refl, apply_instance }, congr, end lemma up_read_write' {α : Type u} {α' : Type (max u v)} {x : get_m α} {y : put_m} (f : α → α') (f' : α ≃ α') (h : ∀ i, f i = f' i) : x.up f -<< up' y = liftable1.up f' (x -<< y) := begin rw ← up_read_write, congr, ext, apply h end
633303e2a532f9ab1254d7a692e944bd00d71111
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/tactic/core.lean
e3e86b4369906110ae7ea78e221c035c29094f26
[ "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
99,424
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import control.basic import data.dlist.basic import meta.expr import system.io import tactic.binder_matching import tactic.interactive_expr import tactic.lean_core_docs import tactic.project_dir universe u attribute [derive [has_reflect, decidable_eq]] tactic.transparency -- Rather than import data.prod.lex here, we can get away with defining the order by hand. instance : has_lt pos := { lt := λ x y, x.line < y.line ∨ x.line = y.line ∧ x.column < y.column } 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 end tactic open tactic namespace expr /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Convert a list of expressions to an expression denoting the list of those expressions. -/ meta def of_list (α : expr) : list expr → tactic expr | [] := tactic.mk_app ``list.nil [α] | (x :: xs) := do exs ← of_list xs, tactic.mk_app ``list.cons [α, x, exs] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace name /-- `pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm` or (recusively) in any declarations occurring in the value of `nm` with namespace `pre`. Auxiliary function for `name.contains_sorry`. -/ meta def contains_sorry_aux (pre : name) : name → tactic bool | nm := do env ← get_env, decl ← get_decl nm, ff ← return decl.value.contains_sorry | return tt, (decl.value.list_names_with_prefix pre).mfold ff $ λ n b, if b then return tt else n.contains_sorry_aux /-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`). See also `expr.contains_sorry`. -/ meta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm end name namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function export interaction_monad (get_state set_state run_with_state) /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.dedup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expressions are not necessarily in whnf. -/ meta def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr) := prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- Given an expression `f` (likely a binary operation) and a further expression `x`, calling `list_binary_operands f x` breaks `x` apart into successions of applications of `f` until this can no longer be done and returns a list of the leaves of the process. This matches `f` up to semireducible unification. In particular, it will match applications of the same polymorphic function with different type-class arguments. E.g., if `i1` and `i2` are both instances of `has_add T` and `e := has_add.add T i1 x (has_add.add T i2 y z)`, then ``list_binary_operands `((+) : T → T → T) e`` returns `[x, y, z]`. For example: ```lean #eval list_binary_operands `(@has_add.add ℕ _) `(3 + (4 * 5 + 6) + 7 / 3) >>= tactic.trace -- [3, 4 * 5, 6, 7 / 3] #eval list_binary_operands `(@list.append ℕ) `([1, 2] ++ [3, 4] ++ (1 :: [])) >>= tactic.trace -- [[1, 2], [3, 4], [1]] ``` -/ meta def list_binary_operands (f : expr) : expr → tactic (list expr) | x@(expr.app (expr.app g a) b) := do some _ ← try_core (unify f g) | pure [x], as ← list_binary_operands a, bs ← list_binary_operands b, pure (as ++ bs) | a := pure [a] -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [reflected _ α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-- `get_univ_level t` returns the universe level of a type `t` -/ meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) : tactic level := do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive | fail "get_univ_level: argument is not a type", return u /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := do ctx ← unsafe.type_context.get_local_context.run, (some decl) ← pure $ ctx.get_local_decl e.local_uniq_name | fail format!"is_local_def: {e} is not a local constant", when decl.value.is_none $ fail format!"is_local_def: {e} is not a local definition" /-- Returns the local definitions from the context. A local definition is a local constant of the form `e : α := t`. The local definitions are returned in the order in which they appear in the context. -/ meta def local_defs : tactic (list expr) := do ctx ← unsafe.type_context.get_local_context.run, ctx' ← local_context, ctx'.mfilter $ λ h, do (some decl) ← pure $ ctx.get_local_decl h.local_uniq_name | fail format!"local_defs: local {h} not found in the local context", pure decl.value.is_some /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and substitute `t` for `h`. This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (h : expr) : tactic unit := do e ← do { -- we first find the variable being substituted away t ← infer_type h, let (f, args) := t.get_app_fn_args, if (f.const_name = `eq ∨ f.const_name = `heq) then do { let lhs := args.inth 1, let rhs := args.ilast, if rhs.is_local_constant then return rhs else if lhs.is_local_constant then return lhs else fail "subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." } else return h }, success_if_fail (is_local_def e) <|> fail format!("Cannot substitute variable {e.local_pp_name}, " ++ "it is a local definition. If you really want to do this, use `clear_value` first."), subst h /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Given the name of a user attribute, produces a list of `tactic expr`s, each of which is the application of `i_to_expr_for_apply` to a declaration with that attribute. -/ meta def resolve_attribute_expr_list (attr_name : name) : tactic (list (tactic expr)) := do l ← attribute.get_instances attr_name, list.map i_to_expr_for_apply <$> list.reverse <$> l.mmap resolve_name /--`apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given as names of attributes) and `the tactic assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (args : list pexpr) (attrs : list name) (n : nat) (opt : apply_cfg) : tactic unit := do attr_exprs ← lock_tactic_state $ attrs.mfoldl (λ l n, list.append l <$> resolve_attribute_expr_list n) [], let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs, -- `args_exprs` is a list of `tactic expr`, rather than just `expr`, because these expressions will -- be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt args_exprs) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- A version of `lean.parser.many` that requires at least `n` items -/ meta def repeat_at_least {α : Type} (p : lean.parser α) : ℕ → lean.parser (list α) | 0 := many p | (n + 1) := list.cons <$> p <*> repeat_at_least n /-- A version of `lean.parser.sep_by` that allows trailing delimiters, but requires at least one item. Like `lean.parser.sep_by`, as a result of the `lean.parser` monad not being pure, this is only well-behaved if `p` and `s` are backtrackable; which in practice means they must not consume the input when they do not have a match. -/ meta def sep_by_trailing {α : Type} (s : lean.parser unit) (p : lean.parser α) : lean.parser (list α) := do fst ← p, some () ← optional s | pure [fst], some rest ← optional sep_by_trailing | pure [fst], pure (fst :: rest) /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do env ← get_env, n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, set_env env, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }}", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. The `aggressive` argument controls whether the instance is added globally, where it has low priority, or in the local context, where it has very high priority. -/ meta def classical (aggressive : bool := ff) : tactic unit := if aggressive then do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache else do -- Turn on the `prop_decidable` instance. `9` is what we use in the `classical` locale tactic.set_basic_attribute `instance `classical.prop_decidable ff (some 9) open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open _root_.lean open _root_.lean.parser open _root_.interactive _root_.interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean _root_.interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of any project. Requires as argument any declaration name `n` in that project, and `k`, the number of characters in the path of the file where `n` is declared not part of the `src` directory. Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`. Note: does not work in the file where `n` is declared. -/ meta def get_project_dir (n : name) (k : ℕ) : tactic string := do e ← get_env, s ← e.decl_olean n <|> fail!"Did not find declaration {n}. This command does not work in the file where {n} is declared.", return $ s.popn_back k /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := get_project_dir `mathlib_dir_locator 23 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail! "name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute. If the user attribute has a parameter, the default value will be used. This tactic raises an error if there is no `inhabited` instance for the parameter type. -/ meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%`(c_name) default %%`(persistent)) <|> fail! ("Cannot set attribute @[{attr_name}].\n" ++ "The corresponding user attribute {user_attr_nm} " ++ "has a parameter without a default value.\n" ++ "Solution: provide an `inhabited` instance."), tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
1e2b22edd2706463c37726b10d9782d9da176b48
0d2e44896897eda703992595d71a0b19ed30b8a1
/uexp/src/uexp/rules/pullConstantThroughUnion3.lean
442593fcf5a0e45b307eeb5a0ac28ebe53db1b91
[ "BSD-2-Clause" ]
permissive
wwombat/Cosette
a87312aabefdb53ea8b67c37731bd58c7485afb6
4c5dc6172e24d3546c9818ac1fad06f72fe1c991
refs/heads/master
1,619,479,568,051
1,520,292,502,000
1,520,292,502,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,946
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int constant integer_2: const int constant integer_3: const int theorem Rule: forall (Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL (((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (table rel_emp) )) :SQL Γ _) = denoteSQL ((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (((SELECT1 (e2p (constantExpr integer_2)) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (e2p (constantExpr integer_2)) FROM1 (table rel_emp) ))) ) : SQL Γ _):= begin intros, unfold_all_denotations, funext, simp, sorry end
06b78e08a38c7c3a81633d5c4ffcf8d20fd6ca4f
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/limits/limits.lean
7f5d43c153b025c40cf1c844023d3944a350cfab
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
6,727
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton, Mario Carneiro import category_theory.limits.shape import category_theory.filtered open category_theory namespace category_theory.limits universes u v w variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 section limit variables {J : Type v} [𝒥 : small_category J] include 𝒥 class is_limit {F : J ⥤ C} (t : cone F) := (lift : ∀ (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), (lift s ≫ t.π j) = s.π j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, (m ≫ t.π j) = s.π j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp,search] is_limit.fac restate_axiom is_limit.uniq' attribute [search,back'] is_limit.uniq @[extensionality] lemma is_limit.ext {F : J ⥤ C} {t : cone F} (P Q : is_limit t) : P = Q := begin tactic.unfreeze_local_instances, cases P, cases Q, congr, obviously end lemma is_limit.univ {F : J ⥤ C} {t : cone F} [is_limit t] (s : cone F) (φ : s.X ⟶ t.X) : (∀ j, φ ≫ t.π j = s.π j) ↔ (φ = is_limit.lift t s) := by obviously def is_limit.of_lift_univ {F : J ⥤ C} {t : cone F} (lift : Π (s : cone F), s.X ⟶ t.X) (univ : Π (s : cone F) (φ : s.X ⟶ t.X), (∀ j : J, (φ ≫ t.π j) = s.π j) ↔ (φ = lift s)) : is_limit t := { lift := lift, fac' := λ s j, ((univ s (lift s)).mpr (eq.refl (lift s))) j, uniq' := begin obviously, apply univ_s_m.mp, obviously, end } end limit section colimit variables {J : Type v} [𝒥 : small_category J] include 𝒥 class is_colimit {F : J ⥤ C} (t : cocone F) := (desc : ∀ (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), (t.ι j ≫ desc s) = s.ι j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, (t.ι j ≫ m) = s.ι j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp,search] is_colimit.fac restate_axiom is_colimit.uniq' attribute [search,back'] is_colimit.uniq @[extensionality] lemma is_colimit.ext {F : J ⥤ C} {t : cocone F} (P Q : is_colimit t) : P = Q := begin tactic.unfreeze_local_instances, cases P, cases Q, congr, obviously end lemma is_colimit.univ {F : J ⥤ C} {t : cocone F} [is_colimit t] (s : cocone F) (φ : t.X ⟶ s.X) : (∀ j, t.ι j ≫ φ = s.ι j) ↔ (φ = is_colimit.desc t s) := by obviously def is_colimit.of_desc_univ {F : J ⥤ C} {t : cocone F} (desc : Π (s : cocone F), t.X ⟶ s.X) (univ : Π (s : cocone F) (φ : t.X ⟶ s.X), (∀ j : J, (t.ι j ≫ φ) = s.ι j) ↔ (φ = desc s)) : is_colimit t := { desc := desc, fac' := λ s j, ((univ s (desc s)).mpr (eq.refl (desc s))) j, uniq' := begin obviously, apply univ_s_m.mp, obviously, end } end colimit variable (C) class has_limits := (limit : Π {J : Type v} [𝒥 : small_category J] (F : J ⥤ C), cone F) (is_limit : Π {J : Type v} [𝒥 : small_category J] (F : J ⥤ C), is_limit (limit F) . obviously) class has_filtered_limits := (limit : Π {J : Type v} [𝒥 : small_category J] [filtered.{v v} J] (F : J ⥤ C), cone F) (is_limit : Π {J : Type v} [𝒥 : small_category J] [filtered.{v v} J] (F : J ⥤ C), is_limit (limit F) . obviously) -- also do finite limits? variable {C} section variables [has_limits.{u v} C] {J : Type v} [𝒥 : small_category J] include 𝒥 def limit.cone (F : J ⥤ C) : cone F := has_limits.limit.{u v} F def limit (F : J ⥤ C) := (limit.cone F).X def limit.π (F : J ⥤ C) (j : J) : limit F ⟶ F j := (limit.cone F).π j instance limit.universal_property (F : J ⥤ C) : is_limit (limit.cone F) := has_limits.is_limit.{u v} C F def limit.lift (F : J ⥤ C) (c : cone F) : c.X ⟶ limit F := is_limit.lift _ c -- @[simp] def limit.universal_property_lift (F : J ⥤ C) (c : cone F) : (limit.universal_property F).lift c = limit.lift F c := rfl @[simp] def limit.lift_π (F : J ⥤ C) (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π j := is_limit.fac _ c j -- FIXME why the @? @[simp] lemma limit.cone_π (F : J ⥤ C) (j : J) : (limit.cone F).π j = (@limit.π C _ _ J _ F j) := rfl -- TODO needs a home def cone.pullback {F : J ⥤ C} (A : cone F) {X : C} (f : X ⟶ A.X) : cone F := { X := X, π := λ j, f ≫ A.π j } -- lemma limit.pullback_lift (F : J ⥤ C) (c : cone F) {X : C} (f : X ⟶ c.X) : f ≫ limit.lift F c = limit.lift F (c.pullback f) := sorry def limit.map (F G : J ⥤ C) (α : F ⟹ G) : limit F ⟶ limit G := is_limit.lift _ { X := _, π := λ j, limit.π F j ≫ α j } section variables {K : Type v} [𝒦 : small_category K] include 𝒦 def limit.pre (F : J ⥤ C) (E : K ⥤ J) : limit F ⟶ limit (E ⋙ F) := @is_limit.lift _ _ _ _ _ (limit.cone (E ⋙ F)) _ { X := limit F, π := λ k, limit.π F (E k) } end section variables {D : Type u} [𝒟 : category.{u v} D] [has_limits.{u v} D] include 𝒟 def limit.post (F : J ⥤ C) (G : C ⥤ D) : G (limit F) ⟶ limit (F ⋙ G) := @is_limit.lift _ _ _ _ _ (limit.cone (F ⋙ G)) _ { X := _, π := λ j, G.map (limit.π F j) } end @[extensionality] def limit.hom_ext {F : J ⥤ C} {c : cone F} (f g : c.X ⟶ limit F) (w_f : ∀ j, f ≫ limit.π F j = c.π j) (w_g : ∀ j, g ≫ limit.π F j = c.π j) : f = g := begin have p_f := is_limit.uniq _ c f (by obviously), have p_g := is_limit.uniq _ c g (by obviously), obviously, end end variable (C) class has_colimits := (colimit : Π {J : Type v} [𝒥 : small_category J] (F : J ⥤ C), cocone F) (is_colimit : Π {J : Type v} [𝒥 : small_category J] (F : J ⥤ C), is_colimit (colimit F) . obviously) class has_filtered_colimits := (colimit : Π {J : Type v} [𝒥 : small_category J] [filtered.{v v} J] (F : J ⥤ C), cocone F) (is_colimit : Π {J : Type v} [𝒥 : small_category J] [filtered.{v v} J] (F : J ⥤ C), is_colimit (colimit F) . obviously) variable {C} section variables [has_colimits.{u v} C] {J : Type v} [𝒥 : small_category J] include 𝒥 def colimit.cocone (F : J ⥤ C) : cocone F := has_colimits.colimit.{u v} F def colimit (F : J ⥤ C) := (colimit.cocone F).X def colimit.ι (F : J ⥤ C) (j : J) : F j ⟶ colimit F := (colimit.cocone F).ι j instance colimit.universal_property (F : J ⥤ C) : is_colimit (colimit.cocone F) := has_colimits.is_colimit.{u v} C F @[extensionality] def colimit.hom_ext {F : J ⥤ C} {c : cocone F} (f g : colimit F ⟶ c.X) (w_f : ∀ j, colimit.ι F j ≫ f = c.ι j) (w_g : ∀ j, colimit.ι F j ≫ g = c.ι j) : f = g := begin have p_f := is_colimit.uniq _ c f (by obviously), have p_g := is_colimit.uniq _ c g (by obviously), obviously, end end end category_theory.limits
3339a9702a172f0b6222883e8438797d72da2b4d
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/linear/yoneda.lean
c8b3cb3dd8a5fac1f679eba142672f1a93d5c11a
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,893
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.basic import category_theory.linear import category_theory.preadditive.additive_functor import category_theory.preadditive.yoneda /-! # The Yoneda embedding for `R`-linear categories The Yoneda embedding for `R`-linear categories `C`, sends an object `X : C` to the `Module R`-valued presheaf on `C`, with value on `Y : Cᵒᵖ` given by `Module.of R (unop Y ⟶ X)`. TODO: `linear_yoneda R C` is `R`-linear. TODO: In fact, `linear_yoneda` itself is additive and `R`-linear. -/ universes w v u open opposite namespace category_theory variables (R : Type w) [ring R] (C : Type u) [category.{v} C] [preadditive C] [linear R C] /-- The Yoneda embedding for `R`-linear categories `C`, sending an object `X : C` to the `Module R`-valued presheaf on `C`, with value on `Y : Cᵒᵖ` given by `Module.of R (unop Y ⟶ X)`. -/ @[simps] def linear_yoneda : C ⥤ Cᵒᵖ ⥤ Module R := { obj := λ X, { obj := λ Y, Module.of R (unop Y ⟶ X), map := λ Y Y' f, linear.left_comp R _ f.unop, map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y, linear.right_comp R _ f }, map_id' := λ X, by { ext, simp }, -- `obviously` provides these, but slowly map_comp' := λ _ _ _ f g, by { ext, simp } } /-- The Yoneda embedding for `R`-linear categories `C`, sending an object `Y : Cᵒᵖ` to the `Module R`-valued copresheaf on `C`, with value on `X : C` given by `Module.of R (unop Y ⟶ X)`. -/ @[simps] def linear_coyoneda : Cᵒᵖ ⥤ C ⥤ Module R := { obj := λ Y, { obj := λ X, Module.of R (unop Y ⟶ X), map := λ Y Y', linear.right_comp _ _, map_id' := λ Y, by { ext, exact category.comp_id _ }, map_comp' := λ _ _ _ f g, by { ext, exact eq.symm (category.assoc _ _ _) } }, map := λ Y Y' f, { app := λ X, linear.left_comp _ _ f.unop }, map_id' := λ X, by { ext, simp }, -- `obviously` provides these, but slowly map_comp' := λ _ _ _ f g, by { ext, simp } } instance linear_yoneda_obj_additive (X : C) : ((linear_yoneda R C).obj X).additive := {} instance linear_coyoneda_obj_additive (Y : Cᵒᵖ) : ((linear_coyoneda R C).obj Y).additive := {} @[simp] lemma whiskering_linear_yoneda : linear_yoneda R C ⋙ (whiskering_right _ _ _).obj (forget (Module.{v} R)) = yoneda := rfl @[simp] lemma whiskering_linear_yoneda₂ : linear_yoneda R C ⋙ (whiskering_right _ _ _).obj (forget₂ (Module.{v} R) AddCommGroup.{v}) = preadditive_yoneda := rfl @[simp] lemma whiskering_linear_coyoneda : linear_coyoneda R C ⋙ (whiskering_right _ _ _).obj (forget (Module.{v} R)) = coyoneda := rfl @[simp] lemma whiskering_linear_coyoneda₂ : linear_coyoneda R C ⋙ (whiskering_right _ _ _).obj (forget₂ (Module.{v} R) AddCommGroup.{v}) = preadditive_coyoneda := rfl instance linear_yoneda_full : full (linear_yoneda R C) := let yoneda_full : full (linear_yoneda R C ⋙ (whiskering_right _ _ _).obj (forget (Module.{v} R))) := yoneda.yoneda_full in by exactI full.of_comp_faithful (linear_yoneda R C) (((whiskering_right _ _ _)).obj (forget (Module.{v} R))) instance linear_coyoneda_full : full (linear_coyoneda R C) := let coyoneda_full : full (linear_coyoneda R C ⋙ (whiskering_right _ _ _).obj (forget (Module.{v} R))) := coyoneda.coyoneda_full in by exactI full.of_comp_faithful (linear_coyoneda R C) (((whiskering_right _ _ _)).obj (forget (Module.{v} R))) instance linear_yoneda_faithful : faithful (linear_yoneda R C) := faithful.of_comp_eq (whiskering_linear_yoneda R C) instance linear_coyoneda_faithful : faithful (linear_coyoneda R C) := faithful.of_comp_eq (whiskering_linear_coyoneda R C) end category_theory
4ee9b1d7b149fdc88142f0633bc0b5d655fc057e
69bc7d0780be17e452d542a93f9599488f1c0c8e
/10-1-2019.lean
2217db0ff1a0a7cff89b8b5fc811b129d28f05d1
[]
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
2,164
lean
-- Notes 10/1/2019 /- Let's look at our "roadmap:" - literal terms - values (nat, string, bool, etc.) - lambda expressions - represent "total functions" (has values for every possible input in domain) - type names - first-class type system means types themselves are terms - allows for generalization over types - (list nat) type can be imagined as a function from Type → Type - identifier terms - function application -/ -- Notes on polymorphism -- nat specific box inductive boxed_nat | box : nat → boxed_nat def unbox_nat : boxed_nat → nat | (boxed_nat.box x) := x -- "Box" type that generalizes over some type α inductive boxed (T : Type) : Type | box : T → boxed #check boxed -- boxed is a function which "takes" in one type and returns another type open boxed def test : boxed nat := box 2 #check test -- "boxed ℕ" -- polymorphic function to unbox any type -- note that we have to use the "c-style" syntax here, as we need to refer to the name T in the function's type definition def unbox (T : Type) : (boxed T) → T | (box x) := x -- I don't think it's possible to express this using multiple lambdas #eval unbox nat test -- "nat" provides value for type argument T def mybox := box 23 -- boxed ℕ def inception_box := box mybox -- boxed (boxed ℕ) #check inception_box #check unbox _ inception_box -- we can infer the type here, so why even bother? -- when we use brackets, the type-checker infers a value for T "invisibly" def smart_unbox {T: Type} : (boxed T) → T | (box x) := x #check smart_unbox inception_box -- Note on import statmeents: -- import .boxed -- imports local file boxed.lean -- we can now execute tests on our boxed datatypes -- How do we deal with partial functions? -- Define some "maybe" datatype that represents when we have a meaningful response inductive maybe (T : Type) : Type | some : T → maybe | none : maybe def double_if_positive : nat → (maybe nat) := λ (n: nat), if n > 0 then (maybe.some (n * 2)) else (maybe.none nat) #reduce double_if_positive 2 #reduce double_if_positive 0
2e4a5cec08cf242e70add562d7681ecf8fc135fd
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/function/ess_sup.lean
4db07fd96da472f3d9097d1b3e53860285143af1
[ "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
7,340
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.measure.measure_space import order.filter.ennreal /-! # Essential supremum and infimum We define the essential supremum and infimum of a function `f : α → β` with respect to a measure `μ` on `α`. The essential supremum is the infimum of the constants `c : β` such that `f x ≤ c` almost everywhere. TODO: The essential supremum of functions `α → ℝ≥0∞` is used in particular to define the norm in the `L∞` space (see measure_theory/lp_space.lean). There is a different quantity which is sometimes also called essential supremum: the least upper-bound among measurable functions of a family of measurable functions (in an almost-everywhere sense). We do not define that quantity here, which is simply the supremum of a map with values in `α →ₘ[μ] β` (see measure_theory/ae_eq_fun.lean). ## Main definitions * `ess_sup f μ := μ.ae.limsup f` * `ess_inf f μ := μ.ae.liminf f` -/ open measure_theory filter open_locale ennreal measure_theory variables {α β : Type*} {m : measurable_space α} {μ ν : measure α} section conditionally_complete_lattice variable [conditionally_complete_lattice β] /-- Essential supremum of `f` with respect to measure `μ`: the smallest `c : β` such that `f x ≤ c` a.e. -/ def ess_sup {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.limsup f /-- Essential infimum of `f` with respect to measure `μ`: the greatest `c : β` such that `c ≤ f x` a.e. -/ def ess_inf {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.liminf f lemma ess_sup_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_sup f μ = ess_sup g μ := limsup_congr hfg lemma ess_inf_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_inf f μ = ess_inf g μ := @ess_sup_congr_ae α (order_dual β) _ _ _ _ _ hfg end conditionally_complete_lattice section complete_lattice variable [complete_lattice β] @[simp] lemma ess_sup_measure_zero {m : measurable_space α} {f : α → β} : ess_sup f (0 : measure α) = ⊥ := le_bot_iff.mp (Inf_le (by simp [set.mem_set_of_eq, eventually_le, ae_iff])) @[simp] lemma ess_inf_measure_zero {m : measurable_space α} {f : α → β} : ess_inf f (0 : measure α) = ⊤ := @ess_sup_measure_zero α (order_dual β) _ _ _ lemma ess_sup_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_sup f μ ≤ ess_sup g μ := limsup_le_limsup hfg lemma ess_inf_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_inf f μ ≤ ess_inf g μ := liminf_le_liminf hfg lemma ess_sup_const (c : β) (hμ : μ ≠ 0) : ess_sup (λ x : α, c) μ = c := begin haveI hμ_ne_bot : μ.ae.ne_bot, { rwa [ne_bot_iff, ne.def, ae_eq_bot] }, exact limsup_const c, end lemma ess_sup_le_of_ae_le {f : α → β} (c : β) (hf : f ≤ᵐ[μ] (λ _, c)) : ess_sup f μ ≤ c := begin refine (ess_sup_mono_ae hf).trans _, by_cases hμ : μ = 0, { simp [hμ], }, { rwa ess_sup_const, }, end lemma ess_inf_const (c : β) (hμ : μ ≠ 0) : ess_inf (λ x : α, c) μ = c := @ess_sup_const α (order_dual β) _ _ _ _ hμ lemma le_ess_inf_of_ae_le {f : α → β} (c : β) (hf : (λ _, c) ≤ᵐ[μ] f) : c ≤ ess_inf f μ := @ess_sup_le_of_ae_le α (order_dual β) _ _ _ _ c hf lemma ess_sup_const_bot : ess_sup (λ x : α, (⊥ : β)) μ = (⊥ : β) := limsup_const_bot lemma ess_inf_const_top : ess_inf (λ x : α, (⊤ : β)) μ = (⊤ : β) := liminf_const_top lemma order_iso.ess_sup_apply {m : measurable_space α} {γ} [complete_lattice γ] (f : α → β) (μ : measure α) (g : β ≃o γ) : g (ess_sup f μ) = ess_sup (λ x, g (f x)) μ := begin refine order_iso.limsup_apply g _ _ _ _, all_goals { is_bounded_default, }, end lemma order_iso.ess_inf_apply {m : measurable_space α} {γ} [complete_lattice γ] (f : α → β) (μ : measure α) (g : β ≃o γ) : g (ess_inf f μ) = ess_inf (λ x, g (f x)) μ := @order_iso.ess_sup_apply α (order_dual β) _ _ (order_dual γ) _ _ _ g.dual lemma ess_sup_mono_measure {f : α → β} (hμν : ν ≪ μ) : ess_sup f ν ≤ ess_sup f μ := begin refine limsup_le_limsup_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _, all_goals { is_bounded_default, }, end lemma ess_inf_antitone_measure {f : α → β} (hμν : μ ≪ ν) : ess_inf f ν ≤ ess_inf f μ := begin refine liminf_le_liminf_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _, all_goals { is_bounded_default, }, end lemma ess_sup_smul_measure {f : α → β} {c : ℝ≥0∞} (hc : c ≠ 0) : ess_sup f (c • μ) = ess_sup f μ := begin simp_rw ess_sup, suffices h_smul : (c • μ).ae = μ.ae, by rw h_smul, ext1, simp_rw mem_ae_iff, simp [hc], end end complete_lattice section complete_linear_order variable [complete_linear_order β] lemma ae_lt_of_ess_sup_lt {f : α → β} {x : β} (hf : ess_sup f μ < x) : ∀ᵐ y ∂μ, f y < x := filter.eventually_lt_of_limsup_lt hf lemma ae_lt_of_lt_ess_inf {f : α → β} {x : β} (hf : x < ess_inf f μ) : ∀ᵐ y ∂μ, x < f y := @ae_lt_of_ess_sup_lt α (order_dual β) _ _ _ _ _ hf lemma ess_sup_indicator_eq_ess_sup_restrict [has_zero β] {s : set α} {f : α → β} (hf : 0 ≤ᵐ[μ.restrict s] f) (hs : measurable_set s) (hs_not_null : μ s ≠ 0) : ess_sup (s.indicator f) μ = ess_sup f (μ.restrict s) := begin refine le_antisymm _ (Limsup_le_Limsup_of_le (map_restrict_ae_le_map_indicator_ae hs) (by is_bounded_default) (by is_bounded_default)), refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_restrict_le, _), rw eventually_map at h_restrict_le ⊢, rw ae_restrict_iff' hs at h_restrict_le, have hc : 0 ≤ c, { suffices : ∃ x, 0 ≤ f x ∧ f x ≤ c, by { obtain ⟨x, hx⟩ := this, exact hx.1.trans hx.2, }, refine frequently.exists _, { exact μ.ae, }, rw [eventually_le, ae_restrict_iff' hs] at hf, have hs' : ∃ᵐ x ∂μ, x ∈ s, { contrapose! hs_not_null, rw [not_frequently, ae_iff] at hs_not_null, suffices : {a : α | ¬a ∉ s} = s, by rwa ← this, simp, }, refine hs'.mp (hf.mp (h_restrict_le.mono (λ x hxs_imp_c hxf_nonneg hxs, _))), rw pi.zero_apply at hxf_nonneg, exact ⟨hxf_nonneg hxs, hxs_imp_c hxs⟩, }, refine h_restrict_le.mono (λ x hxc, _), by_cases hxs : x ∈ s, { simpa [hxs] using hxc hxs, }, { simpa [hxs] using hc, }, end end complete_linear_order namespace ennreal variables {f : α → ℝ≥0∞} lemma ae_le_ess_sup (f : α → ℝ≥0∞) : ∀ᵐ y ∂μ, f y ≤ ess_sup f μ := eventually_le_limsup f @[simp] lemma ess_sup_eq_zero_iff : ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := limsup_eq_zero_iff lemma ess_sup_const_mul {a : ℝ≥0∞} : ess_sup (λ (x : α), a * (f x)) μ = a * ess_sup f μ := limsup_const_mul lemma ess_sup_add_le (f g : α → ℝ≥0∞) : ess_sup (f + g) μ ≤ ess_sup f μ + ess_sup g μ := limsup_add_le f g lemma ess_sup_liminf_le {ι} [encodable ι] [linear_order ι] (f : ι → α → ℝ≥0∞) : ess_sup (λ x, at_top.liminf (λ n, f n x)) μ ≤ at_top.liminf (λ n, ess_sup (λ x, f n x) μ) := by { simp_rw ess_sup, exact ennreal.limsup_liminf_le_liminf_limsup (λ a b, f b a), } end ennreal
6a70aef015e1fe0f703ca07f784303bb1a0a7c40
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/category_theory/preadditive/additive_functor.lean
dab8053d2162bba9381b8d0a724a403b2d51171d
[ "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
4,847
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.preadditive import category_theory.limits.shapes.biproducts /-! # Additive Functors A functor between two preadditive categories is called *additive* provided that the induced map on hom types is a morphism of abelian groups. An additive functor between preadditive categories creates and preserves biproducts. # Implementation details `functor.additive` is a `Prop`-valued class, defined by saying that for every two objects `X` and `Y`, the map `F.map : (X ⟶ Y) → (F.obj X ⟶ F.obj Y)` is a morphism of abelian groups. # Project: - Prove that a functor is additive if it preserves finite biproducts (See https://stacks.math.columbia.edu/tag/010M.) -/ namespace category_theory /-- A functor `F` is additive provided `F.map` is an additive homomorphism. -/ class functor.additive {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) : Prop := (map_zero' : Π {X Y : C}, F.map (0 : X ⟶ Y) = 0 . obviously) (map_add' : Π {X Y : C} {f g : X ⟶ Y}, F.map (f + g) = F.map f + F.map g . obviously) section preadditive namespace functor section variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) [functor.additive F] @[simp] lemma map_zero {X Y : C} : F.map (0 : X ⟶ Y) = 0 := functor.additive.map_zero' @[simp] lemma map_add {X Y : C} {f g : X ⟶ Y} : F.map (f + g) = F.map f + F.map g := functor.additive.map_add' instance : additive (𝟭 C) := {} instance {E : Type*} [category E] [preadditive E] (G : D ⥤ E) [functor.additive G] : additive (F ⋙ G) := {} /-- `F.map_add_hom` is an additive homomorphism whose underlying function is `F.map`. -/ @[simps] def map_add_hom {X Y : C} : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y) := { to_fun := λ f, F.map f, map_zero' := F.map_zero, map_add' := λ _ _, F.map_add } lemma coe_map_add_hom {X Y : C} : ⇑(F.map_add_hom : (X ⟶ Y) →+ _) = @map C _ D _ F X Y := rfl @[simp] lemma map_neg {X Y : C} {f : X ⟶ Y} : F.map (-f) = - F.map f := F.map_add_hom.map_neg _ @[simp] lemma map_sub {X Y : C} {f g : X ⟶ Y} : F.map (f - g) = F.map f - F.map g := F.map_add_hom.map_sub _ _ open_locale big_operators @[simp] lemma map_sum {X Y : C} {α : Type*} (f : α → (X ⟶ Y)) (s : finset α) : F.map (∑ a in s, f a) = ∑ a in s, F.map (f a) := (F.map_add_hom : (X ⟶ Y) →+ _).map_sum f s end section induced_category variables {C : Type*} {D : Type*} [category D] [preadditive D] (F : C → D) instance induced_functor_additive : functor.additive (induced_functor F) := {} end induced_category section -- To talk about preservation of biproducts we need to specify universes explicitly. noncomputable theory universes v u₁ u₂ variables {C : Type u₁} {D : Type u₂} [category.{v} C] [category.{v} D] [preadditive C] [preadditive D] (F : C ⥤ D) [functor.additive F] open category_theory.limits /-- An additive functor between preadditive categories creates finite biproducts. -/ instance map_has_biproduct {J : Type v} [fintype J] [decidable_eq J] (f : J → C) [has_biproduct f] : has_biproduct (λ j, F.obj (f j)) := has_biproduct_of_total { X := F.obj (⨁ f), π := λ j, F.map (biproduct.π f j), ι := λ j, F.map (biproduct.ι f j), ι_π := λ j j', by { simp only [←F.map_comp], split_ifs, { subst h, simp, }, { simp [h], }, }, } (by simp_rw [←F.map_comp, ←F.map_sum, biproduct.total, functor.map_id]) /-- An additive functor between preadditive categories preserves finite biproducts. -/ -- This essentially repeats the work of the previous instance, -- but gives good definitional reduction to `biproduct.lift` and `biproduct.desc`. @[simps] def map_biproduct {J : Type v} [fintype J] [decidable_eq J] (f : J → C) [has_biproduct f] : F.obj (⨁ f) ≅ ⨁ (λ j, F.obj (f j)) := { hom := biproduct.lift (λ j, F.map (biproduct.π f j)), inv := biproduct.desc (λ j, F.map (biproduct.ι f j)), hom_inv_id' := by simp only [biproduct.lift_desc, ←F.map_comp, ←F.map_sum, biproduct.total, F.map_id], inv_hom_id' := begin ext j j', simp only [category.comp_id, category.assoc, biproduct.lift_π, biproduct.ι_desc_assoc, ←F.map_comp, biproduct.ι_π, F.map_dite, dif_ctx_congr, eq_to_hom_map, F.map_zero], end } end end functor namespace equivalence variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] instance inverse_additive (e : C ≌ D) [e.functor.additive] : e.inverse.additive := { map_zero' := λ X Y, by { apply e.functor.map_injective, simp, }, map_add' := λ X Y f g, by { apply e.functor.map_injective, simp, }, } end equivalence end preadditive end category_theory
d60f148e88650add7aa5bee2adbe2ff8692aaab9
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/pnat/factors.lean
a4c8a0e14b7aaf2baaff0547be9b1ff240911eed
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
14,493
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import data.pnat.prime import data.multiset.sort import data.int.gcd import algebra.group /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_add_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≤ v → u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p ::ₘ 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_injective : function.injective (coe : prime_multiset → multiset ℕ) := multiset.map_injective nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = (p : ℕ) ::ₘ 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } /-- Converts a `prime_multiset` to a `multiset ℕ+`. -/ def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_injective : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.map_injective nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = (p : ℕ+) ::ₘ 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } /-- The product of a `prime_multiset`, as a `ℕ+`. -/ def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := ((monoid_hom.of coe).map_multiset_prod v.to_pnat_multiset), rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := by { change multiset.prod ((p : ℕ+) ::ₘ 0) = (p : ℕ+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } /-- If a `multiset ℕ` consists only of primes, it can be recast as a `prime_multiset`. -/ def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] /-- If a `multiset ℕ+` consists only of primes, it can be recast as a `prime_multiset`. -/ def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } /-- If a `list ℕ+` consists only of primes, it can be recast as a `prime_multiset` with the coercion from lists to multisets. -/ def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset → multiset ℕ+)], rw [multiset.prod_add] } theorem prod_smul (d : ℕ) (u : prime_multiset) : (d • u).prod = u.prod ^ d := by { induction d with d ih, refl, rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.prime_of_mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.prime_of_mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_injective, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with ⟨l⟩, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := by simp [factor_multiset, prime_multiset.of_nat_list, prime_multiset.of_nat_multiset] theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = m • (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd.intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_self_add } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_nsmul, prime_multiset.card_of_prime, mul_one] }, { have : ∀ (m : ℕ), m • (p ::ₘ 0) = multiset.repeat p m := λ m, by {induction m with m ih, { refl }, rw [succ_nsmul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
80292d3feb0139774bb2800e78196283e085789c
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/preserves/opposites.lean
115f22c3421311d474b19632023571d1c811bb02
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,001
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.opposites import category_theory.limits.preserves.finite /-! # Limit preservation properties of `functor.op` and related constructions We formulate conditions about `F` which imply that `F.op`, `F.unop`, `F.left_op` and `F.right_op` preserve certain (co)limits. ## Future work * Dually, it is possible to formulate conditions about `F.op` ec. for `F` to preserve certain (co)limits. -/ universes w w' v₁ v₂ u₁ u₂ noncomputable theory open category_theory namespace category_theory.limits section variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] variables {J : Type w} [category.{w'} J] /-- If `F : C ⥤ D` preserves colimits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of `K : J ⥤ Cᵒᵖ`. -/ def preserves_limit_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ D) [preserves_colimit K.left_op F] : preserves_limit K F.op := { preserves := λ c hc, is_limit_cone_right_op_of_cocone _ (is_colimit_of_preserves F (is_colimit_cocone_left_op_of_cone _ hc)) } /-- If `F : C ⥤ Dᵒᵖ` preserves colimits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.left_op : Cᵒᵖ ⥤ D` preserves limits of `K : J ⥤ Cᵒᵖ`. -/ def preserves_limit_left_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ Dᵒᵖ) [preserves_colimit K.left_op F] : preserves_limit K F.left_op := { preserves := λ c hc, is_limit_cone_unop_of_cocone _ (is_colimit_of_preserves F (is_colimit_cocone_left_op_of_cone _ hc)) } /-- If `F : Cᵒᵖ ⥤ D` preserves colimits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves limits of `K : J ⥤ C`. -/ def preserves_limit_right_op (K : J ⥤ C) (F : Cᵒᵖ ⥤ D) [preserves_colimit K.op F] : preserves_limit K F.right_op := { preserves := λ c hc, is_limit_cone_right_op_of_cocone _ (is_colimit_of_preserves F (is_colimit_cone_op _ hc)) } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.unop : C ⥤ D` preserves limits of `K : J ⥤ C`. -/ def preserves_limit_unop (K : J ⥤ C) (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_colimit K.op F] : preserves_limit K F.unop := { preserves := λ c hc, is_limit_cone_unop_of_cocone _ (is_colimit_of_preserves F (is_colimit_cone_op _ hc)) } /-- If `F : C ⥤ D` preserves limits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of `K : J ⥤ Cᵒᵖ`. -/ def preserves_colimit_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ D) [preserves_limit K.left_op F] : preserves_colimit K F.op := { preserves := λ c hc, is_colimit_cocone_right_op_of_cone _ (is_limit_of_preserves F (is_limit_cone_left_op_of_cocone _ hc)) } /-- If `F : C ⥤ Dᵒᵖ` preserves limits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.left_op : Cᵒᵖ ⥤ D` preserves colimits of `K : J ⥤ Cᵒᵖ`. -/ def preserves_colimit_left_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ Dᵒᵖ) [preserves_limit K.left_op F] : preserves_colimit K F.left_op := { preserves := λ c hc, is_colimit_cocone_unop_of_cone _ (is_limit_of_preserves F (is_limit_cone_left_op_of_cocone _ hc)) } /-- If `F : Cᵒᵖ ⥤ D` preserves limits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves colimits of `K : J ⥤ C`. -/ def preserves_colimit_right_op (K : J ⥤ C) (F : Cᵒᵖ ⥤ D) [preserves_limit K.op F] : preserves_colimit K F.right_op := { preserves := λ c hc, is_colimit_cocone_right_op_of_cone _ (is_limit_of_preserves F (is_limit_cocone_op _ hc)) } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.unop : C ⥤ D` preserves colimits of `K : J ⥤ C`. -/ def preserves_colimit_unop (K : J ⥤ C) (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_limit K.op F] : preserves_colimit K F.unop := { preserves := λ c hc, is_colimit_cocone_unop_of_cone _ (is_limit_of_preserves F (is_limit_cocone_op _ hc)) } section variables (J) /-- If `F : C ⥤ D` preserves colimits of shape `Jᵒᵖ`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of shape `J`. -/ def preserves_limits_of_shape_op (F : C ⥤ D) [preserves_colimits_of_shape Jᵒᵖ F] : preserves_limits_of_shape J F.op := { preserves_limit := λ K, preserves_limit_op K F } /-- If `F : C ⥤ Dᵒᵖ` preserves colimits of shape `Jᵒᵖ`, then `F.left_op : Cᵒᵖ ⥤ D` preserves limits of shape `J`. -/ def preserves_limits_of_shape_left_op (F : C ⥤ Dᵒᵖ) [preserves_colimits_of_shape Jᵒᵖ F] : preserves_limits_of_shape J F.left_op := { preserves_limit := λ K, preserves_limit_left_op K F } /-- If `F : Cᵒᵖ ⥤ D` preserves colimits of shape `Jᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves limits of shape `J`. -/ def preserves_limits_of_shape_right_op (F : Cᵒᵖ ⥤ D) [preserves_colimits_of_shape Jᵒᵖ F] : preserves_limits_of_shape J F.right_op := { preserves_limit := λ K, preserves_limit_right_op K F } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of shape `Jᵒᵖ`, then `F.unop : C ⥤ D` preserves limits of shape `J`. -/ def preserves_limits_of_shape_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_colimits_of_shape Jᵒᵖ F] : preserves_limits_of_shape J F.unop := { preserves_limit := λ K, preserves_limit_unop K F } /-- If `F : C ⥤ D` preserves limits of shape `Jᵒᵖ`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of shape `J`. -/ def preserves_colimits_of_shape_op (F : C ⥤ D) [preserves_limits_of_shape Jᵒᵖ F] : preserves_colimits_of_shape J F.op := { preserves_colimit := λ K, preserves_colimit_op K F } /-- If `F : C ⥤ Dᵒᵖ` preserves limits of shape `Jᵒᵖ`, then `F.left_op : Cᵒᵖ ⥤ D` preserves colimits of shape `J`. -/ def preserves_colimits_of_shape_left_op (F : C ⥤ Dᵒᵖ) [preserves_limits_of_shape Jᵒᵖ F] : preserves_colimits_of_shape J F.left_op := { preserves_colimit := λ K, preserves_colimit_left_op K F } /-- If `F : Cᵒᵖ ⥤ D` preserves limits of shape `Jᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves colimits of shape `J`. -/ def preserves_colimits_of_shape_right_op (F : Cᵒᵖ ⥤ D) [preserves_limits_of_shape Jᵒᵖ F] : preserves_colimits_of_shape J F.right_op := { preserves_colimit := λ K, preserves_colimit_right_op K F } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of shape `Jᵒᵖ`, then `F.unop : C ⥤ D` preserves colimits of shape `J`. -/ def preserves_colimits_of_shape_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_limits_of_shape Jᵒᵖ F] : preserves_colimits_of_shape J F.unop := { preserves_colimit := λ K, preserves_colimit_unop K F } end /-- If `F : C ⥤ D` preserves colimits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits. -/ def preserves_limits_op (F : C ⥤ D) [preserves_colimits F] : preserves_limits F.op := { preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_op J F } /-- If `F : C ⥤ Dᵒᵖ` preserves colimits, then `F.left_op : Cᵒᵖ ⥤ D` preserves limits. -/ def preserves_limits_left_op (F : C ⥤ Dᵒᵖ) [preserves_colimits F] : preserves_limits F.left_op := { preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_left_op J F } /-- If `F : Cᵒᵖ ⥤ D` preserves colimits, then `F.right_op : C ⥤ Dᵒᵖ` preserves limits. -/ def preserves_limits_right_op (F : Cᵒᵖ ⥤ D) [preserves_colimits F] : preserves_limits F.right_op := { preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_right_op J F } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits, then `F.unop : C ⥤ D` preserves limits. -/ def preserves_limits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_colimits F] : preserves_limits F.unop := { preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_unop J F } /-- If `F : C ⥤ D` preserves limits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits. -/ def perserves_colimits_op (F : C ⥤ D) [preserves_limits F] : preserves_colimits F.op := { preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_op J F } /-- If `F : C ⥤ Dᵒᵖ` preserves limits, then `F.left_op : Cᵒᵖ ⥤ D` preserves colimits. -/ def preserves_colimits_left_op (F : C ⥤ Dᵒᵖ) [preserves_limits F] : preserves_colimits F.left_op := { preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_left_op J F } /-- If `F : Cᵒᵖ ⥤ D` preserves limits, then `F.right_op : C ⥤ Dᵒᵖ` preserves colimits. -/ def preserves_colimits_right_op (F : Cᵒᵖ ⥤ D) [preserves_limits F] : preserves_colimits F.right_op := { preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_right_op J F } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits, then `F.unop : C ⥤ D` preserves colimits. -/ def preserves_colimits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_limits F] : preserves_colimits F.unop := { preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_unop J F } end section -- Preservation of finite (colimits) is only defined when the morphisms of C and D live in the same -- universe. variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₁} D] /-- If `F : C ⥤ D` preserves finite colimits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite limits. -/ def preserves_finite_limits_op (F : C ⥤ D) [preserves_finite_colimits F] : preserves_finite_limits F.op := { preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_op J F } /-- If `F : C ⥤ Dᵒᵖ` preserves finite colimits, then `F.left_op : Cᵒᵖ ⥤ D` preserves finite limits. -/ def preserves_finite_limits_left_op (F : C ⥤ Dᵒᵖ) [preserves_finite_colimits F] : preserves_finite_limits F.left_op := { preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_left_op J F } /-- If `F : Cᵒᵖ ⥤ D` preserves finite colimits, then `F.right_op : C ⥤ Dᵒᵖ` preserves finite limits. -/ def preserves_finite_limits_right_op (F : Cᵒᵖ ⥤ D) [preserves_finite_colimits F] : preserves_finite_limits F.right_op := { preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_right_op J F } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite colimits, then `F.unop : C ⥤ D` preserves finite limits. -/ def preserves_finite_limits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_finite_colimits F] : preserves_finite_limits F.unop := { preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_unop J F } /-- If `F : C ⥤ D` preserves finite limits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite colimits. -/ def preserves_finite_colimits_op (F : C ⥤ D) [preserves_finite_limits F] : preserves_finite_colimits F.op := { preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_op J F } /-- If `F : C ⥤ Dᵒᵖ` preserves finite limits, then `F.left_op : Cᵒᵖ ⥤ D` preserves finite colimits. -/ def preserves_finite_colimits_left_op (F : C ⥤ Dᵒᵖ) [preserves_finite_limits F] : preserves_finite_colimits F.left_op := { preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_left_op J F } /-- If `F : Cᵒᵖ ⥤ D` preserves finite limits, then `F.right_op : C ⥤ Dᵒᵖ` preserves finite colimits. -/ def preserves_finite_colimits_right_op (F : Cᵒᵖ ⥤ D) [preserves_finite_limits F] : preserves_finite_colimits F.right_op := { preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_right_op J F } /-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite limits, then `F.unop : C ⥤ D` preserves finite colimits. -/ def preserves_finite_colimits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_finite_limits F] : preserves_finite_colimits F.unop := { preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_unop J F } end end category_theory.limits
ba08246b9fbfd30606d321c01e450f7933c63656
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/tools/super/clausifier.lean
0c2428df818d7a3f67b1489a2780c3665c0a93e3
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,820
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .clause_ops import .prover_state .misc_preprocessing open expr list tactic monad decidable universe u namespace super meta def try_option {a : Type u} (tac : tactic a) : tactic (option a) := lift some tac <|> return none private meta def normalize : expr → tactic expr | e := do e' ← whnf e reducible, args' ← monad.for e'^.get_app_args normalize, return $ app_of_list e'^.get_app_fn args' meta def inf_normalize_l (c : clause) : tactic (list clause) := on_first_left c $ λtype, do type' ← normalize type, guard $ type' ≠ type, h ← mk_local_def `h type', return [([h], h)] meta def inf_normalize_r (c : clause) : tactic (list clause) := on_first_right c $ λha, do a' ← normalize ha^.local_type, guard $ a' ≠ ha^.local_type, hna ← mk_local_def `hna (imp a' c^.local_false), return [([hna], app hna ha)] meta def inf_false_l (c : clause) : tactic (list clause) := first $ do i ← list.range c^.num_lits, if c^.get_lit i = clause.literal.left false_ then [return []] else [] meta def inf_false_r (c : clause) : tactic (list clause) := on_first_right c $ λhf, if hf^.local_type = c^.local_false then return [([], hf)] else match hf^.local_type with | const ``false [] := do pr ← mk_app ``false.rec [c^.local_false, hf], return [([], pr)] | _ := failed end meta def inf_true_l (c : clause) : tactic (list clause) := on_first_left c $ λt, match t with | (const ``true []) := return [([], const ``true.intro [])] | _ := failed end meta def inf_true_r (c : clause) : tactic (list clause) := first $ do i ← list.range c^.num_lits, if c^.get_lit i = clause.literal.right (const ``true []) then [return []] else [] meta def inf_not_l (c : clause) : tactic (list clause) := on_first_left c $ λtype, match type with | app (const ``not []) a := do hna ← mk_local_def `h (imp a false_), return [([hna], hna)] | _ := failed end meta def inf_not_r (c : clause) : tactic (list clause) := on_first_right c $ λhna, match hna^.local_type with | app (const ``not []) a := do hnna ← mk_local_def `h (imp (imp a false_) c^.local_false), return [([hnna], app hnna hna)] | _ := failed end meta def inf_and_l (c : clause) : tactic (list clause) := on_first_left c $ λab, match ab with | (app (app (const ``and []) a) b) := do ha ← mk_local_def `l a, hb ← mk_local_def `r b, pab ← mk_mapp ``and.intro [some a, some b, some ha, some hb], return [([ha, hb], pab)] | _ := failed end meta def inf_and_r (c : clause) : tactic (list clause) := on_first_right' c $ λhyp, do pa ← mk_mapp ``and.left [none, none, some hyp], pb ← mk_mapp ``and.right [none, none, some hyp], return [([], pa), ([], pb)] meta def inf_iff_l (c : clause) : tactic (list clause) := on_first_left c $ λab, match ab with | (app (app (const ``iff []) a) b) := do hab ← mk_local_def `l (imp a b), hba ← mk_local_def `r (imp b a), pab ← mk_mapp ``iff.intro [some a, some b, some hab, some hba], return [([hab, hba], pab)] | _ := failed end meta def inf_iff_r (c : clause) : tactic (list clause) := on_first_right' c $ λhyp, do pa ← mk_mapp ``iff.mp [none, none, some hyp], pb ← mk_mapp ``iff.mpr [none, none, some hyp], return [([], pa), ([], pb)] meta def inf_or_r (c : clause) : tactic (list clause) := on_first_right c $ λhab, match hab^.local_type with | (app (app (const ``or []) a) b) := do hna ← mk_local_def `l (imp a c^.local_false), hnb ← mk_local_def `r (imp b c^.local_false), proof ← mk_app ``or.elim [a, b, c^.local_false, hab, hna, hnb], return [([hna, hnb], proof)] | _ := failed end meta def inf_or_l (c : clause) : tactic (list clause) := on_first_left c $ λab, match ab with | (app (app (const ``or []) a) b) := do ha ← mk_local_def `l a, hb ← mk_local_def `l b, pa ← mk_mapp ``or.inl [some a, some b, some ha], pb ← mk_mapp ``or.inr [some a, some b, some hb], return [([ha], pa), ([hb], pb)] | _ := failed end meta def inf_all_r (c : clause) : tactic (list clause) := on_first_right' c $ λhallb, match hallb^.local_type with | (pi n bi a b) := do ha ← mk_local_def `x a, return [([ha], app hallb ha)] | _ := failed end lemma imp_l {F a b} [decidable a] : ((a → b) → F) → ((a → F) → F) := λhabf haf, decidable.by_cases (assume ha : a, haf ha) (assume hna : ¬a, habf (take ha, absurd ha hna)) lemma imp_l' {F a b} [decidable F] : ((a → b) → F) → ((a → F) → F) := λhabf haf, decidable.by_cases (assume hf : F, hf) (assume hnf : ¬F, habf (take ha, absurd (haf ha) hnf)) lemma imp_l_c {F : Prop} {a b} : ((a → b) → F) → ((a → F) → F) := λhabf haf, classical.by_cases (assume hf : F, hf) (assume hnf : ¬F, habf (take ha, absurd (haf ha) hnf)) meta def inf_imp_l (c : clause) : tactic (list clause) := on_first_left_dn c $ λhnab, match hnab^.local_type with | (pi _ _ (pi _ _ a b) _) := if b^.has_var then failed else do hna ← mk_local_def `na (imp a c^.local_false), pf ← first (do r ← [``super.imp_l, ``super.imp_l', ``super.imp_l_c], [mk_app r [hnab, hna]]), hb ← mk_local_def `b b, return [([hna], pf), ([hb], app hnab (lam `a binder_info.default a hb))] | _ := failed end meta def inf_ex_l (c : clause) : tactic (list clause) := on_first_left c $ λexp, match exp with | (app (app (const ``Exists [u]) dom) pred) := do hx ← mk_local_def `x dom, predx ← whnf $ app pred hx, hpx ← mk_local_def `hpx predx, return [([hx,hpx], app_of_list (const ``exists.intro [u]) [dom, pred, hx, hpx])] | _ := failed end lemma demorgan' {F a} {b : a → Prop} : ((∀x, b x) → F) → (((∃x, b x → F) → F) → F) := assume hab hnenb, classical.by_cases (assume h : ∃x, ¬b x, begin cases h with x, apply hnenb, existsi x, intros, contradiction end) (assume h : ¬∃x, ¬b x, hab (take x, classical.by_cases (assume bx : b x, bx) (assume nbx : ¬b x, begin assert hf : false, apply h, existsi x, assumption, contradiction end))) meta def inf_all_l (c : clause) : tactic (list clause) := on_first_left_dn c $ λhnallb, match hnallb^.local_type with | pi _ _ (pi n bi a b) _ := do enb ← mk_mapp ``Exists [none, some $ lam n binder_info.default a (imp b c^.local_false)], hnenb ← mk_local_def `h (imp enb c^.local_false), pr ← mk_app ``super.demorgan' [hnallb, hnenb], return [([hnenb], pr)] | _ := failed end meta def inf_ex_r (c : clause) : tactic (list clause) := do (qf, ctx) ← c^.open_constn c^.num_quants, skolemized ← on_first_right' qf $ λhexp, match hexp^.local_type with | (app (app (const ``Exists [_]) d) p) := do sk_sym_name_pp ← get_unused_name `sk (some 1), inh_lc ← mk_local' `w binder_info.implicit d, sk_sym ← mk_local_def sk_sym_name_pp (pis (ctx ++ [inh_lc]) d), sk_p ← whnf_no_delta $ app p (app_of_list sk_sym (ctx ++ [inh_lc])), sk_ax ← mk_mapp ``Exists [some (local_type sk_sym), some (lambdas [sk_sym] (pis (ctx ++ [inh_lc]) (imp hexp^.local_type sk_p)))], sk_ax_name ← get_unused_name `sk_axiom (some 1), assert sk_ax_name sk_ax, nonempt_of_inh ← mk_mapp ``nonempty.intro [some d, some inh_lc], eps ← mk_mapp ``classical.epsilon [some d, some nonempt_of_inh, some p], existsi (lambdas (ctx ++ [inh_lc]) eps), eps_spec ← mk_mapp ``classical.epsilon_spec [some d, some p], exact (lambdas (ctx ++ [inh_lc]) eps_spec), sk_ax_local ← get_local sk_ax_name, cases sk_ax_local [sk_sym_name_pp, sk_ax_name], sk_ax' ← get_local sk_ax_name, return [([inh_lc], app_of_list sk_ax' (ctx ++ [inh_lc, hexp]))] | _ := failed end, return $ skolemized^.for (λs, s^.close_constn ctx) meta def first_some {a : Type} : list (tactic (option a)) → tactic (option a) | [] := return none | (x::xs) := do xres ← x, match xres with some y := return (some y) | none := first_some xs end private meta def get_clauses_core' (rules : list (clause → tactic (list clause))) : list clause → tactic (list clause) | cs := lift list.join $ do for cs $ λc, do first $ rules^.for (λr, r c >>= get_clauses_core') ++ [return [c]] meta def get_clauses_core (rules : list (clause → tactic (list clause))) (initial : list clause) : tactic (list clause) := do clauses ← get_clauses_core' rules initial, filter (λc, lift bnot $ is_taut c) $ list.nub_on clause.type clauses meta def clausification_rules_intuit : list (clause → tactic (list clause)) := [ inf_false_l, inf_false_r, inf_true_l, inf_true_r, inf_not_l, inf_not_r, inf_and_l, inf_and_r, inf_iff_l, inf_iff_r, inf_or_l, inf_or_r, inf_ex_l, inf_normalize_l, inf_normalize_r ] meta def clausification_rules_classical : list (clause → tactic (list clause)) := [ inf_false_l, inf_false_r, inf_true_l, inf_true_r, inf_not_l, inf_not_r, inf_and_l, inf_and_r, inf_iff_l, inf_iff_r, inf_or_l, inf_or_r, inf_imp_l, inf_all_r, inf_ex_l, inf_all_l, inf_ex_r, inf_normalize_l, inf_normalize_r ] meta def get_clauses_classical : list clause → tactic (list clause) := get_clauses_core clausification_rules_classical meta def get_clauses_intuit : list clause → tactic (list clause) := get_clauses_core clausification_rules_intuit meta def as_refutation : tactic unit := do repeat (do intro1, skip), tgt ← target, if tgt^.is_constant || tgt^.is_local_constant then skip else do local_false_name ← get_unused_name `F none, tgt_type ← infer_type tgt, definev local_false_name tgt_type tgt, local_false ← get_local local_false_name, target_name ← get_unused_name `target none, assertv target_name (imp tgt local_false) (lam `hf binder_info.default tgt $ mk_var 0), change local_false meta def clauses_of_context : tactic (list clause) := do local_false ← target, l ← local_context, monad.for l (clause.of_proof local_false) meta def clausify_pre := preprocessing_rule $ take new, lift list.join $ for new $ λ dc, do cs ← get_clauses_classical [dc^.c], if cs^.length ≤ 1 then return (for cs $ λ c, { dc with c := c }) else for cs (λc, mk_derived c dc^.sc) -- @[super.inf] meta def clausification_inf : inf_decl := inf_decl.mk 0 $ λgiven, list.foldr orelse (return ()) $ do r ← clausification_rules_classical, [do cs ← r given^.c, cs' ← get_clauses_classical cs, for' cs' (λc, mk_derived c given^.sc^.sched_now >>= add_inferred), remove_redundant given^.id []] end super
bf74d8d5682541009e3bbf8f3c9f7eab9fe70647
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/simp_proj.lean
1efe50b5c3624cbbfc482a121e9a387b92b00c8e
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,225
lean
def f (a : nat) := (a, 0) example (a b : nat) (h : a = b) : (f a).1 = b := begin simp [f], guard_target a = b, exact h end example (a b : nat) (h : a = b) : (f a).1 = b := begin simp [f] {proj := ff}, guard_target (a, 0)^.1 = b, exact h end def g (a : nat) := (λ x, x) a example (a b : nat) (h : a = b) : g a = b := begin simp [g], guard_target a = b, exact h end example (a b : nat) (h : a = b) : g a = b := begin simp [g] {beta := ff}, guard_target (λ x, x) a = b, exact h end example (a b : nat) : a + b = b + a := begin simp only [has_add.add], guard_target nat.add a b = nat.add b a, apply nat.add_comm end example (a b : nat) : a + b = b + a := begin unfold has_add.add, guard_target nat.add a b = nat.add b a, apply nat.add_comm end example (a b : nat) : a + b = b + a := begin simp only [*, has_add.add] at *, guard_target nat.add a b = nat.add b a, apply nat.add_comm end example (a b : nat) : a + b = b + a := begin simp only [*, has_add.add], guard_target nat.add a b = nat.add b a, apply nat.add_comm end example (a b : nat) : a + b = b + a := begin conv { simp only [has_add.add] }, guard_target nat.add a b = nat.add b a, apply nat.add_comm end
6d959a644c74cbf4b52a7b4994ff7091c8d626f2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/calculus/extend_deriv.lean
16dae36a05cbc7d75176cec45106bbae11ff076f
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
11,050
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value /-! # Extending differentiability to the boundary We investigate how differentiable functions inside a set extend to differentiable functions on the boundary. For this, it suffices that the function and its derivative admit limits there. A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`. One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or the right endpoint of an interval, are given in `has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and `has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms of the one-dimensional derivative `deriv ℝ f`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open filter set metric continuous_linear_map open_locale topological_space local attribute [mono] prod_mono /-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there with derivative `f'`. -/ theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F} (f_diff : differentiable_on ℝ f s) (s_conv : convex s) (s_open : is_open s) (f_cont : ∀y ∈ closure s, continuous_within_at f s y) (h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) : has_fderiv_within_at f f' (closure s) x := begin classical, -- one can assume without loss of generality that `x` belongs to the closure of `s`, as the -- statement is empty otherwise by_cases hx : x ∉ closure s, { rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx }, push_neg at hx, rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff], /- One needs to show that `∥f y - f x - f' (y - x)∥ ≤ ε ∥y - x∥` for `y` close to `x` in `closure s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/ assume ε ε_pos, obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ∥fderiv ℝ f y - f'∥ < ε, by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos, set B := ball x δ, suffices : ∀ y ∈ B ∩ (closure s), ∥f y - f x - (f' y - f' x)∥ ≤ ε * ∥y - x∥, from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩, suffices : ∀ p : E × E, p ∈ closure ((B ∩ s).prod (B ∩ s)) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥ ≤ ε * ∥p.2 - p.1∥, { rw closure_prod_eq at this, intros y y_in, apply this ⟨x, y⟩, have : B ∩ closure s ⊆ closure (B ∩ s), from closure_inter_open is_open_ball, exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ }, have key : ∀ p : E × E, p ∈ (B ∩ s).prod (B ∩ s) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥ ≤ ε * ∥p.2 - p.1∥, { rintros ⟨u, v⟩ ⟨u_in, v_in⟩, have conv : convex (B ∩ s) := (convex_ball _ _).inter s_conv, have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _), have bound : ∀ z ∈ (B ∩ s), ∥fderiv_within ℝ f (B ∩ s) z - f'∥ ≤ ε, { intros z z_in, convert le_of_lt (hδ _ z_in.2 z_in.1), have op : is_open (B ∩ s) := is_open_ball.inter s_open, rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in), exact (diff z z_in).differentiable_at (is_open.mem_nhds op z_in) }, simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in }, rintros ⟨u, v⟩ uv_in, refine continuous_within_at.closure_le uv_in _ _ key, have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y, { intros y y_in, exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) }, all_goals { -- common start for both continuity proofs have : (B ∩ s).prod (B ∩ s) ⊆ s.prod s, by mono ; exact inter_subset_right _ _, obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s, by simpa [closure_prod_eq] using closure_mono this uv_in, apply continuous_within_at.mono _ this, simp only [continuous_within_at] }, rw nhds_within_prod_eq, { have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by { intros, abel }, simp only [this], exact tendsto.comp continuous_norm.continuous_at ((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $ tendsto.comp (f_cont' u u_in) tendsto_fst) }, { apply tendsto_nhds_within_of_tendsto_nhds, rw nhds_prod_eq, exact tendsto_const_nhds.mul (tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) }, end /-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/ lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ 𝓝[Ioi a] a) (f_lim' : tendsto (λx, deriv f x) (𝓝[Ioi a] a) (𝓝 e)) : has_deriv_within_at f e (Ici a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ab, sab⟩ : ∃ b ∈ Ioi a, Ioc a b ⊆ s := mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs, let t := Ioo a b, have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex t := convex_Ioo a b, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc a b := closure_Ioo ab, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)), { simp [deriv_fderiv.symm], refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _, exact tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim' }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc a b) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (mem_nhds_within_Ici_iff_exists_Icc_subset.2 ⟨b, ab, subset.refl _⟩) end /-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/ lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ 𝓝[Iio a] a) (f_lim' : tendsto (λx, deriv f x) (𝓝[Iio a] a) (𝓝 e)) : has_deriv_within_at f e (Iic a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s := mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs, let t := Ioo b a, have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex t := convex_Ioo b a, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc b a := closure_Ioo ba, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)), { simp [deriv_fderiv.symm], refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _, exact tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim' }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc b a) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (mem_nhds_within_Iic_iff_exists_Icc_subset.2 ⟨b, ba, subset.refl _⟩) end /-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are continuous at this point, then `g` is also the derivative of `f` at this point. -/ lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ} (f_diff : ∀ y ≠ x, has_deriv_at f (g y) y) (hf : continuous_at f x) (hg : continuous_at g x) : has_deriv_at f (g x) x := begin have A : has_deriv_within_at f (g x) (Ici x) x, { have diff : differentiable_on ℝ f (Ioi x) := λy hy, (f_diff y (ne_of_gt hy)).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuous_within_at self_mem_nhds_within, have : tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) := tendsto_inf_left hg, apply this.congr' _, apply mem_sets_of_superset self_mem_nhds_within (λy hy, _), exact (f_diff y (ne_of_gt hy)).deriv.symm }, have B : has_deriv_within_at f (g x) (Iic x) x, { have diff : differentiable_on ℝ f (Iio x) := λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at self_mem_nhds_within, have : tendsto g (𝓝[Iio x] x) (𝓝 (g x)) := tendsto_inf_left hg, apply this.congr' _, apply mem_sets_of_superset self_mem_nhds_within (λy hy, _), exact (f_diff y (ne_of_lt hy)).deriv.symm }, simpa using B.union A end
4bbf3b2381fe40eab5c4fe836fce61da9d066868
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/asymptotics.lean
b3ace01302afd5591686652045acd901d135c5fb
[]
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
83,671
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.basic import Mathlib.topology.local_homeomorph import Mathlib.PostPort universes u_1 u_3 u_4 u_7 u_6 u_2 u_5 u_8 u_11 u_9 u_13 namespace Mathlib /-! # 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.) -/ namespace asymptotics /-! ### 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 {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (c : ℝ) (f : α → E) (g : α → F) (l : filter α) := filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l /-- 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. -/ theorem is_O_with_iff {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {l : filter α} : is_O_with c f g l ↔ filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l := iff.rfl theorem is_O_with.of_bound {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {l : filter α} (h : filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l) : 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 {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (f : α → E) (g : α → F) (l : filter α) := ∃ (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. -/ theorem is_O_iff_is_O_with {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {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. -/ theorem is_O_iff {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ (c : ℝ), filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l := iff.rfl theorem is_O.of_bound {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (c : ℝ) {f : α → E} {g : α → F} {l : filter α} (h : filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l) : is_O f g l := Exists.intro 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 {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (f : α → E) (g : α → F) (l : filter α) := ∀ {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. -/ theorem is_o_iff_forall_is_O_with {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {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. -/ theorem is_o_iff {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ {c : ℝ}, 0 < c → filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l := iff.rfl theorem is_o.def {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : filter.eventually (fun (x : α) => norm (f x) ≤ c * norm (g x)) l := h hc theorem is_o.def' {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {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 /-! ### Conversions -/ theorem is_O_with.is_O {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {l : filter α} (h : is_O_with c f g l) : is_O f g l := Exists.intro c h theorem is_o.is_O_with {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} (hgf : is_o f g l) : is_O_with 1 f g l := hgf zero_lt_one theorem is_o.is_O {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} (hgf : is_o f g l) : is_O f g l := is_O_with.is_O (is_o.is_O_with hgf) theorem is_O_with.weaken {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {c' : ℝ} {f : α → E} {g' : α → F'} {l : filter α} (h : is_O_with c f g' l) (hc : c ≤ c') : is_O_with c' f g' l := filter.mem_sets_of_superset h fun (x : α) (hx : x ∈ set_of fun (x : α) => (fun (x : α) => norm (f x) ≤ c * norm (g' x)) x) => le_trans hx (mul_le_mul_of_nonneg_right hc (norm_nonneg (g' x))) theorem is_O_with.exists_pos {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {f : α → E} {g' : α → F'} {l : filter α} (h : is_O_with c f g' l) : ∃ (c' : ℝ), ∃ (H : 0 < c'), is_O_with c' f g' l := Exists.intro (max c 1) (Exists.intro (lt_of_lt_of_le zero_lt_one (le_max_right c 1)) (is_O_with.weaken h (le_max_left c 1))) theorem is_O.exists_pos {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} (h : is_O f g' l) : ∃ (c : ℝ), ∃ (H : 0 < c), is_O_with c f g' l := sorry theorem is_O_with.exists_nonneg {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {f : α → E} {g' : α → F'} {l : filter α} (h : is_O_with c f g' l) : ∃ (c' : ℝ), ∃ (H : 0 ≤ c'), is_O_with c' f g' l := sorry theorem is_O.exists_nonneg {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} (h : is_O f g' l) : ∃ (c : ℝ), ∃ (H : 0 ≤ c), is_O_with c f g' l := sorry /-! ### Subsingleton -/ theorem is_o_of_subsingleton {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} [subsingleton E'] : is_o f' g' l := sorry theorem is_O_of_subsingleton {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} [subsingleton E'] : is_O f' g' l := is_o.is_O is_o_of_subsingleton /-! ### Congruence -/ theorem is_O_with_congr {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : filter.eventually_eq l f₁ f₂) (hg : filter.eventually_eq l g₁ g₂) : is_O_with c₁ f₁ g₁ l ↔ is_O_with c₂ f₂ g₂ l := sorry theorem is_O_with.congr' {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : filter.eventually_eq l f₁ f₂) (hg : filter.eventually_eq l g₁ g₂) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := iff.mp (is_O_with_congr hc hf hg) theorem is_O_with.congr {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {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 := fun (h : is_O_with c₁ f₁ g₁ l) => is_O_with.congr' hc (filter.univ_mem_sets' hf) (filter.univ_mem_sets' hg) h theorem is_O_with.congr_left {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {g : α → F} {f₁ : α → E} {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 fun (_x : α) => rfl theorem is_O_with.congr_right {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g₁ : α → F} {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 (fun (_x : α) => rfl) hg theorem is_O_with.congr_const {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {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 (fun (_x : α) => rfl) fun (_x : α) => rfl theorem is_O_congr {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {g₂ : α → F} {l : filter α} (hf : filter.eventually_eq l f₁ f₂) (hg : filter.eventually_eq l g₁ g₂) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := exists_congr fun (c : ℝ) => is_O_with_congr rfl hf hg theorem is_O.congr' {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {g₂ : α → F} {l : filter α} (hf : filter.eventually_eq l f₁ f₂) (hg : filter.eventually_eq l g₁ g₂) : is_O f₁ g₁ l → is_O f₂ g₂ l := iff.mp (is_O_congr hf hg) theorem is_O.congr {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {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 := fun (h : is_O f₁ g₁ l) => is_O.congr' (filter.univ_mem_sets' hf) (filter.univ_mem_sets' hg) h theorem is_O.congr_left {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {g : α → F} {f₁ : α → E} {f₂ : α → E} {l : filter α} (hf : ∀ (x : α), f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf fun (_x : α) => rfl theorem is_O.congr_right {α : Type u_1} {E : Type u_3} [has_norm E] {f : α → E} {g₁ : α → E} {g₂ : α → E} {l : filter α} (hg : ∀ (x : α), g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (fun (_x : α) => rfl) hg theorem is_o_congr {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {g₂ : α → F} {l : filter α} (hf : filter.eventually_eq l f₁ f₂) (hg : filter.eventually_eq l g₁ g₂) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr fun (c : ℝ) (hc : 0 < c) => is_O_with_congr (Eq.refl c) hf hg theorem is_o.congr' {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {g₂ : α → F} {l : filter α} (hf : filter.eventually_eq l f₁ f₂) (hg : filter.eventually_eq l g₁ g₂) : is_o f₁ g₁ l → is_o f₂ g₂ l := iff.mp (is_o_congr hf hg) theorem is_o.congr {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f₁ : α → E} {f₂ : α → E} {g₁ : α → F} {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 := fun (h : is_o f₁ g₁ l) => is_o.congr' (filter.univ_mem_sets' hf) (filter.univ_mem_sets' hg) h theorem is_o.congr_left {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {g : α → F} {f₁ : α → E} {f₂ : α → E} {l : filter α} (hf : ∀ (x : α), f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf fun (_x : α) => rfl theorem is_o.congr_right {α : Type u_1} {E : Type u_3} [has_norm E] {f : α → E} {g₁ : α → E} {g₂ : α → E} {l : filter α} (hg : ∀ (x : α), g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (fun (_x : α) => rfl) hg /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto {α : Type u_1} {β : Type u_2} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {l : filter α} (hcfg : is_O_with c f g l) {k : β → α} {l' : filter β} (hk : filter.tendsto k l' l) : is_O_with c (f ∘ k) (g ∘ k) l' := hk hcfg theorem is_O.comp_tendsto {α : Type u_1} {β : Type u_2} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} (hfg : is_O f g l) {k : β → α} {l' : filter β} (hk : filter.tendsto k l' l) : is_O (f ∘ k) (g ∘ k) l' := Exists.imp (fun (c : ℝ) (h : is_O_with c f g l) => is_O_with.comp_tendsto h hk) hfg theorem is_o.comp_tendsto {α : Type u_1} {β : Type u_2} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} (hfg : is_o f g l) {k : β → α} {l' : filter β} (hk : filter.tendsto k l' l) : is_o (f ∘ k) (g ∘ k) l' := fun (c : ℝ) (cpos : 0 < c) => is_O_with.comp_tendsto (hfg cpos) hk @[simp] theorem is_O_with_map {α : Type u_1} {β : Type u_2} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {k : β → α} {l : filter β} : is_O_with c f g (filter.map k l) ↔ is_O_with c (f ∘ k) (g ∘ k) l := filter.mem_map @[simp] theorem is_O_map {α : Type u_1} {β : Type u_2} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {k : β → α} {l : filter β} : is_O f g (filter.map k l) ↔ is_O (f ∘ k) (g ∘ k) l := sorry @[simp] theorem is_o_map {α : Type u_1} {β : Type u_2} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {k : β → α} {l : filter β} : is_o f g (filter.map k l) ↔ is_o (f ∘ k) (g ∘ k) l := sorry theorem is_O_with.mono {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {l : filter α} {l' : filter α} (h : is_O_with c f g l') (hl : l ≤ l') : is_O_with c f g l := hl h theorem is_O.mono {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} {l' : filter α} (h : is_O f g l') (hl : l ≤ l') : is_O f g l := Exists.imp (fun (c : ℝ) (h : is_O_with c f g l') => is_O_with.mono h hl) h theorem is_o.mono {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} {l' : filter α} (h : is_o f g l') (hl : l ≤ l') : is_o f g l := fun (c : ℝ) (cpos : 0 < c) => is_O_with.mono (h cpos) hl theorem is_O_with.trans {α : Type u_1} {E : Type u_3} {F : Type u_4} {G : Type u_5} [has_norm E] [has_norm F] [has_norm G] {c : ℝ} {c' : ℝ} {f : α → E} {g : α → F} {k : α → G} {l : filter α} (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 := sorry theorem is_O.trans {α : Type u_1} {E : Type u_3} {G : Type u_5} {F' : Type u_7} [has_norm E] [has_norm G] [normed_group F'] {f : α → E} {k : α → G} {g' : α → F'} {l : filter α} (hfg : is_O f g' l) (hgk : is_O g' k l) : is_O f k l := sorry theorem is_o.trans_is_O_with {α : Type u_1} {E : Type u_3} {F : Type u_4} {G : Type u_5} [has_norm E] [has_norm F] [has_norm G] {c : ℝ} {f : α → E} {g : α → F} {k : α → G} {l : filter α} (hfg : is_o f g l) (hgk : is_O_with c g k l) (hc : 0 < c) : is_o f k l := sorry theorem is_o.trans_is_O {α : Type u_1} {E : Type u_3} {F : Type u_4} {G' : Type u_8} [has_norm E] [has_norm F] [normed_group G'] {f : α → E} {g : α → F} {k' : α → G'} {l : filter α} (hfg : is_o f g l) (hgk : is_O g k' l) : is_o f k' l := sorry theorem is_O_with.trans_is_o {α : Type u_1} {E : Type u_3} {F : Type u_4} {G : Type u_5} [has_norm E] [has_norm F] [has_norm G] {c : ℝ} {f : α → E} {g : α → F} {k : α → G} {l : filter α} (hfg : is_O_with c f g l) (hgk : is_o g k l) (hc : 0 < c) : is_o f k l := sorry theorem is_O.trans_is_o {α : Type u_1} {E : Type u_3} {G : Type u_5} {F' : Type u_7} [has_norm E] [has_norm G] [normed_group F'] {f : α → E} {k : α → G} {g' : α → F'} {l : filter α} (hfg : is_O f g' l) (hgk : is_o g' k l) : is_o f k l := sorry theorem is_o.trans {α : Type u_1} {E : Type u_3} {F : Type u_4} {G' : Type u_8} [has_norm E] [has_norm F] [normed_group G'] {f : α → E} {g : α → F} {k' : α → G'} {l : filter α} (hfg : is_o f g l) (hgk : is_o g k' l) : is_o f k' l := is_o.trans_is_O hfg (is_o.is_O hgk) theorem is_o.trans' {α : Type u_1} {E : Type u_3} {G : Type u_5} {F' : Type u_7} [has_norm E] [has_norm G] [normed_group F'] {f : α → E} {k : α → G} {g' : α → F'} {l : filter α} (hfg : is_o f g' l) (hgk : is_o g' k l) : is_o f k l := is_O.trans_is_o (is_o.is_O hfg) hgk theorem is_O_with_of_le' {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} (l : filter α) (hfg : ∀ (x : α), norm (f x) ≤ c * norm (g x)) : is_O_with c f g l := filter.univ_mem_sets' hfg theorem is_O_with_of_le {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} (l : filter α) (hfg : ∀ (x : α), norm (f x) ≤ norm (g x)) : is_O_with 1 f g l := is_O_with_of_le' l fun (x : α) => eq.mpr (id (Eq._oldrec (Eq.refl (norm (f x) ≤ 1 * norm (g x))) (one_mul (norm (g x))))) (hfg x) theorem is_O_of_le' {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} (l : filter α) (hfg : ∀ (x : α), norm (f x) ≤ c * norm (g x)) : is_O f g l := is_O_with.is_O (is_O_with_of_le' l hfg) theorem is_O_of_le {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} (l : filter α) (hfg : ∀ (x : α), norm (f x) ≤ norm (g x)) : is_O f g l := is_O_with.is_O (is_O_with_of_le l hfg) theorem is_O_with_refl {α : Type u_1} {E : Type u_3} [has_norm E] (f : α → E) (l : filter α) : is_O_with 1 f f l := is_O_with_of_le l fun (_x : α) => le_refl (norm (f _x)) theorem is_O_refl {α : Type u_1} {E : Type u_3} [has_norm E] (f : α → E) (l : filter α) : is_O f f l := is_O_with.is_O (is_O_with_refl f l) theorem is_O_with.trans_le {α : Type u_1} {E : Type u_3} {F : Type u_4} {G : Type u_5} [has_norm E] [has_norm F] [has_norm G] {c : ℝ} {f : α → E} {g : α → F} {k : α → G} {l : filter α} (hfg : is_O_with c f g l) (hgk : ∀ (x : α), norm (g x) ≤ norm (k x)) (hc : 0 ≤ c) : is_O_with c f k l := is_O_with.congr_const (mul_one c) (is_O_with.trans hfg (is_O_with_of_le l hgk) hc) theorem is_O.trans_le {α : Type u_1} {E : Type u_3} {G : Type u_5} {F' : Type u_7} [has_norm E] [has_norm G] [normed_group F'] {f : α → E} {k : α → G} {g' : α → F'} {l : filter α} (hfg : is_O f g' l) (hgk : ∀ (x : α), norm (g' x) ≤ norm (k x)) : is_O f k l := is_O.trans hfg (is_O_of_le l hgk) theorem is_o.trans_le {α : Type u_1} {E : Type u_3} {F : Type u_4} {G : Type u_5} [has_norm E] [has_norm F] [has_norm G] {f : α → E} {g : α → F} {k : α → G} {l : filter α} (hfg : is_o f g l) (hgk : ∀ (x : α), norm (g x) ≤ norm (k x)) : is_o f k l := is_o.trans_is_O_with hfg (is_O_with_of_le l hgk) zero_lt_one @[simp] theorem is_O_with_bot {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (c : ℝ) (f : α → E) (g : α → F) : is_O_with c f g ⊥ := trivial @[simp] theorem is_O_bot {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (f : α → E) (g : α → F) : is_O f g ⊥ := is_O_with.is_O (is_O_with_bot 1 f g) @[simp] theorem is_o_bot {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] (f : α → E) (g : α → F) : is_o f g ⊥ := fun (c : ℝ) (_x : 0 < c) => is_O_with_bot c f g theorem is_O_with.join {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {l : filter α} {l' : filter α} (h : is_O_with c f g l) (h' : is_O_with c f g l') : is_O_with c f g (l ⊔ l') := iff.mpr filter.mem_sup_sets { left := h, right := h' } theorem is_O_with.join' {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {c' : ℝ} {f : α → E} {g' : α → F'} {l : filter α} {l' : filter α} (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') := iff.mpr filter.mem_sup_sets { left := is_O_with.weaken h (le_max_left c c'), right := is_O_with.weaken h' (le_max_right c c') } theorem is_O.join {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} {l' : filter α} (h : is_O f g' l) (h' : is_O f g' l') : is_O f g' (l ⊔ l') := sorry theorem is_o.join {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {l : filter α} {l' : filter α} (h : is_o f g l) (h' : is_o f g l') : is_o f g (l ⊔ l') := fun (c : ℝ) (cpos : 0 < c) => is_O_with.join (h cpos) (h' cpos) /-! ### Simplification : norm -/ @[simp] theorem is_O_with_norm_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {f : α → E} {g' : α → F'} {l : filter α} : is_O_with c f (fun (x : α) => norm (g' x)) l ↔ is_O_with c f g' l := sorry theorem is_O_with.norm_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {f : α → E} {g' : α → F'} {l : filter α} : is_O_with c f g' l → is_O_with c f (fun (x : α) => norm (g' x)) l := iff.mpr is_O_with_norm_right @[simp] theorem is_O_norm_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_O f (fun (x : α) => norm (g' x)) l ↔ is_O f g' l := exists_congr fun (_x : ℝ) => is_O_with_norm_right theorem is_O.norm_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_O f g' l → is_O f (fun (x : α) => norm (g' x)) l := iff.mpr is_O_norm_right @[simp] theorem is_o_norm_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_o f (fun (x : α) => norm (g' x)) l ↔ is_o f g' l := forall_congr fun (_x : ℝ) => forall_congr fun (_x_1 : 0 < _x) => is_O_with_norm_right theorem is_o.norm_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_o f g' l → is_o f (fun (x : α) => norm (g' x)) l := iff.mpr is_o_norm_right @[simp] theorem is_O_with_norm_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {g : α → F} {f' : α → E'} {l : filter α} : is_O_with c (fun (x : α) => norm (f' x)) g l ↔ is_O_with c f' g l := sorry theorem is_O_with.of_norm_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {g : α → F} {f' : α → E'} {l : filter α} : is_O_with c (fun (x : α) => norm (f' x)) g l → is_O_with c f' g l := iff.mp is_O_with_norm_left @[simp] theorem is_O_norm_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_O (fun (x : α) => norm (f' x)) g l ↔ is_O f' g l := exists_congr fun (_x : ℝ) => is_O_with_norm_left theorem is_O.of_norm_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_O (fun (x : α) => norm (f' x)) g l → is_O f' g l := iff.mp is_O_norm_left @[simp] theorem is_o_norm_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_o (fun (x : α) => norm (f' x)) g l ↔ is_o f' g l := forall_congr fun (_x : ℝ) => forall_congr fun (_x_1 : 0 < _x) => is_O_with_norm_left theorem is_o.of_norm_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_o (fun (x : α) => norm (f' x)) g l → is_o f' g l := iff.mp is_o_norm_left theorem is_O_with_norm_norm {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {c : ℝ} {f' : α → E'} {g' : α → F'} {l : filter α} : is_O_with c (fun (x : α) => norm (f' x)) (fun (x : α) => norm (g' x)) l ↔ is_O_with c f' g' l := iff.trans is_O_with_norm_left is_O_with_norm_right theorem is_O_with.of_norm_norm {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {c : ℝ} {f' : α → E'} {g' : α → F'} {l : filter α} : is_O_with c (fun (x : α) => norm (f' x)) (fun (x : α) => norm (g' x)) l → is_O_with c f' g' l := iff.mp is_O_with_norm_norm theorem is_O_norm_norm {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_O (fun (x : α) => norm (f' x)) (fun (x : α) => norm (g' x)) l ↔ is_O f' g' l := iff.trans is_O_norm_left is_O_norm_right theorem is_O.of_norm_norm {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_O (fun (x : α) => norm (f' x)) (fun (x : α) => norm (g' x)) l → is_O f' g' l := iff.mp is_O_norm_norm theorem is_o_norm_norm {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_o (fun (x : α) => norm (f' x)) (fun (x : α) => norm (g' x)) l ↔ is_o f' g' l := iff.trans is_o_norm_left is_o_norm_right theorem is_o.norm_norm {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_o f' g' l → is_o (fun (x : α) => norm (f' x)) (fun (x : α) => norm (g' x)) l := iff.mpr is_o_norm_norm /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {f : α → E} {g' : α → F'} {l : filter α} : is_O_with c f (fun (x : α) => -g' x) l ↔ is_O_with c f g' l := sorry theorem is_O_with.neg_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {c : ℝ} {f : α → E} {g' : α → F'} {l : filter α} : is_O_with c f g' l → is_O_with c f (fun (x : α) => -g' x) l := iff.mpr is_O_with_neg_right @[simp] theorem is_O_neg_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_O f (fun (x : α) => -g' x) l ↔ is_O f g' l := exists_congr fun (_x : ℝ) => is_O_with_neg_right theorem is_O.of_neg_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_O f (fun (x : α) => -g' x) l → is_O f g' l := iff.mp is_O_neg_right @[simp] theorem is_o_neg_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_o f (fun (x : α) => -g' x) l ↔ is_o f g' l := forall_congr fun (_x : ℝ) => forall_congr fun (_x_1 : 0 < _x) => is_O_with_neg_right theorem is_o.of_neg_right {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} {l : filter α} : is_o f (fun (x : α) => -g' x) l → is_o f g' l := iff.mp is_o_neg_right @[simp] theorem is_O_with_neg_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {g : α → F} {f' : α → E'} {l : filter α} : is_O_with c (fun (x : α) => -f' x) g l ↔ is_O_with c f' g l := sorry theorem is_O_with.neg_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {g : α → F} {f' : α → E'} {l : filter α} : is_O_with c f' g l → is_O_with c (fun (x : α) => -f' x) g l := iff.mpr is_O_with_neg_left @[simp] theorem is_O_neg_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_O (fun (x : α) => -f' x) g l ↔ is_O f' g l := exists_congr fun (_x : ℝ) => is_O_with_neg_left theorem is_O.neg_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_O f' g l → is_O (fun (x : α) => -f' x) g l := iff.mpr is_O_neg_left @[simp] theorem is_o_neg_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_o (fun (x : α) => -f' x) g l ↔ is_o f' g l := forall_congr fun (_x : ℝ) => forall_congr fun (_x_1 : 0 < _x) => is_O_with_neg_left theorem is_o.neg_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {f' : α → E'} {l : filter α} : is_o f' g l → is_o (fun (x : α) => -f' x) g l := iff.mpr is_o_neg_left /-! ### Product of functions (right) -/ theorem is_O_with_fst_prod {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_O_with 1 f' (fun (x : α) => (f' x, g' x)) l := is_O_with_of_le l fun (x : α) => le_max_left (norm (f' x)) (norm (prod.snd (f' x, g' x))) theorem is_O_with_snd_prod {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_O_with 1 g' (fun (x : α) => (f' x, g' x)) l := is_O_with_of_le l fun (x : α) => le_max_right (norm (prod.fst (f' x, g' x))) (norm (g' x)) theorem is_O_fst_prod {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_O f' (fun (x : α) => (f' x, g' x)) l := is_O_with.is_O is_O_with_fst_prod theorem is_O_snd_prod {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} : is_O g' (fun (x : α) => (f' x, g' x)) l := is_O_with.is_O is_O_with_snd_prod theorem is_O_fst_prod' {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {l : filter α} {f' : α → E' × F'} : is_O (fun (x : α) => prod.fst (f' x)) f' l := is_O_fst_prod theorem is_O_snd_prod' {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {l : filter α} {f' : α → E' × F'} : is_O (fun (x : α) => prod.snd (f' x)) f' l := is_O_snd_prod theorem is_O_with.prod_rightl {α : Type u_1} {E : Type u_3} {F' : Type u_7} {G' : Type u_8} [has_norm E] [normed_group F'] [normed_group G'] {c : ℝ} {f : α → E} {g' : α → F'} (k' : α → G') {l : filter α} (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (fun (x : α) => (g' x, k' x)) l := is_O_with.congr_const (mul_one c) (is_O_with.trans h is_O_with_fst_prod hc) theorem is_O.prod_rightl {α : Type u_1} {E : Type u_3} {F' : Type u_7} {G' : Type u_8} [has_norm E] [normed_group F'] [normed_group G'] {f : α → E} {g' : α → F'} (k' : α → G') {l : filter α} (h : is_O f g' l) : is_O f (fun (x : α) => (g' x, k' x)) l := sorry theorem is_o.prod_rightl {α : Type u_1} {E : Type u_3} {F' : Type u_7} {G' : Type u_8} [has_norm E] [normed_group F'] [normed_group G'] {f : α → E} {g' : α → F'} (k' : α → G') {l : filter α} (h : is_o f g' l) : is_o f (fun (x : α) => (g' x, k' x)) l := fun (c : ℝ) (cpos : 0 < c) => is_O_with.prod_rightl k' (h cpos) (le_of_lt cpos) theorem is_O_with.prod_rightr {α : Type u_1} {E : Type u_3} {E' : Type u_6} {F' : Type u_7} [has_norm E] [normed_group E'] [normed_group F'] {c : ℝ} {f : α → E} (f' : α → E') {g' : α → F'} {l : filter α} (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (fun (x : α) => (f' x, g' x)) l := is_O_with.congr_const (mul_one c) (is_O_with.trans h is_O_with_snd_prod hc) theorem is_O.prod_rightr {α : Type u_1} {E : Type u_3} {E' : Type u_6} {F' : Type u_7} [has_norm E] [normed_group E'] [normed_group F'] {f : α → E} (f' : α → E') {g' : α → F'} {l : filter α} (h : is_O f g' l) : is_O f (fun (x : α) => (f' x, g' x)) l := sorry theorem is_o.prod_rightr {α : Type u_1} {E : Type u_3} {E' : Type u_6} {F' : Type u_7} [has_norm E] [normed_group E'] [normed_group F'] {f : α → E} (f' : α → E') {g' : α → F'} {l : filter α} (h : is_o f g' l) : is_o f (fun (x : α) => (f' x, g' x)) l := fun (c : ℝ) (cpos : 0 < c) => is_O_with.prod_rightr f' (h cpos) (le_of_lt cpos) theorem is_O_with.prod_left_same {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {c : ℝ} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (hf : is_O_with c f' k' l) (hg : is_O_with c g' k' l) : is_O_with c (fun (x : α) => (f' x, g' x)) k' l := filter.mp_sets hg (filter.mp_sets hf (filter.univ_mem_sets' (id fun (x : α) => max_le))) theorem is_O_with.prod_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {c : ℝ} {c' : ℝ} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (hf : is_O_with c f' k' l) (hg : is_O_with c' g' k' l) : is_O_with (max c c') (fun (x : α) => (f' x, g' x)) k' l := is_O_with.prod_left_same (is_O_with.weaken hf (le_max_left c c')) (is_O_with.weaken hg (le_max_right c c')) theorem is_O_with.prod_left_fst {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {c : ℝ} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (h : is_O_with c (fun (x : α) => (f' x, g' x)) k' l) : is_O_with c f' k' l := is_O_with.congr_const (one_mul c) (is_O_with.trans is_O_with_fst_prod h zero_le_one) theorem is_O_with.prod_left_snd {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {c : ℝ} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (h : is_O_with c (fun (x : α) => (f' x, g' x)) k' l) : is_O_with c g' k' l := is_O_with.congr_const (one_mul c) (is_O_with.trans is_O_with_snd_prod h zero_le_one) theorem is_O_with_prod_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {c : ℝ} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} : is_O_with c (fun (x : α) => (f' x, g' x)) k' l ↔ is_O_with c f' k' l ∧ is_O_with c g' k' l := sorry theorem is_O.prod_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (hf : is_O f' k' l) (hg : is_O g' k' l) : is_O (fun (x : α) => (f' x, g' x)) k' l := sorry theorem is_O.prod_left_fst {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (h : is_O (fun (x : α) => (f' x, g' x)) k' l) : is_O f' k' l := is_O.trans is_O_fst_prod h theorem is_O.prod_left_snd {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (h : is_O (fun (x : α) => (f' x, g' x)) k' l) : is_O g' k' l := is_O.trans is_O_snd_prod h @[simp] theorem is_O_prod_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} : is_O (fun (x : α) => (f' x, g' x)) k' l ↔ is_O f' k' l ∧ is_O g' k' l := sorry theorem is_o.prod_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (hf : is_o f' k' l) (hg : is_o g' k' l) : is_o (fun (x : α) => (f' x, g' x)) k' l := fun (c : ℝ) (hc : 0 < c) => is_O_with.prod_left_same (hf hc) (hg hc) theorem is_o.prod_left_fst {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (h : is_o (fun (x : α) => (f' x, g' x)) k' l) : is_o f' k' l := is_O.trans_is_o is_O_fst_prod h theorem is_o.prod_left_snd {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} (h : is_o (fun (x : α) => (f' x, g' x)) k' l) : is_o g' k' l := is_O.trans_is_o is_O_snd_prod h @[simp] theorem is_o_prod_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {G' : Type u_8} [normed_group E'] [normed_group F'] [normed_group G'] {f' : α → E'} {g' : α → F'} {k' : α → G'} {l : filter α} : is_o (fun (x : α) => (f' x, g' x)) k' l ↔ is_o f' k' l ∧ is_o g' k' l := sorry theorem is_O_with.eq_zero_imp {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {c : ℝ} {f' : α → E'} {g' : α → F'} {l : filter α} (h : is_O_with c f' g' l) : filter.eventually (fun (x : α) => g' x = 0 → f' x = 0) l := sorry theorem is_O.eq_zero_imp {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} (h : is_O f' g' l) : filter.eventually (fun (x : α) => g' x = 0 → f' x = 0) l := sorry /-! ### Addition and subtraction -/ theorem is_O_with.add {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (fun (x : α) => f₁ x + f₂ x) g l := sorry theorem is_O.add {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} : is_O f₁ g l → is_O f₂ g l → is_O (fun (x : α) => f₁ x + f₂ x) g l := sorry theorem is_o.add {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (fun (x : α) => f₁ x + f₂ x) g l := fun (c : ℝ) (cpos : 0 < c) => is_O_with.congr_const (add_halves c) (is_O_with.add (h₁ (half_pos cpos)) (h₂ (half_pos cpos))) theorem is_o.add_add {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {l : filter α} {f₁ : α → E'} {f₂ : α → E'} {g₁ : α → F'} {g₂ : α → F'} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (fun (x : α) => f₁ x + f₂ x) (fun (x : α) => norm (g₁ x) + norm (g₂ x)) l := sorry theorem is_O.add_is_o {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_O f₁ g l) (h₂ : is_o f₂ g l) : is_O (fun (x : α) => f₁ x + f₂ x) g l := is_O.add h₁ (is_o.is_O h₂) theorem is_o.add_is_O {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_o f₁ g l) (h₂ : is_O f₂ g l) : is_O (fun (x : α) => f₁ x + f₂ x) g l := is_O.add (is_o.is_O h₁) h₂ theorem is_O_with.add_is_o {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (fun (x : α) => f₁ x + f₂ x) g l := is_O_with.congr_const (add_sub_cancel'_right c₁ c₂) (is_O_with.add h₁ (h₂ (iff.mpr sub_pos hc))) theorem is_o.add_is_O_with {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_o f₁ g l) (h₂ : is_O_with c₁ f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (fun (x : α) => f₁ x + f₂ x) g l := is_O_with.congr_left (fun (_x : α) => add_comm (f₂ _x) (f₁ _x)) (is_O_with.add_is_o h₂ h₁ hc) theorem is_O_with.sub {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (fun (x : α) => f₁ x - f₂ x) g l := sorry theorem is_O_with.sub_is_o {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {c₁ : ℝ} {c₂ : ℝ} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (fun (x : α) => f₁ x - f₂ x) g l := sorry theorem is_O.sub {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (fun (x : α) => f₁ x - f₂ x) g l := sorry theorem is_o.sub {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (fun (x : α) => f₁ x - f₂ x) g l := sorry /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ theorem is_O_with.symm {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_O_with c (fun (x : α) => f₁ x - f₂ x) g l) : is_O_with c (fun (x : α) => f₂ x - f₁ x) g l := is_O_with.congr_left (fun (x : α) => neg_sub (f₁ x) (f₂ x)) (is_O_with.neg_left h) theorem is_O_with_comm {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} : is_O_with c (fun (x : α) => f₁ x - f₂ x) g l ↔ is_O_with c (fun (x : α) => f₂ x - f₁ x) g l := { mp := is_O_with.symm, mpr := is_O_with.symm } theorem is_O.symm {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_O (fun (x : α) => f₁ x - f₂ x) g l) : is_O (fun (x : α) => f₂ x - f₁ x) g l := is_O.congr_left (fun (x : α) => neg_sub (f₁ x) (f₂ x)) (is_O.neg_left h) theorem is_O_comm {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} : is_O (fun (x : α) => f₁ x - f₂ x) g l ↔ is_O (fun (x : α) => f₂ x - f₁ x) g l := { mp := is_O.symm, mpr := is_O.symm } theorem is_o.symm {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_o (fun (x : α) => f₁ x - f₂ x) g l) : is_o (fun (x : α) => f₂ x - f₁ x) g l := sorry theorem is_o_comm {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} : is_o (fun (x : α) => f₁ x - f₂ x) g l ↔ is_o (fun (x : α) => f₂ x - f₁ x) g l := { mp := is_o.symm, mpr := is_o.symm } theorem is_O_with.triangle {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {c : ℝ} {c' : ℝ} {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} {f₃ : α → E'} (h₁ : is_O_with c (fun (x : α) => f₁ x - f₂ x) g l) (h₂ : is_O_with c' (fun (x : α) => f₂ x - f₃ x) g l) : is_O_with (c + c') (fun (x : α) => f₁ x - f₃ x) g l := is_O_with.congr_left (fun (x : α) => sub_add_sub_cancel (f₁ x) (f₂ x) (f₃ x)) (is_O_with.add h₁ h₂) theorem is_O.triangle {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} {f₃ : α → E'} (h₁ : is_O (fun (x : α) => f₁ x - f₂ x) g l) (h₂ : is_O (fun (x : α) => f₂ x - f₃ x) g l) : is_O (fun (x : α) => f₁ x - f₃ x) g l := is_O.congr_left (fun (x : α) => sub_add_sub_cancel (f₁ x) (f₂ x) (f₃ x)) (is_O.add h₁ h₂) theorem is_o.triangle {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} {f₃ : α → E'} (h₁ : is_o (fun (x : α) => f₁ x - f₂ x) g l) (h₂ : is_o (fun (x : α) => f₂ x - f₃ x) g l) : is_o (fun (x : α) => f₁ x - f₃ x) g l := is_o.congr_left (fun (x : α) => sub_add_sub_cancel (f₁ x) (f₂ x) (f₃ x)) (is_o.add h₁ h₂) theorem is_O.congr_of_sub {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_O (fun (x : α) => f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := { mp := fun (h' : is_O f₁ g l) => is_O.congr_left (fun (x : α) => sub_sub_cancel (f₁ x) (f₂ x)) (is_O.sub h' h), mpr := fun (h' : is_O f₂ g l) => is_O.congr_left (fun (x : α) => sub_add_cancel (f₁ x) (f₂ x)) (is_O.add h h') } theorem is_o.congr_of_sub {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_o (fun (x : α) => f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := { mp := fun (h' : is_o f₁ g l) => is_o.congr_left (fun (x : α) => sub_sub_cancel (f₁ x) (f₂ x)) (is_o.sub h' h), mpr := fun (h' : is_o f₂ g l) => is_o.congr_left (fun (x : α) => sub_add_cancel (f₁ x) (f₂ x)) (is_o.add h h') } /-! ### Zero, one, and other constants -/ theorem is_o_zero {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] (g' : α → F') (l : filter α) : is_o (fun (x : α) => 0) g' l := sorry theorem is_O_with_zero {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {c : ℝ} (g' : α → F') (l : filter α) (hc : 0 ≤ c) : is_O_with c (fun (x : α) => 0) g' l := sorry theorem is_O_with_zero' {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] (g : α → F) (l : filter α) : is_O_with 0 (fun (x : α) => 0) g l := sorry theorem is_O_zero {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] (g : α → F) (l : filter α) : is_O (fun (x : α) => 0) g l := Exists.intro 0 (is_O_with_zero' g l) theorem is_O_refl_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} (g' : α → F') (l : filter α) : is_O (fun (x : α) => f' x - f' x) g' l := is_O.congr_left (fun (x : α) => Eq.symm (sub_self (f' x))) (is_O_zero g' l) theorem is_o_refl_left {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} (g' : α → F') (l : filter α) : is_o (fun (x : α) => f' x - f' x) g' l := is_o.congr_left (fun (x : α) => Eq.symm (sub_self (f' x))) (is_o_zero g' l) @[simp] theorem is_O_with_zero_right_iff {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {c : ℝ} {f' : α → E'} {l : filter α} : is_O_with c f' (fun (x : α) => 0) l ↔ filter.eventually (fun (x : α) => f' x = 0) l := sorry @[simp] theorem is_O_zero_right_iff {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {l : filter α} : is_O f' (fun (x : α) => 0) l ↔ filter.eventually (fun (x : α) => f' x = 0) l := sorry @[simp] theorem is_o_zero_right_iff {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {l : filter α} : is_o f' (fun (x : α) => 0) l ↔ filter.eventually (fun (x : α) => f' x = 0) l := { mp := fun (h : is_o f' (fun (x : α) => 0) l) => iff.mp is_O_zero_right_iff (is_o.is_O h), mpr := fun (h : filter.eventually (fun (x : α) => f' x = 0) l) (c : ℝ) (hc : 0 < c) => iff.mpr is_O_with_zero_right_iff h } theorem is_O_with_const_const {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O_with (norm c / norm c') (fun (x : α) => c) (fun (x : α) => c') l := sorry theorem is_O_const_const {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O (fun (x : α) => c) (fun (x : α) => c') l := is_O_with.is_O (is_O_with_const_const c hc' l) @[simp] theorem is_O_with_top {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} : is_O_with c f g ⊤ ↔ ∀ (x : α), norm (f x) ≤ c * norm (g x) := iff.rfl @[simp] theorem is_O_top {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} : is_O f g ⊤ ↔ ∃ (C : ℝ), ∀ (x : α), norm (f x) ≤ C * norm (g x) := iff.rfl @[simp] theorem is_o_top {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} : is_o f' g' ⊤ ↔ ∀ (x : α), f' x = 0 := sorry @[simp] theorem is_O_with_principal {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {c : ℝ} {f : α → E} {g : α → F} {s : set α} : is_O_with c f g (filter.principal s) ↔ ∀ (x : α), x ∈ s → norm (f x) ≤ c * norm (g x) := iff.rfl theorem is_O_principal {α : Type u_1} {E : Type u_3} {F : Type u_4} [has_norm E] [has_norm F] {f : α → E} {g : α → F} {s : set α} : is_O f g (filter.principal s) ↔ ∃ (c : ℝ), ∀ (x : α), x ∈ s → norm (f x) ≤ c * norm (g x) := iff.rfl theorem is_O_with_const_one {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] (c : E) (l : filter α) : is_O_with (norm c) (fun (x : α) => c) (fun (x : α) => 1) l := sorry theorem is_O_const_one {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] (c : E) (l : filter α) : is_O (fun (x : α) => c) (fun (x : α) => 1) l := is_O_with.is_O (is_O_with_const_one c l) theorem is_o_const_iff_is_o_one {α : Type u_1} {E : Type u_3} {F' : Type u_7} (𝕜 : Type u_11) [has_norm E] [normed_group F'] [normed_field 𝕜] {f : α → E} {l : filter α} {c : F'} (hc : c ≠ 0) : is_o f (fun (x : α) => c) l ↔ is_o f (fun (x : α) => 1) l := { mp := fun (h : is_o f (fun (x : α) => c) l) => is_o.trans_is_O h (is_O_const_one c l), mpr := fun (h : is_o f (fun (x : α) => 1) l) => is_o.trans_is_O h (is_O_const_const 1 hc l) } theorem is_o_const_iff {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {l : filter α} {c : F'} (hc : c ≠ 0) : is_o f' (fun (x : α) => c) l ↔ filter.tendsto f' l (nhds 0) := sorry theorem is_o_id_const {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {c : F'} (hc : c ≠ 0) : is_o (fun (x : E') => x) (fun (x : E') => c) (nhds 0) := iff.mpr (is_o_const_iff hc) (continuous.tendsto continuous_id 0) theorem is_O_const_of_tendsto {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {l : filter α} {y : E'} (h : filter.tendsto f' l (nhds y)) {c : F'} (hc : c ≠ 0) : is_O f' (fun (x : α) => c) l := sorry theorem is_o_one_iff {α : Type u_1} {E' : Type u_6} (𝕜 : Type u_11) [normed_group E'] [normed_field 𝕜] {f' : α → E'} {l : filter α} : is_o f' (fun (x : α) => 1) l ↔ filter.tendsto f' l (nhds 0) := is_o_const_iff one_ne_zero theorem is_O_one_of_tendsto {α : Type u_1} {E' : Type u_6} (𝕜 : Type u_11) [normed_group E'] [normed_field 𝕜] {f' : α → E'} {l : filter α} {y : E'} (h : filter.tendsto f' l (nhds y)) : is_O f' (fun (x : α) => 1) l := is_O_const_of_tendsto h one_ne_zero theorem is_O.trans_tendsto_nhds {α : Type u_1} {E : Type u_3} {F' : Type u_7} (𝕜 : Type u_11) [has_norm E] [normed_group F'] [normed_field 𝕜] {f : α → E} {g' : α → F'} {l : filter α} (hfg : is_O f g' l) {y : F'} (hg : filter.tendsto g' l (nhds y)) : is_O f (fun (x : α) => 1) l := is_O.trans hfg (is_O_one_of_tendsto 𝕜 hg) theorem is_O.trans_tendsto {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} (hfg : is_O f' g' l) (hg : filter.tendsto g' l (nhds 0)) : filter.tendsto f' l (nhds 0) := iff.mp (is_o_one_iff ℝ) (is_O.trans_is_o hfg (iff.mpr (is_o_one_iff ℝ) hg)) theorem is_o.trans_tendsto {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} {l : filter α} (hfg : is_o f' g' l) (hg : filter.tendsto g' l (nhds 0)) : filter.tendsto f' l (nhds 0) := is_O.trans_tendsto (is_o.is_O hfg) hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self {α : Type u_1} {R : Type u_9} [normed_ring R] (c : R) (f : α → R) (l : filter α) : is_O_with (norm c) (fun (x : α) => c * f x) f l := is_O_with_of_le' l fun (x : α) => norm_mul_le c (f x) theorem is_O_const_mul_self {α : Type u_1} {R : Type u_9} [normed_ring R] (c : R) (f : α → R) (l : filter α) : is_O (fun (x : α) => c * f x) f l := is_O_with.is_O (is_O_with_const_mul_self c f l) theorem is_O_with.const_mul_left {α : Type u_1} {F : Type u_4} {R : Type u_9} [has_norm F] [normed_ring R] {c : ℝ} {g : α → F} {l : filter α} {f : α → R} (h : is_O_with c f g l) (c' : R) : is_O_with (norm c' * c) (fun (x : α) => c' * f x) g l := is_O_with.trans (is_O_with_const_mul_self c' f l) h (norm_nonneg c') theorem is_O.const_mul_left {α : Type u_1} {F : Type u_4} {R : Type u_9} [has_norm F] [normed_ring R] {g : α → F} {l : filter α} {f : α → R} (h : is_O f g l) (c' : R) : is_O (fun (x : α) => c' * f x) g l := sorry theorem is_O_with_self_const_mul' {α : Type u_1} {R : Type u_9} [normed_ring R] (u : units R) (f : α → R) (l : filter α) : is_O_with (norm ↑(u⁻¹)) f (fun (x : α) => ↑u * f x) l := is_O_with.congr_left (fun (x : α) => units.inv_mul_cancel_left u (f x)) (is_O_with_const_mul_self (↑(u⁻¹)) (fun (x : α) => ↑u * f x) l) theorem is_O_with_self_const_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with (norm c⁻¹) f (fun (x : α) => c * f x) l := is_O_with.congr_const (normed_field.norm_inv c) (is_O_with_self_const_mul' (units.mk0 c hc) f l) theorem is_O_self_const_mul' {α : Type u_1} {R : Type u_9} [normed_ring R] {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : is_O f (fun (x : α) => c * f x) l := sorry theorem is_O_self_const_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O f (fun (x : α) => c * f x) l := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {α : Type u_1} {F : Type u_4} {R : Type u_9} [has_norm F] [normed_ring R] {g : α → F} {l : filter α} {f : α → R} {c : R} (hc : is_unit c) : is_O (fun (x : α) => c * f x) g l ↔ is_O f g l := { mp := is_O.trans (is_O_self_const_mul' hc f l), mpr := fun (h : is_O f g l) => is_O.const_mul_left h c } theorem is_O_const_mul_left_iff {α : Type u_1} {F : Type u_4} {𝕜 : Type u_11} [has_norm F] [normed_field 𝕜] {g : α → F} {l : filter α} {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O (fun (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 {α : Type u_1} {F : Type u_4} {R : Type u_9} [has_norm F] [normed_ring R] {g : α → F} {l : filter α} {f : α → R} (h : is_o f g l) (c : R) : is_o (fun (x : α) => c * f x) g l := is_O.trans_is_o (is_O_const_mul_self c f l) h theorem is_o_const_mul_left_iff' {α : Type u_1} {F : Type u_4} {R : Type u_9} [has_norm F] [normed_ring R] {g : α → F} {l : filter α} {f : α → R} {c : R} (hc : is_unit c) : is_o (fun (x : α) => c * f x) g l ↔ is_o f g l := { mp := is_O.trans_is_o (is_O_self_const_mul' hc f l), mpr := fun (h : is_o f g l) => is_o.const_mul_left h c } theorem is_o_const_mul_left_iff {α : Type u_1} {F : Type u_4} {𝕜 : Type u_11} [has_norm F] [normed_field 𝕜] {g : α → F} {l : filter α} {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o (fun (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 {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {c' : ℝ} {f : α → E} {l : filter α} {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' f (fun (x : α) => c * g x) l) : is_O_with (c' * norm c) f g l := is_O_with.trans h (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {c : R} (h : is_O f (fun (x : α) => c * g x) l) : is_O f g l := sorry theorem is_O_with.const_mul_right' {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {u : units R} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * norm ↑(u⁻¹)) f (fun (x : α) => ↑u * g x) l := is_O_with.trans h (is_O_with_self_const_mul' u g l) hc' theorem is_O_with.const_mul_right {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] {f : α → E} {l : filter α} {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * (norm c⁻¹)) f (fun (x : α) => c * g x) l := is_O_with.trans h (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {c : R} (hc : is_unit c) (h : is_O f g l) : is_O f (fun (x : α) => c * g x) l := is_O.trans h (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] {f : α → E} {l : filter α} {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_O f g l) : is_O f (fun (x : α) => c * g x) l := is_O.const_mul_right' (is_unit.mk0 c hc) h theorem is_O_const_mul_right_iff' {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {c : R} (hc : is_unit c) : is_O f (fun (x : α) => c * g x) l ↔ is_O f g l := { mp := fun (h : is_O f (fun (x : α) => c * g x) l) => is_O.of_const_mul_right h, mpr := fun (h : is_O f g l) => is_O.const_mul_right' hc h } theorem is_O_const_mul_right_iff {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] {f : α → E} {l : filter α} {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O f (fun (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 {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {c : R} (h : is_o f (fun (x : α) => c * g x) l) : is_o f g l := is_o.trans_is_O h (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {c : R} (hc : is_unit c) (h : is_o f g l) : is_o f (fun (x : α) => c * g x) l := is_o.trans_is_O h (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] {f : α → E} {l : filter α} {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_o f g l) : is_o f (fun (x : α) => c * g x) l := is_o.const_mul_right' (is_unit.mk0 c hc) h theorem is_o_const_mul_right_iff' {α : Type u_1} {E : Type u_3} {R : Type u_9} [has_norm E] [normed_ring R] {f : α → E} {l : filter α} {g : α → R} {c : R} (hc : is_unit c) : is_o f (fun (x : α) => c * g x) l ↔ is_o f g l := { mp := fun (h : is_o f (fun (x : α) => c * g x) l) => is_o.of_const_mul_right h, mpr := fun (h : is_o f g l) => is_o.const_mul_right' hc h } theorem is_o_const_mul_right_iff {α : Type u_1} {E : Type u_3} {𝕜 : Type u_11} [has_norm E] [normed_field 𝕜] {f : α → E} {l : filter α} {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o f (fun (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 {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f₁ : α → R} {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₂) (fun (x : α) => f₁ x * f₂ x) (fun (x : α) => g₁ x * g₂ x) l := sorry theorem is_O.mul {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f₁ : α → R} {f₂ : α → R} {g₁ : α → 𝕜} {g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (fun (x : α) => f₁ x * f₂ x) (fun (x : α) => g₁ x * g₂ x) l := sorry theorem is_O.mul_is_o {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f₁ : α → R} {f₂ : α → R} {g₁ : α → 𝕜} {g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (fun (x : α) => f₁ x * f₂ x) (fun (x : α) => g₁ x * g₂ x) l := sorry theorem is_o.mul_is_O {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f₁ : α → R} {f₂ : α → R} {g₁ : α → 𝕜} {g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_o (fun (x : α) => f₁ x * f₂ x) (fun (x : α) => g₁ x * g₂ x) l := sorry theorem is_o.mul {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f₁ : α → R} {f₂ : α → R} {g₁ : α → 𝕜} {g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (fun (x : α) => f₁ x * f₂ x) (fun (x : α) => g₁ x * g₂ x) l := is_o.mul_is_O h₁ (is_o.is_O h₂) theorem is_O_with.pow' {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {c : ℝ} {l : filter α} {f : α → R} {g : α → 𝕜} (h : is_O_with c f g l) (n : ℕ) : is_O_with (nat.cases_on n (norm 1) fun (n : ℕ) => c ^ (n + 1)) (fun (x : α) => f x ^ n) (fun (x : α) => g x ^ n) l := sorry theorem is_O_with.pow {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {c : ℝ} {l : filter α} [norm_one_class R] {f : α → R} {g : α → 𝕜} (h : is_O_with c f g l) (n : ℕ) : is_O_with (c ^ n) (fun (x : α) => f x ^ n) (fun (x : α) => g x ^ n) l := sorry theorem is_O.pow {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f : α → R} {g : α → 𝕜} (h : is_O f g l) (n : ℕ) : is_O (fun (x : α) => f x ^ n) (fun (x : α) => g x ^ n) l := sorry theorem is_o.pow {α : Type u_1} {R : Type u_9} {𝕜 : Type u_11} [normed_ring R] [normed_field 𝕜] {l : filter α} {f : α → R} {g : α → 𝕜} (h : is_o f g l) {n : ℕ} (hn : 0 < n) : is_o (fun (x : α) => f x ^ n) (fun (x : α) => g x ^ n) l := sorry /-! ### Scalar multiplication -/ theorem is_O_with.const_smul_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} {𝕜 : Type u_11} [has_norm F] [normed_group E'] [normed_field 𝕜] {c : ℝ} {g : α → F} {f' : α → E'} {l : filter α} [normed_space 𝕜 E'] (h : is_O_with c f' g l) (c' : 𝕜) : is_O_with (norm c' * c) (fun (x : α) => c' • f' x) g l := sorry theorem is_O_const_smul_left_iff {α : Type u_1} {F : Type u_4} {E' : Type u_6} {𝕜 : Type u_11} [has_norm F] [normed_group E'] [normed_field 𝕜] {g : α → F} {f' : α → E'} {l : filter α} [normed_space 𝕜 E'] {c : 𝕜} (hc : c ≠ 0) : is_O (fun (x : α) => c • f' x) g l ↔ is_O f' g l := sorry theorem is_o_const_smul_left {α : Type u_1} {F : Type u_4} {E' : Type u_6} {𝕜 : Type u_11} [has_norm F] [normed_group E'] [normed_field 𝕜] {g : α → F} {f' : α → E'} {l : filter α} [normed_space 𝕜 E'] (h : is_o f' g l) (c : 𝕜) : is_o (fun (x : α) => c • f' x) g l := is_o.of_norm_left (is_o.congr_left (fun (x : α) => Eq.symm (norm_smul c (f' x))) (is_o.const_mul_left (is_o.norm_left h) (norm c))) theorem is_o_const_smul_left_iff {α : Type u_1} {F : Type u_4} {E' : Type u_6} {𝕜 : Type u_11} [has_norm F] [normed_group E'] [normed_field 𝕜] {g : α → F} {f' : α → E'} {l : filter α} [normed_space 𝕜 E'] {c : 𝕜} (hc : c ≠ 0) : is_o (fun (x : α) => c • f' x) g l ↔ is_o f' g l := sorry theorem is_O_const_smul_right {α : Type u_1} {E : Type u_3} {E' : Type u_6} {𝕜 : Type u_11} [has_norm E] [normed_group E'] [normed_field 𝕜] {f : α → E} {f' : α → E'} {l : filter α} [normed_space 𝕜 E'] {c : 𝕜} (hc : c ≠ 0) : is_O f (fun (x : α) => c • f' x) l ↔ is_O f f' l := sorry theorem is_o_const_smul_right {α : Type u_1} {E : Type u_3} {E' : Type u_6} {𝕜 : Type u_11} [has_norm E] [normed_group E'] [normed_field 𝕜] {f : α → E} {f' : α → E'} {l : filter α} [normed_space 𝕜 E'] {c : 𝕜} (hc : c ≠ 0) : is_o f (fun (x : α) => c • f' x) l ↔ is_o f f' l := sorry theorem is_O_with.smul {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {𝕜 : Type u_11} [normed_group E'] [normed_group F'] [normed_field 𝕜] {c : ℝ} {c' : ℝ} {f' : α → E'} {g' : α → F'} {l : filter α} [normed_space 𝕜 E'] [normed_space 𝕜 F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜} (h₁ : is_O_with c k₁ k₂ l) (h₂ : is_O_with c' f' g' l) : is_O_with (c * c') (fun (x : α) => k₁ x • f' x) (fun (x : α) => k₂ x • g' x) l := sorry theorem is_O.smul {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {𝕜 : Type u_11} [normed_group E'] [normed_group F'] [normed_field 𝕜] {f' : α → E'} {g' : α → F'} {l : filter α} [normed_space 𝕜 E'] [normed_space 𝕜 F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_O f' g' l) : is_O (fun (x : α) => k₁ x • f' x) (fun (x : α) => k₂ x • g' x) l := sorry theorem is_O.smul_is_o {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {𝕜 : Type u_11} [normed_group E'] [normed_group F'] [normed_field 𝕜] {f' : α → E'} {g' : α → F'} {l : filter α} [normed_space 𝕜 E'] [normed_space 𝕜 F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (fun (x : α) => k₁ x • f' x) (fun (x : α) => k₂ x • g' x) l := sorry theorem is_o.smul_is_O {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {𝕜 : Type u_11} [normed_group E'] [normed_group F'] [normed_field 𝕜] {f' : α → E'} {g' : α → F'} {l : filter α} [normed_space 𝕜 E'] [normed_space 𝕜 F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_O f' g' l) : is_o (fun (x : α) => k₁ x • f' x) (fun (x : α) => k₂ x • g' x) l := sorry theorem is_o.smul {α : Type u_1} {E' : Type u_6} {F' : Type u_7} {𝕜 : Type u_11} [normed_group E'] [normed_group F'] [normed_field 𝕜] {f' : α → E'} {g' : α → F'} {l : filter α} [normed_space 𝕜 E'] [normed_space 𝕜 F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (fun (x : α) => k₁ x • f' x) (fun (x : α) => k₂ x • g' x) l := sorry /-! ### Sum -/ theorem is_O_with.sum {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {ι : Type u_13} {A : ι → α → E'} {C : ι → ℝ} {s : finset ι} (h : ∀ (i : ι), i ∈ s → is_O_with (C i) (A i) g l) : is_O_with (finset.sum s fun (i : ι) => C i) (fun (x : α) => finset.sum s fun (i : ι) => A i x) g l := sorry theorem is_O.sum {α : Type u_1} {F : Type u_4} {E' : Type u_6} [has_norm F] [normed_group E'] {g : α → F} {l : filter α} {ι : Type u_13} {A : ι → α → E'} {s : finset ι} (h : ∀ (i : ι), i ∈ s → is_O (A i) g l) : is_O (fun (x : α) => finset.sum s fun (i : ι) => A i x) g l := sorry theorem is_o.sum {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {g' : α → F'} {l : filter α} {ι : Type u_13} {A : ι → α → E'} {s : finset ι} (h : ∀ (i : ι), i ∈ s → is_o (A i) g' l) : is_o (fun (x : α) => finset.sum s fun (i : ι) => A i x) g' l := sorry /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_0 {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {f : α → 𝕜} {g : α → 𝕜} {l : filter α} (h : is_o f g l) : filter.tendsto (fun (x : α) => f x / g x) l (nhds 0) := sorry theorem is_o_iff_tendsto' {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {f : α → 𝕜} {g : α → 𝕜} {l : filter α} (hgf : filter.eventually (fun (x : α) => g x = 0 → f x = 0) l) : is_o f g l ↔ filter.tendsto (fun (x : α) => f x / g x) l (nhds 0) := sorry theorem is_o_iff_tendsto {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {f : α → 𝕜} {g : α → 𝕜} {l : filter α} (hgf : ∀ (x : α), g x = 0 → f x = 0) : is_o f g l ↔ filter.tendsto (fun (x : α) => f x / g x) l (nhds 0) := { mp := fun (h : is_o f g l) => is_o.tendsto_0 h, mpr := iff.mpr (is_o_iff_tendsto' (filter.eventually_of_forall hgf)) } theorem is_o_of_tendsto' {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {f : α → 𝕜} {g : α → 𝕜} {l : filter α} (hgf : filter.eventually (fun (x : α) => g x = 0 → f x = 0) l) : filter.tendsto (fun (x : α) => f x / g x) l (nhds 0) → is_o f g l := iff.mpr (is_o_iff_tendsto' hgf) theorem is_o_of_tendsto {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {f : α → 𝕜} {g : α → 𝕜} {l : filter α} (hgf : ∀ (x : α), g x = 0 → f x = 0) : filter.tendsto (fun (x : α) => f x / g x) l (nhds 0) → is_o f g l := iff.mpr (is_o_iff_tendsto hgf) /-! ### Eventually (u / v) * v = u If `u` and `v` are linked by an `is_O_with` relation, then we eventually have `(u / v) * v = u`, even if `v` vanishes. -/ theorem is_O_with.eventually_mul_div_cancel {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {c : ℝ} {l : filter α} {u : α → 𝕜} {v : α → 𝕜} (h : is_O_with c u v l) : filter.eventually_eq l (u / v * v) u := sorry /-- If `u = O(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ theorem is_O.eventually_mul_div_cancel {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {l : filter α} {u : α → 𝕜} {v : α → 𝕜} (h : is_O u v l) : filter.eventually_eq l (u / v * v) u := sorry /-- If `u = o(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ theorem is_o.eventually_mul_div_cancel {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {l : filter α} {u : α → 𝕜} {v : α → 𝕜} (h : is_o u v l) : filter.eventually_eq l (u / v * v) u := is_O_with.eventually_mul_div_cancel (h zero_lt_one) /-! ### Equivalent definitions of the form `∃ φ, u =ᶠ[l] φ * v` in a `normed_field`. -/ /-- If `∥φ∥` is eventually bounded by `c`, and `u =ᶠ[l] φ * v`, then we have `is_O_with c u v l`. This does not require any assumptions on `c`, which is why we keep this version along with `is_O_with_iff_exists_eq_mul`. -/ theorem is_O_with_of_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {c : ℝ} {l : filter α} {u : α → 𝕜} {v : α → 𝕜} (φ : α → 𝕜) (hφ : filter.eventually (fun (x : α) => norm (φ x) ≤ c) l) (h : filter.eventually_eq l u (φ * v)) : is_O_with c u v l := sorry theorem is_O_with_iff_exists_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {c : ℝ} {l : filter α} {u : α → 𝕜} {v : α → 𝕜} (hc : 0 ≤ c) : is_O_with c u v l ↔ ∃ (φ : α → 𝕜), ∃ (hφ : filter.eventually (fun (x : α) => norm (φ x) ≤ c) l), filter.eventually_eq l u (φ * v) := sorry theorem is_O_with.exists_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {c : ℝ} {l : filter α} {u : α → 𝕜} {v : α → 𝕜} (h : is_O_with c u v l) (hc : 0 ≤ c) : ∃ (φ : α → 𝕜), ∃ (hφ : filter.eventually (fun (x : α) => norm (φ x) ≤ c) l), filter.eventually_eq l u (φ * v) := iff.mp (is_O_with_iff_exists_eq_mul hc) h theorem is_O_iff_exists_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {l : filter α} {u : α → 𝕜} {v : α → 𝕜} : is_O u v l ↔ ∃ (φ : α → 𝕜), ∃ (hφ : filter.is_bounded_under LessEq l (norm ∘ φ)), filter.eventually_eq l u (φ * v) := sorry theorem is_O.exists_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {l : filter α} {u : α → 𝕜} {v : α → 𝕜} : is_O u v l → ∃ (φ : α → 𝕜), ∃ (hφ : filter.is_bounded_under LessEq l (norm ∘ φ)), filter.eventually_eq l u (φ * v) := iff.mp is_O_iff_exists_eq_mul theorem is_o_iff_exists_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {l : filter α} {u : α → 𝕜} {v : α → 𝕜} : is_o u v l ↔ ∃ (φ : α → 𝕜), ∃ (hφ : filter.tendsto φ l (nhds 0)), filter.eventually_eq l u (φ * v) := sorry theorem is_o.exists_eq_mul {α : Type u_1} {𝕜 : Type u_11} [normed_field 𝕜] {l : filter α} {u : α → 𝕜} {v : α → 𝕜} : is_o u v l → ∃ (φ : α → 𝕜), ∃ (hφ : filter.tendsto φ l (nhds 0)), filter.eventually_eq l u (φ * v) := iff.mp is_o_iff_exists_eq_mul /-! ### Miscellanous lemmas -/ theorem is_o_pow_pow {𝕜 : Type u_11} [normed_field 𝕜] {m : ℕ} {n : ℕ} (h : m < n) : is_o (fun (x : 𝕜) => x ^ n) (fun (x : 𝕜) => x ^ m) (nhds 0) := sorry theorem is_o_norm_pow_norm_pow {E' : Type u_6} [normed_group E'] {m : ℕ} {n : ℕ} (h : m < n) : is_o (fun (x : E') => norm x ^ n) (fun (x : E') => norm x ^ m) (nhds 0) := is_o.comp_tendsto (is_o_pow_pow h) tendsto_norm_zero theorem is_o_pow_id {𝕜 : Type u_11} [normed_field 𝕜] {n : ℕ} (h : 1 < n) : is_o (fun (x : 𝕜) => x ^ n) (fun (x : 𝕜) => x) (nhds 0) := sorry theorem is_o_norm_pow_id {E' : Type u_6} [normed_group E'] {n : ℕ} (h : 1 < n) : is_o (fun (x : E') => norm x ^ n) (fun (x : E') => x) (nhds 0) := sorry theorem is_O_with.right_le_sub_of_lt_1 {α : Type u_1} {E' : Type u_6} [normed_group E'] {c : ℝ} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (fun (x : α) => f₂ x - f₁ x) l := sorry theorem is_O_with.right_le_add_of_lt_1 {α : Type u_1} {E' : Type u_6} [normed_group E'] {c : ℝ} {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (fun (x : α) => f₁ x + f₂ x) l := sorry theorem is_o.right_is_O_sub {α : Type u_1} {E' : Type u_6} [normed_group E'] {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_o f₁ f₂ l) : is_O f₂ (fun (x : α) => f₂ x - f₁ x) l := is_O_with.is_O (is_O_with.right_le_sub_of_lt_1 (is_o.def' h one_half_pos) one_half_lt_one) theorem is_o.right_is_O_add {α : Type u_1} {E' : Type u_6} [normed_group E'] {l : filter α} {f₁ : α → E'} {f₂ : α → E'} (h : is_o f₁ f₂ l) : is_O f₂ (fun (x : α) => f₁ x + f₂ x) l := is_O_with.is_O (is_O_with.right_le_add_of_lt_1 (is_o.def' h one_half_pos) one_half_lt_one) /-- If `f x = O(g x)` along `cofinite`, then there exists a positive constant `C` such that `∥f x∥ ≤ C * ∥g x∥` whenever `g x ≠ 0`. -/ theorem bound_of_is_O_cofinite {α : Type u_1} {E : Type u_3} {F' : Type u_7} [has_norm E] [normed_group F'] {f : α → E} {g' : α → F'} (h : is_O f g' filter.cofinite) : ∃ (C : ℝ), ∃ (H : C > 0), ∀ {x : α}, g' x ≠ 0 → norm (f x) ≤ C * norm (g' x) := sorry theorem is_O_cofinite_iff {α : Type u_1} {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f' : α → E'} {g' : α → F'} (h : ∀ (x : α), g' x = 0 → f' x = 0) : is_O f' g' filter.cofinite ↔ ∃ (C : ℝ), ∀ (x : α), norm (f' x) ≤ C * norm (g' x) := sorry theorem bound_of_is_O_nat_at_top {E : Type u_3} {E' : Type u_6} [has_norm E] [normed_group E'] {f : ℕ → E} {g' : ℕ → E'} (h : is_O f g' filter.at_top) : ∃ (C : ℝ), ∃ (H : C > 0), ∀ {x : ℕ}, g' x ≠ 0 → norm (f x) ≤ C * norm (g' x) := sorry theorem is_O_nat_at_top_iff {E' : Type u_6} {F' : Type u_7} [normed_group E'] [normed_group F'] {f : ℕ → E'} {g : ℕ → F'} (h : ∀ (x : ℕ), g x = 0 → f x = 0) : is_O f g filter.at_top ↔ ∃ (C : ℝ), ∀ (x : ℕ), norm (f x) ≤ C * norm (g x) := sorry theorem is_O_one_nat_at_top_iff {E' : Type u_6} [normed_group E'] {f : ℕ → E'} : is_O f (fun (n : ℕ) => 1) filter.at_top ↔ ∃ (C : ℝ), ∀ (n : ℕ), norm (f n) ≤ C := sorry end asymptotics theorem summable_of_is_O {ι : Type u_1} {E : Type u_2} [normed_group E] [complete_space E] {f : ι → E} (g : ι → ℝ) (hg : summable g) (h : asymptotics.is_O f g filter.cofinite) : summable f := sorry theorem summable_of_is_O_nat {E : Type u_1} [normed_group E] [complete_space E] {f : ℕ → E} (g : ℕ → ℝ) (hg : summable g) (h : asymptotics.is_O f g filter.at_top) : summable f := summable_of_is_O g hg (Eq.symm nat.cofinite_eq_at_top ▸ h) namespace local_homeomorph /-- Transfer `is_O_with` over a `local_homeomorph`. -/ theorem is_O_with_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {E : Type u_3} [has_norm E] {F : Type u_4} [has_norm F] (e : local_homeomorph α β) {b : β} (hb : b ∈ local_equiv.target (to_local_equiv e)) {f : β → E} {g : β → F} {C : ℝ} : asymptotics.is_O_with C f g (nhds b) ↔ asymptotics.is_O_with C (f ∘ ⇑e) (g ∘ ⇑e) (nhds (coe_fn (local_homeomorph.symm e) b)) := sorry /-- Transfer `is_O` over a `local_homeomorph`. -/ theorem is_O_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {E : Type u_3} [has_norm E] {F : Type u_4} [has_norm F] (e : local_homeomorph α β) {b : β} (hb : b ∈ local_equiv.target (to_local_equiv e)) {f : β → E} {g : β → F} : asymptotics.is_O f g (nhds b) ↔ asymptotics.is_O (f ∘ ⇑e) (g ∘ ⇑e) (nhds (coe_fn (local_homeomorph.symm e) b)) := exists_congr fun (C : ℝ) => is_O_with_congr e hb /-- Transfer `is_o` over a `local_homeomorph`. -/ theorem is_o_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {E : Type u_3} [has_norm E] {F : Type u_4} [has_norm F] (e : local_homeomorph α β) {b : β} (hb : b ∈ local_equiv.target (to_local_equiv e)) {f : β → E} {g : β → F} : asymptotics.is_o f g (nhds b) ↔ asymptotics.is_o (f ∘ ⇑e) (g ∘ ⇑e) (nhds (coe_fn (local_homeomorph.symm e) b)) := forall_congr fun (c : ℝ) => forall_congr fun (hc : 0 < c) => is_O_with_congr e hb end local_homeomorph namespace homeomorph /-- Transfer `is_O_with` over a `homeomorph`. -/ theorem is_O_with_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {E : Type u_3} [has_norm E] {F : Type u_4} [has_norm F] (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} {C : ℝ} : asymptotics.is_O_with C f g (nhds b) ↔ asymptotics.is_O_with C (f ∘ ⇑e) (g ∘ ⇑e) (nhds (coe_fn (homeomorph.symm e) b)) := local_homeomorph.is_O_with_congr (to_local_homeomorph e) trivial /-- Transfer `is_O` over a `homeomorph`. -/ theorem is_O_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {E : Type u_3} [has_norm E] {F : Type u_4} [has_norm F] (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : asymptotics.is_O f g (nhds b) ↔ asymptotics.is_O (f ∘ ⇑e) (g ∘ ⇑e) (nhds (coe_fn (homeomorph.symm e) b)) := exists_congr fun (C : ℝ) => is_O_with_congr e /-- Transfer `is_o` over a `homeomorph`. -/ theorem is_o_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {E : Type u_3} [has_norm E] {F : Type u_4} [has_norm F] (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : asymptotics.is_o f g (nhds b) ↔ asymptotics.is_o (f ∘ ⇑e) (g ∘ ⇑e) (nhds (coe_fn (homeomorph.symm e) b)) := forall_congr fun (c : ℝ) => forall_congr fun (hc : 0 < c) => is_O_with_congr e
5861727da92f1778117da5c6fe731fe4bcba69b3
7d5ad87afb17e514aee234fcf0a24412eed6384f
/src/colimit.lean
7066c035e9ad59b74cd6ce0e56948286270791ab
[]
no_license
digama0/flypitch
764f849eaef59c045dfbeca142a0f827973e70c1
2ec14b8da6a3964f09521d17e51f363d255b030f
refs/heads/master
1,586,980,069,651
1,547,078,141,000
1,547,078,283,000
164,965,135
1
0
null
1,547,082,858,000
1,547,082,857,000
null
UTF-8
Lean
false
false
13,523
lean
import .to_mathlib tactic.tidy tactic.linarith /- The proper generality to do this is with directed categories as the indexing objects -/ /- We'll settle for directed types instead -/ --local attribute [instance, priority 0] classical.prop_decidable universes u v w namespace colimit -- def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z structure directed_type : Type (u+1) := (carrier : Type u) (rel : carrier → carrier → Prop) (h_reflexive : reflexive rel) (h_transitive : transitive rel) (h_directed : ∀ x y, ∃ z : carrier, rel x z ∧ rel y z) lemma trans {D : directed_type} {i j k : D.carrier} (h1 : D.rel i j) (h2 : D.rel j k) : D.rel i k := begin fapply directed_type.h_transitive, exact j, repeat{assumption} end structure directed_diagram (D : (directed_type : Type (u+1))) : Type (max (u+1) (v+1)) := (obj : D.carrier → Type v) (mor : ∀{x}, ∀{y}, D.rel x y → (obj x → obj y)) (h_mor : ∀{x} {y} {z} {f1 : D.rel x y} {f2 : D.rel y z} {f3 : D.rel x z}, (mor f3) = (mor f2) ∘ (mor f1)) -- functoriality @[reducible]def directed_type_of_nat : directed_type := begin refine ⟨ℕ, (≤), _, _, _⟩, intro, refl, fapply le_trans, intros, fapply exists.intro, exact x + y, simp only [*, zero_le, le_add_iff_nonneg_right, and_self, le_add_iff_nonneg_left] end notation `ℕ'` := directed_type_of_nat @[simp]lemma ℕ_of_ℕ'.carrier : (ℕ').carrier = ℕ := by refl @[simp]lemma le_of_ℕ'.rel : (ℕ').rel = nat.le := by refl -- @[reducible]def has_le_ℕ' : has_le (ℕ').carrier := begin split, rw[ℕ_of_ℕ'.carrier], exact λ x y, x ≤ y end -- attribute [instance] has_le_ℕ' def constant_functor (D : directed_type) (A : Type v) : directed_diagram D := ⟨(λ x, A), λ x y h, id, by simp⟩ def coproduct_of_directed_diagram {D : (directed_type : Type (u+1)) } (F : (directed_diagram D : Type (max (u+1) (v+1)))) : Type (max u v) := Σ a : D.carrier, F.obj a def canonical_inclusion_coproduct {D : directed_type} {F : directed_diagram D} (i : D.carrier) : F.obj i → coproduct_of_directed_diagram F := λ x, ⟨i,x⟩ def germ_relation {D : (directed_type : Type (u+1)) } (F : (directed_diagram D : Type (max (u+1) (v+1)))) : coproduct_of_directed_diagram F → coproduct_of_directed_diagram F → Prop := λ ⟨i,x⟩ ⟨j, y⟩, ∃ k : D.carrier, ∃ z : F.obj k, ∃ f_x : D.rel i k, ∃ f_y : D.rel j k, (F.mor f_x) x = z ∧ (F.mor f_y) y = z lemma germ_equivalence {D : (directed_type : Type (u+1)) } (F : (directed_diagram D : Type (max (u+1) (v+1)))) : equivalence (germ_relation F) := begin split, {rintro ⟨i, x⟩, repeat{split}, swap, exact i, exact D.h_reflexive i}, split, {intros x y, rcases x with ⟨i, x⟩, rcases y with ⟨j, y⟩, intro h, rcases h with ⟨ℓ,z,f_x,f_y,H⟩, repeat{fapply exists.intro}, exacts [ℓ,z,f_y,f_x, and.intro H.right H.left]}, {unfold transitive, intros, cases x with i x, cases y with j y, cases z with k z, rcases a with ⟨ℓ₁, z, fi, fj_1, Hℓ₁⟩, rcases a_1 with ⟨ℓ₂, z', fj_2, fk, Hℓ₂⟩, have a_2 := D.h_directed ℓ₁ ℓ₂, rcases a_2 with ⟨ℓ₃, g1, g2⟩, have f1 : D.rel i (ℓ₃), {fapply D.h_transitive, exacts [ℓ₁, fi, g1]}, have f2 : D.rel j ℓ₃, {fapply D.h_transitive, exacts [ℓ₁, fj_1, g1]}, have f3 : D.rel k (ℓ₃), {fapply D.h_transitive, exacts [ℓ₂, fk, g2]}, have H1 : F.mor f1 = F.mor g1 ∘ F.mor fi; have H2_l : F.mor f2 = F.mor g1 ∘ F.mor fj_1; have H2_r : F.mor f2 = F.mor g2 ∘ F.mor fj_2; have H3 : F.mor f3 = F.mor g2 ∘ F.mor fk; all_goals{try{fapply F.h_mor}}, have H4 : (F.mor fi x) = (F.mor fj_1 y), by cc, dedup, have H5 : (F.mor fk z) = (F.mor fj_2 y), by cc, unfold germ_relation at *, fapply exists.intro, exact ℓ₃, fapply exists.intro, exact (F.mor f2) y, fapply exists.intro, exact f1, fapply exists.intro, exact f3, fapply and.intro, {simp[H1, H2_l], rw[H4]}, {simp[H2_r, H3], rw[H5]}, } end @[reducible]def coproduct_setoid {D : directed_type} (F : directed_diagram D) : setoid $ coproduct_of_directed_diagram F := ⟨germ_relation F, germ_equivalence F⟩ attribute [instance] coproduct_setoid def colimit {D : (directed_type : Type (u+1)) } (F : (directed_diagram D : Type (max (u+1) (v+1)))) : Type (max u v) := @quotient (coproduct_of_directed_diagram F) (by fapply coproduct_setoid) def canonical_map {D : directed_type} {F : directed_diagram D} (i : D.carrier) : F.obj i → colimit F := (by apply quotient.mk) ∘ canonical_inclusion_coproduct i lemma canonical_map_inj_of_transition_maps_inj {D : directed_type} {F : directed_diagram D} (i : D.carrier) (H : ∀ {i} {j}, ∀ h : D.rel i j, function.injective (F.mor h)) : function.injective (@canonical_map D F i) := begin unfold function.injective canonical_map canonical_inclusion_coproduct, intros x y, simp only [function.comp_app, quotient.eq], simp only [(≈)], unfold germ_relation, intro H_eqv, rcases H_eqv with ⟨j,z,edge,_, ⟨H1, H2⟩⟩, exact H edge (by cc) end structure cocone {D} (F : directed_diagram D) := (vertex : Type*) (map : Π i : D.carrier, F.obj i → vertex) (h_compat : ∀{i}, ∀{j}, Π h : D.rel i j, (map i) = (map j) ∘ (F.mor h)) def cocone_of_colimit {D} (F : directed_diagram D) : cocone F := begin refine ⟨colimit F, canonical_map, _⟩, intros i j H, fapply funext, intro x, simp only [quotient.eq,(≈),canonical_map,function.comp], have h_refl : D.rel j j, by apply D.h_reflexive, refine ⟨j,F.mor H x, H, h_refl, rfl, _⟩, change ((F.mor h_refl) ∘ (F.mor H)) x = F.mor H x, rw[<-F.h_mor] end /- Given a cocone V over a diagram D, return the canonical map colim D → V-/ def universal_map {D} {F : directed_diagram D} {V : cocone F} : colimit F → (V.vertex) := begin fapply quotient.lift, {exact λp, V.map p.fst p.snd}, {intros p q H, rcases p with ⟨i,x⟩, rcases q with ⟨j,y⟩, simp only *, simp[(≈), germ_relation] at H, rcases H with ⟨k,z,⟨f1, H1⟩,f2,H2⟩, change V.map i x = V.map j y, have : V.map i x = V.map k (F.mor f1 x), simp only [V.h_compat f1, eq_self_iff_true, function.comp_app], have : V.map j y = V.map k (F.mor f2 y), simp only [V.h_compat f2, eq_self_iff_true, function.comp_app], simp only [*, eq_self_iff_true], } end @[simp]lemma universal_map_property {D} {F : directed_diagram D} {V : cocone F} (i : D.carrier) (x) : universal_map ((canonical_map i) x) = (V.map i) x := by refl /- this generalizes canonical_map_inj_of_transition_maps_inj, because every colimit is a cocone over its own diagram If the maps to the vertex are injective, then the comparison map from the colimit is injective. -/ lemma universal_map_inj_of_components_inj {D} {F : directed_diagram D} {V : cocone F} (h_inj : ∀ i : D.carrier, function.injective (V.map i)) : function.injective (universal_map : colimit F → (V.vertex)) := begin unfold universal_map, rintros ⟨i,x⟩ ⟨j,y⟩ H, unfold quotient.lift at H, dsimp[colimit] at *, change (⟦⟨i,x⟩⟧ : colimit F) = (⟦⟨j,y⟩⟧ : colimit F), simp[quotient.eq, (≈)], have := (D.h_directed i j), rcases this with ⟨k, Hik, Hjk⟩, refine ⟨k, F.mor Hik x, Hik, Hjk, rfl, _⟩, fapply h_inj k, simp only [*, V.h_compat Hik, V.h_compat Hjk, function.injective.eq_iff, eq_self_iff_true, function.comp_app] at * end /- Given a germ-equivalence class from the colimit, return a representative from the coproduct and a proof that this is a lift -/ noncomputable def germ_rep {D} {F : directed_diagram D} (a : colimit F) : Σ' x : (coproduct_of_directed_diagram F), ⟦x⟧ = a := classical.psigma_of_exists (quotient.exists_rep a) @[simp]lemma canonical_map_quotient {D} {F : directed_diagram D} (a : coproduct_of_directed_diagram F) : canonical_map a.fst a.snd = ⟦a⟧ := by {auto_cases, refl} /- Assuming canonical maps into the colimit are injective, ⟨i,x⟩ and ⟨j,y⟩ in the same fiber over a ⟦z⟧ : colimit F are related by any transition map i → j. -/ @[simp]lemma eq_mor_of_same_fiber {D} {F : directed_diagram D} (a b : coproduct_of_directed_diagram F) {z : colimit F} (Ha : ⟦a⟧ = z) (Hb : ⟦b⟧ = z) (H_inj : ∀ i : D.carrier, function.injective (@canonical_map D F i)) (H_rel : D.rel a.fst b.fst) : F.mor H_rel a.snd = b.snd := begin have H_eq : z = canonical_map (b.fst) (F.mor H_rel (a.snd)), by {have := (cocone_of_colimit F).h_compat, have H := congr_fun (@this a.fst b.fst H_rel) a.snd, dsimp[cocone_of_colimit] at H, rw[canonical_map_quotient, Ha] at H, exact H}, have : canonical_map (b.fst) (b.snd) = canonical_map (b.fst) (F.mor H_rel (a.snd)), simp only [*, canonical_map_quotient b, colimit.canonical_map_quotient, function.injective.eq_iff, eq_self_iff_true], fapply H_inj b.fst, symmetry, exact this end @[simp]lemma eq_mor_of_same_fiber' {D} {F : directed_diagram D} (a_fst b_fst : D.carrier) (a_snd : F.obj a_fst) (b_snd : F.obj b_fst) {z : colimit F} (Ha : ⟦(⟨a_fst, a_snd⟩ : coproduct_of_directed_diagram F)⟧ = z) (Hb : ⟦(⟨b_fst, b_snd⟩ : coproduct_of_directed_diagram F)⟧ = z) (H_inj : ∀ i : D.carrier, function.injective (@canonical_map D F i)) (H_rel : D.rel a_fst b_fst) : F.mor H_rel a_snd = b_snd := begin let a : coproduct_of_directed_diagram F := ⟨a_fst, a_snd⟩, let b : coproduct_of_directed_diagram F := ⟨b_fst, b_snd⟩, have : ⟦a⟧ = z, by assumption, have : ⟦b⟧ = z, by assumption, change F.mor H_rel a.snd = b.snd, have := @eq_mor_of_same_fiber D F a b z _ _ _ _, repeat{assumption}, end /- Given an x : F_i and a j : ℕ, apply the map to obtain x' : F_{i+j} -/ @[reducible]def push_to_sum_r {F : directed_diagram ℕ'} {i} (x : F.obj i) (j) : F.obj (i+j) := F.mor (by simp only [zero_le, le_add_iff_nonneg_right]) x @[reducible]def push_to_sum_l {F : directed_diagram ℕ'} {j} (x : F.obj j) (i) : F.obj (i+j) := F.mor (by simp only [zero_le, le_add_iff_nonneg_right, add_comm]) x /- The push_to of x is in the same germ-equivalence class of x -/ lemma same_fiber_as_push_to_r {F : directed_diagram ℕ'} {i} (x : F.obj i) (j) : canonical_map i x = canonical_map (i+j) (push_to_sum_r x j) := by {have := (cocone_of_colimit F).h_compat, have := @this i (i+j) (by simp), tidy} lemma same_fiber_as_push_to_l {F : directed_diagram ℕ'} {j} (x : F.obj j) (i) : canonical_map j x = canonical_map (i+j) (push_to_sum_l x i) := by {have := (cocone_of_colimit F).h_compat, have := @this i (i+j) (by simp), tidy} namespace nat @[simp]lemma le_of_le_and_ne_succ {x y : ℕ} (H : x ≤ y + 1) (H' : x ≠ y + 1) : x ≤ y := by simp only [*, nat.lt_of_le_and_ne, nat.le_of_lt_succ, ne.def, not_false_iff] end nat end colimit namespace omega_colimit open colimit /- Facts about directed colimits indexed by ℕ'. -/ def diagram.mk.map {F : ℕ → Type*} {h_succ : ∀{i : ℕ}, F i → F (i+1)} : Π (x y : ℕ), x ≤ y → F x → F y | x 0 h := by {rw[nat.eq_zero_of_le_zero h], exact id} | x (y+1) h := by {by_cases x = y + 1, rw[h], exact id, refine h_succ ∘ _, apply diagram.mk.map, apply nat.le_of_le_and_ne_succ, repeat{assumption}} @[simp]lemma diagram.mk.map_self_id {F : ℕ → Type*} {h_succ : ∀(i : ℕ), F i → F (i+1)} (x : ℕ) : @diagram.mk.map F @h_succ x x (by constructor) = id := by {induction x, tidy, simp[diagram.mk.map,*], refl} /- If the successive maps of h_succ are injective, then all their compositions are injective -/ lemma diagram.mk.map_inj {F : ℕ → Type*} {h_succ : ∀(i : ℕ), F i → F (i+1)} {h_inj : ∀ {i : ℕ}, function.injective (@h_succ i )} (x y : ℕ) (h : x ≤ y) : function.injective (@diagram.mk.map F h_succ x y h) := begin induction y, {have : x = 0, by exact nat.eq_zero_of_le_zero h, dsimp[*,diagram.mk.map], finish}, by_cases x = y_n + 1, {dsimp[*, diagram.mk.map], finish}, have : x ≤ y_n, by {apply nat.le_of_le_and_ne_succ, repeat{assumption}}, simp[*, diagram.mk.map], apply function.injective_comp, apply h_inj, apply y_ih end -- /- Given a ℕ-indexed family of types and a way of assigning maps between successive objects -- in this family, return the induced directed_diagram over ℕ'. -/ def diagram.mk(F : ℕ → Type*) (h_succ :∀{i : ℕ}, F i → F (i+1)) : directed_diagram ℕ' := begin refine ⟨F, by {apply diagram.mk.map, assumption}, _⟩, intros x y z H1 H2 H3, induction z, induction y, induction x, dsimp[diagram.mk.map], refl, by {exfalso, fapply nat.succ_ne_zero, exact x_n, apply (nat.le_zero_iff).mp, assumption}, by {exfalso, fapply nat.succ_ne_zero, exact y_n, apply (nat.le_zero_iff).mp, assumption}, by_cases y = z_n+1, subst h; by_cases x = z_n+1; {repeat{dsimp[diagram.mk.map], simp*, refl}}, by_cases x = z_n+1, {exfalso, have : y < z_n+1, by {fapply nat.lt_of_le_and_ne, repeat{assumption}}, dsimp at *, linarith}, {have h_x : x ≤ z_n; have h_y : y ≤ z_n, all_goals{try{apply nat.le_of_le_and_ne_succ, repeat{assumption}}}, have := @z_ih h_y h_x, dsimp[diagram.mk.map], dedup, simp only [h, h_1, dif_neg, not_false_iff, colimit.nat.le_of_le_and_ne_succ], rw[this]} end -- TODO refactor henkin_language_chain et al in terms of diagram.mk end omega_colimit
a3d3e2a0523ff7b9f4f7e14c5d4a5e3d4cf7bc14
b7fc5b86b12212bea5542eb2c9d9f0988fd78697
/src/exercises_sources/thursday/order.lean
d7a499cec7b7171fb44acce4078506f975e497ed
[]
no_license
stjordanis/lftcm2020
3b16591aec853c8546d9c8b69c0bf3f5f3956fee
1f3485e4dafdc587b451ec5144a1d8d3ec9b411e
refs/heads/master
1,675,958,865,413
1,609,901,722,000
1,609,901,722,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,107
lean
/- # Orders Groups, rings, fields, modules etc are in the "algebra hierarchy". Metric and topological spaces are in the "topology hierarchy". The other important hierarchy is the "order hierarchy". It starts with partially ordered sets, and then goes on to lattices. Because I like algebra, let's demonstrate the order hierarchy by making an algebraic type, namely the type of subgroups of a group G, and then working up the order hierarchy with it. Subgroups of a group are ordered by inclusion, and this is where we shall start. We will then define infs and sups, and bot and top, and go on from there. -/ import tactic -- We will be using all of the theory of subsets of a type -- without further comment (e.g. `inter_subset_left A B : A ∩ B ⊆ A`) -- so let's open the `set` namespace. open set -- The type of subgroups of a group G is called `subgroup G` in Lean. -- It already has a lattice structure in Lean. -- So let's just redo the entire theory and call it `subgp G`. /-- The type of subgroups of a group `G`. -/ structure subgp (G : Type) [group G] := -- A subgroup of G is a sub*set* of G, called `carrier` (carrier : set G) -- and then axioms saying it's closed under the group structure (i.e. *, 1, ⁻¹) (mul_mem {a b : G} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) (one_mem : (1 : G) ∈ carrier) (inv_mem {a : G} : a ∈ carrier → a⁻¹ ∈ carrier) namespace subgp /- Note in particular that we have a function `subgp.carrier : subgp G → set G`, sending a subgroup of `G` to the underlying subset (`set G` is the type of subsets of G). -/ -- Let G be a group, let H,J,K be subgroups of G, and let a,b,c be elements of G. variables {G : Type} [group G] (H J K : subgp G) (a b c : G) /- # Extensionality One of the first things you should consider proving about a newly-defined type is an extensionality lemma: a sensible criterion to check that two terms are equal. When are two subgroups of `G` equal? A subgroup is defined by four things: a subset, and three proofs. But two proofs of a proposition `P` are equal by definition in Lean, so two subgroups of `G` are equal iff their underlying subsets are equal, which is true iff their underlying subsets have the same elements. Let's give names to these basic results because they'll show up everywhere. Let's start by showing that two subgroups are equal if their underlying subsets are equal. This is precisely the statement that `∀ H J : subgp G, H.carrier = J.carrier → H = J`, and a good name for this would be `carrier_injective`. We adopt the Lean tradition of putting as many things to the left of the `:` as we can; it doesn't change the statement of the theorem. -/ lemma carrier_injective (H J : subgp G) (h : H.carrier = J.carrier) : H = J := begin -- take H and J apart cases H, cases J, -- and note that they are the same set, and then a bunch of proofs -- which are equal by definition, so it's obvious simp * at *, end -- Now let's prove that two subgroups are equal iff they have the same elements. -- This is the most useful "extensionality lemma" so we tag it `@[ext]`. @[ext] theorem ext {H J : subgp G} (h : ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier) : H = J := begin -- it suffices to prove the subsets are equal apply carrier_injective, -- Now let's use extensionality for subsets ext x, exact h x, end -- We also want the `iff` version of this. theorem ext_iff {H J : subgp G} : H = J ↔ ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier := begin split, { -- one way is just a rewrite! intro h, rw h, simp, }, { -- the other way we just did exact subgp.ext, } end /- ## Partial orders -/ -- These are familiar to most mathematicians. We will put a partial order -- structure on `subgp G`. In other words, we will create a term of -- type `partial_order (subgp G)`. -- Let's define `H ≤ J` to mean `H.carrier ⊆ J.carrier`, using the `has_le` notation typeclass instance : has_le (subgp G) := ⟨λ H J, H.carrier ⊆ J.carrier⟩ -- "tidy" is a one-size-fits-all tactic which solves certain kinds of "follow your nose" goals. instance : partial_order (subgp G) := { le := (≤), le_refl := by tidy, le_trans := by tidy, le_antisymm := by tidy } /- Here is a second proof. If X → Y is injective, and Y is partially ordered, then X inherits a partial order. This construction (it's not a theorem, because it involves data) is called `partial_order.lift`. Applying it to the injection `subgp.carrier` and the fact that Lean already knows that `set G` is partially ordered, turns into this second construction, (which I won't call an `instance` because if I did then I would have committed the sin of making two terms of type `partial_order (subgp G)`, and `partial_order (subgp G)` is a class so should have at most one instance): -/ -- partial_order.lift is the function which pulls a partial order back along an injection. example : partial_order (subgp G) := partial_order.lift subgp.carrier carrier_injective /- Note that we magically just inherited `<` notatation, because `#check partial_order` tells you that `partial_order` extends `preorder`, which extends `has_lt`, which is a notation typeclass. In other words, `#check (H < J)` makes sense, and is a `Prop`. In fact `H < J` is defined to mean `H ≤ J ∧ ¬ (J ≤ H)`. # From partial orders to lattices. Let's now prove that `subgp G` is a `semilattice_inf_top`. This is a class which extends `partial_order` -- it is a partial order equipped with a top element, and a function `inf : subgp G → subgp G → subgp G` (called "inf" or "meet" or "greatest lower bound", satisfying some axioms. In our case, `top` will be the subgroup `G` of `G` (or more precisely `univ`), and `inf` will just be intersection. The work we need to do is to check that these are subgroups, and to prove the axioms for a `semilattice_inf_top`, which we'll come to later. First let's define `top` -- the biggest subgroup. The underlying carrier is `univ : set G`, i.e. the subset `G` of `G`. I'll leave it to you to prove that the subgroup axioms hold! The useful piece of interface for `univ` you'll need is `mem_univ g : g ∈ univ`. -/ def top : subgp G := { carrier := set.univ, mul_mem := begin intros, apply mem_univ, end, one_mem := begin apply mem_univ, end, inv_mem := begin intros, apply mem_univ, end } -- Add the `⊤` notation (typed with `\top`) for this subgroup: instance : has_top (subgp G) := ⟨top⟩ -- Now `#check (⊤ : subgp G)` works /- We'll now prove the theorem that the intersection of two subgroups is a subgroup. This is a *definition* in Lean, indeed it is a construction which given two subgroups `H` and `K` of `G` produces a third subgroup `H ⊓ K` (Lean's notation for `inf H K`). The part of the interface for `∩` you'll need is that `a ∈ B ∩ C` is definitionally equal to `a ∈ B ∧ a ∈ C`, so you can use `split` if you have a goal `⊢ a ∈ B ∩ C`, and you can use `cases h` if you have a hypothesis `h : a ∈ B ∩ C`. Don't forget `mul_mem H`, `one_mem H` and `inv_mem H`, the axioms for `H` if `H : subgp G`. -/ /-- "Theorem" : intersection of two subgps is a subgp -/ definition inf (H K : subgp G) : subgp G := { carrier := H.carrier ∩ K.carrier, mul_mem := begin rintros a b ⟨haH, haK⟩ ⟨hbH, hbK⟩, split, { apply H.mul_mem haH hbH }, { apply K.mul_mem haK hbK }, end, one_mem := begin split, { apply one_mem }, { apply one_mem }, end, inv_mem := begin rintros a ⟨haH, haK⟩, exact ⟨H.inv_mem haH, K.inv_mem haK⟩, end } -- Add the `⊓` notation (type with `\inf`) for the intersection (inf) of two subgroups: instance : has_inf (subgp G) := ⟨inf⟩ -- We now check the four axioms for a semilattice_inf_top. -- They are called `le_top`, `inf_le_left`, `inf_le_right` and `le_inf`. -- You might be able to guess the statementss of the axioms -- from their names. lemma le_top (H : subgp G) : H ≤ ⊤ := begin intros x hx, apply mem_univ, end lemma inf_le_left (H K : subgp G) : H ⊓ K ≤ H := begin -- by definition this says `H.carrier ∩ K.carrier ⊆ H.carrier` change H.carrier ∩ K.carrier ⊆ H.carrier, -- now try `library_search`, to find that this is called `inter_subset_left apply inter_subset_left, end lemma inf_le_right (H K : subgp G) : H ⊓ K ≤ K := inter_subset_right _ _ -- Can you use `library_search`, or other methods, to find the name of the -- statement that if `A B C : set G` then `A ⊆ B → A ⊆ C → A ⊆ (B ∩ C)`? lemma le_inf (H J K : subgp G) (h1 : H ≤ J) (h2 : H ≤ K) : H ≤ J ⊓ K := begin exact subset_inter h1 h2, end -- Now we're ready to make the instance. instance : semilattice_inf_top (subgp G) := { top := top, le_top := le_top, inf := inf, inf_le_left := inf_le_left, inf_le_right := inf_le_right, le_inf := le_inf, .. subgp.partial_order } -- don't forget to inlude the partial order /- The logic behind `semilattice_inf_top` is that it is the simplest class which is closed under all finite "meet"s. The meet of 0 subgroups is `top`, the meet of one subgroup is the subgroup, the meet of two subgroups is their inf, and for three or more you proceed by induction. We could now go on to make a `semilattice_sup_bot` structure, and then a lattice structure. But let's jump straight to the strongest type in the order hierarchy -- a `complete_lattice`. This has arbitrary `Inf` and `Sup`s. So let's first note that we can do better than finite intersections -- we can take arbitrary intersections! Let's now define the `Inf` of an arbitrary set of subgroups of `G`. The part of the interface for sets you'll need to know here is that if `S` is a set of subsets of `G`, then `⋂₀ S` is notation for their intersection, and to work with it you'll need to know `set.mem_sInter : g ∈ ⋂₀ S ↔ ∀ (U : set G), U ∈ S → g ∈ U`. -/ def Inf (S : set (subgp G)) : subgp G := { carrier := Inf (subgp.carrier '' S), mul_mem := begin intros x y hx hy, rw mem_sInter at hx hy ⊢, rintro t ⟨H, hH, rfl⟩, apply H.mul_mem, apply hx, use H, tauto, apply hy, use H, tauto, end, one_mem := begin rw mem_sInter, rintro t ⟨H, hH, rfl⟩, apply subgp.one_mem, end, inv_mem := begin intros x hx, rw mem_sInter at hx ⊢, rintro t ⟨H, Hh, rfl⟩, apply H.inv_mem, apply hx, use [H, Hh], end } -- We now equip `subgp G` with an Inf. I think the notation is `⨅`, or `\Inf`, -- but I find it hard to use, and `#print notation ⨅` returns garbage. instance : has_Inf (subgp G) := ⟨Inf⟩ /- # Complete lattices Let's jump straight from `semilattice_inf_bot` to `complete_lattice`. A complete lattice has arbitrary Infs and arbitrary Sups, and satisfies some other axioms which you can probably imagine. Our next goal is to make `subgp G` into a complete lattice. We will do it in two ways. The first way is to show that if our `Inf` satisfies `(∀ (S : set (subgp G)), is_glb S (Inf S))` then we can build a complete lattice from this, using `complete_lattice_of_Inf`. -/ instance : complete_lattice (subgp G) := complete_lattice_of_Inf _ begin -- ⊢ ∀ (s : set (subgp G)), is_glb s (has_Inf.Inf s) -- See if you can figure out what this says, and how to prove it. -- You might find the function `is_glb.of_image` useful. intro S, apply @is_glb.of_image _ _ _ _ subgp.carrier, intros, refl, apply is_glb_Inf, end /- Now let me show you another way to do this. # Galois connections A Galois conection is a pair of adjoint functors between two partially ordered sets, considered as categories whose hom sets Hom(H,J) have size 1 if H ≤ J and size 0 otherwise. In other words, a Galois connection between two partial orders α and β is a pair of monotone functions `l : α → β` and `u : β → α` such that `∀ (a : α) (b : β), l a ≤ b ↔ a ≤ u b`. There is an example coming from Galois theory (between subfields and subgroups), and an example coming from classical algebraic geometry (between affine varieties and ideals); note that in both cases you have to use the opposite partial order on one side to make everything covariant. The examples we want to keep in mind here are: 1) α = subsets of G, β = subgroups of G, l = "subgroup generated by", u = `carrier` 2) X : Type, α := set (set X), β := topologies on X, l = topology generated by a collection of open sets, u = the open sets regarded as subsets. As you can imagine, there are a bunch of abstract theorems with simple proofs proved for Galois connections. You can see them by `#check galois_connection`, jumping to the definition, and reading the next 150 lines of the mathlib file after the definition. Examples of theorems you might recognise from contexts where you have seen this before: lemma le_u_l (a : α) : a ≤ u (l a) := ... lemma l_u_le (b : β) : l (u b) ≤ b := ... lemma u_l_u_eq_u : u ∘ l ∘ u = u := ... lemma l_u_l_eq_l : l ∘ u ∘ l = l := ... # Galois insertions A particularly cool kind of Galois connection is a Galois insertion, which is a Galois connection such that `l ∘ u = id`. This is true for both the examples we're keeping in mind (the subgroup of `G` generated by a subgroup is the same subgroup; the topology on `X` generated by a topology is the same topology). Our new goal: let's make subgroups of a group into a complete lattice, using the fact that `carrier` is part of a Galois insertion. -/ -- The adjoint functor to the `carrier` functor is the `span` functor -- from subsets to subgps. Here we will CHEAT by using `Inf` to -- define `span`. We could have built `span` directly with -- an inductive definition. def span (S : set G) : subgp G := Inf {H : subgp G | S ⊆ H.carrier} -- Here are some theorems about it. lemma monotone_carrier : monotone (subgp.carrier : subgp G → set G) := λ H J, id lemma monotone_span : monotone (span : set G → subgp G) := λ S T h, Inf_le_Inf $ λ H hH x hx, hH $ h hx lemma subset_span (S : set G) : S ≤ (span S).carrier := begin rintro x hx _ ⟨H, hH, rfl⟩, exact hH hx, end lemma span_subgp (H : subgp G) : span H.carrier = H := begin ext, split, { intro hx, unfold span at hx, replace hx := mem_sInter.1 hx, apply hx, use H, simp }, { intro h, apply subset_span, exact h}, end -- We have proved all the things we need to show that `span` and `carrier` -- form a Galois insertion, using `galois_insertion.monotone_intro`. def gi_subgp : galois_insertion (span : set G → subgp G) (subgp.carrier : subgp G → set G) := galois_insertion.monotone_intro monotone_carrier monotone_span subset_span span_subgp -- Note that `set G` is already a complete lattice: example : complete_lattice (set G) := by apply_instance -- and now `subgp G` can also be made into a complete lattice, by -- a theorem about Galois insertions. Again, I don't use `instance` -- because we already made the instance above. example : complete_lattice (subgp G) := galois_insertion.lift_complete_lattice gi_subgp end subgp -- Because Alex defined the topology generated by a collection of subsets -- yesterday, I'll show you how you can use Galois insertions to prove -- that if `X : Type` then the type of topological space structures on `X` -- is a complete lattice. We use the topology generated by a collection -- of subsets, which is a functor adjoint to the forgetful functor. -- We start by literally copying some stuff from Alex' talk. open set @[ext] class topological_space (X : Type) := (is_open : set X → Prop) -- why set X → Prop not set (set X)? former plays -- nicer with typeclasses later (univ_mem : is_open univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) namespace topological_space def forget {X : Type} : topological_space X → set (set X) := @is_open X /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generated_open (X : Type) (g : set (set X)) : set X → Prop | basic : ∀ s ∈ g, generated_open s | univ : generated_open univ | inter : ∀s t, generated_open s → generated_open t → generated_open (s ∩ t) | sUnion : ∀k, (∀ s ∈ k, generated_open s) → generated_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from {X : Type} (g : set (set X)) : topological_space X := { is_open := generated_open X g, univ_mem := sorry, inter := sorry, union := sorry } -- Recall that `topological_space X` is the type of topological space structures -- on `X`. Our Galois insertion will use the adjoint functors -- `generate_from` and `is_open`. -- We'd better start by giving the collection of topological space structures on X -- a partial order: instance (X : Type) : partial_order (topological_space X) := partial_order.lift (forget) begin -- need to show that a top space is determined by its open sets intros τ₁ τ₂ h, cases τ₁, cases τ₂, simp [forget, *] at *, end -- Exercise (LONG): First, show that we have a Galois insertion. lemma monotone_is_open {X : Type} : monotone (forget : topological_space X → set (set X)) := begin intros τ₁ τ₂, intro h, intros U hU, exact h hU, end lemma monotone_span {X : Type} : monotone (generate_from : set (set X) → topological_space X) := begin intros C₁ C₂, intro h, intros U hU, induction hU with V hV V W _ _ hV2 hW2 C _ hC, { apply generated_open.basic, apply h, assumption }, { apply generated_open.univ }, { apply generated_open.inter, exact hV2, exact hW2}, { apply generated_open.sUnion, exact hC }, end lemma subset_forget {X : Type} (Us : set (set X)) : Us ≤ forget (generate_from Us) := begin intros U hU, apply generated_open.basic, assumption, end lemma generate_forget {X : Type} (τ : topological_space X) : generate_from (forget τ) = τ := begin ext U, split, { intro hU, induction hU with V hV V W _ _ hV2 hW2 C _ hC, { exact hV }, { apply univ_mem }, { apply inter _ _ hV2 hW2 }, { apply union _ hC }}, { -- easy way intro hU, apply generated_open.basic, exact hU } end def gi_top (X : Type) : galois_insertion (generate_from : set (set X) → topological_space X) (forget : topological_space X → set (set X)) := galois_insertion.monotone_intro monotone_is_open monotone_span subset_forget generate_forget /- Then deduce that the type of topological space structures on X is a complete lattice, i.e. that there is a good definition of arbitrary Infs and Sups of topological space structures on a type, and they satisfy all the correct properties of Infs and Sups. In other words, -/ example (X : Type) : complete_lattice (topological_space X) := galois_insertion.lift_complete_lattice (gi_top X) end topological_space
4bf289acc7fed694efe2bf6d36bf49f8d6bc2c31
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/rewrite_all/basic_auto.lean
4b69b70e480abe83cca2342575d2ace9bd6276de
[]
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
605
lean
/- Copyright (c) 2018 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mllist import Mathlib.tactic.core import Mathlib.PostPort universes l namespace Mathlib inductive side where | L : side | R : side def side.other : side → side := sorry def side.to_string : side → string := sorry protected instance side.has_to_string : has_to_string side := has_to_string.mk side.to_string namespace tactic.rewrite_all end Mathlib
35a31c84142e0c7a593a0eaa47e2db116fb10603
c777c32c8e484e195053731103c5e52af26a25d1
/archive/100-theorems-list/9_area_of_a_circle.lean
9b628e2f8cc89b35f2d3c0f651270ed453187d82
[ "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
6,503
lean
/- Copyright (c) 2021 James Arthur, Benjamin Davidson, Andrew Souther. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: James Arthur, Benjamin Davidson, Andrew Souther -/ import measure_theory.integral.fund_thm_calculus import analysis.special_functions.sqrt import analysis.special_functions.trigonometric.inverse_deriv /-! # Freek № 9: The Area of a Circle In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main tools our proof uses are `volume_region_between_eq_integral`, which allows us to represent the area of the disc as an integral, and `interval_integral.integral_eq_sub_of_has_deriv_at'_of_le`, the second fundamental theorem of calculus. We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the `region_between` two functions. Though not necessary for the main proof, we nonetheless choose to include a proof of the measurability of the disc in order to convince the reader that the set whose volume we will be calculating is indeed measurable and our result is therefore meaningful. In the main proof, `area_disc`, we use `volume_region_between_eq_integral` followed by `interval_integral.integral_of_le` to reduce our goal to a single `interval_integral`: `∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`. After disposing of the trivial case `r = 0`, we show that `λ x, 2 * sqrt (r ^ 2 - x ^ 2)` is equal to the derivative of `λ x, r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere on `Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental theorem of calculus with those facts. Some simple algebra then completes the proof. Note that we choose to define `disc` as a set of points in `ℝ × ℝ`. This is admittedly not ideal; it would be more natural to define `disc` as a `metric.ball` in `euclidean_space ℝ (fin 2)` (as well as to provide a more general proof in higher dimensions). However, our proof indirectly relies on a number of theorems (particularly `measure_theory.measure.prod_apply`) which do not yet exist for Euclidean space, thus forcing us to use this less-preferable definition. As `measure_theory.pi` continues to develop, it should eventually become possible to redefine `disc` and extend our proof to the n-ball. -/ open set real measure_theory interval_integral open_locale real nnreal /-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that `p.1 ^ 2 + p.2 ^ 2 < r ^ 2`. Note that this definition is not equivalent to `metric.ball (0 : ℝ × ℝ) r`. This was done intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `metric.ball` in `ℝ × ℝ` a square, not a disc. See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/ def disc (r : ℝ) := {p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2} variable (r : ℝ≥0) /-- A disc of radius `r` can be represented as the region between the two curves `λ x, - sqrt (r ^ 2 - x ^ 2)` and `λ x, sqrt (r ^ 2 - x ^ 2)`. -/ lemma disc_eq_region_between : disc r = region_between (λ x, -sqrt (r^2 - x^2)) (λ x, sqrt (r^2 - x^2)) (Ioc (-r) r) := begin ext p, simp only [disc, region_between, mem_set_of_eq, mem_Ioo, mem_Ioc, pi.neg_apply], split; intro h, { cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2, rw [add_comm, ← lt_sub_iff_add_lt] at h, exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩ }, { rw [add_comm, ← lt_sub_iff_add_lt], exact sq_lt.mpr h.2 }, end /-- The disc is a `measurable_set`. -/ theorem measurable_set_disc : measurable_set (disc r) := by apply measurable_set_lt; apply continuous.measurable; continuity /-- **Area of a Circle**: The area of a disc with radius `r` is `π * r ^ 2`. -/ theorem area_disc : volume (disc r) = nnreal.pi * r ^ 2 := begin let f := λ x, sqrt (r ^ 2 - x ^ 2), let F := λ x, (r:ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2), have hf : continuous f := by continuity, suffices : ∫ x in -r..r, 2 * f x = nnreal.pi * r ^ 2, { have h : integrable_on f (Ioc (-r) r) := hf.integrable_on_Icc.mono_set Ioc_subset_Icc_self, calc volume (disc r) = volume (region_between (λ x, -f x) f (Ioc (-r) r)) : by rw disc_eq_region_between ... = ennreal.of_real (∫ x in Ioc (-r:ℝ) r, (f - has_neg.neg ∘ f) x) : volume_region_between_eq_integral h.neg h measurable_set_Ioc (λ x hx, neg_le_self (sqrt_nonneg _)) ... = ennreal.of_real (∫ x in (-r:ℝ)..r, 2 * f x) : by simp [two_mul, integral_of_le] ... = nnreal.pi * r ^ 2 : by rw_mod_cast [this, ← ennreal.coe_nnreal_eq], }, obtain ⟨hle, (heq | hlt)⟩ := ⟨nnreal.coe_nonneg r, hle.eq_or_lt⟩, { simp [← heq] }, have hderiv : ∀ x ∈ Ioo (-r:ℝ) r, has_deriv_at F (2 * f x) x, { rintros x ⟨hx1, hx2⟩, convert ((has_deriv_at_const x ((r:ℝ)^2)).mul ((has_deriv_at_arcsin _ _).comp x ((has_deriv_at_const x (r:ℝ)⁻¹).mul (has_deriv_at_id' x)))).add ((has_deriv_at_id' x).mul ((((has_deriv_at_id' x).pow 2).const_sub ((r:ℝ)^2)).sqrt _)), { have h : sqrt (1 - x ^ 2 / r ^ 2) * r = sqrt (r ^ 2 - x ^ 2), { rw [← sqrt_sq hle, ← sqrt_mul, sub_mul, sqrt_sq hle, mul_comm_div, div_self (pow_ne_zero 2 hlt.ne'), one_mul, mul_one], simpa [sqrt_sq hle, div_le_one (pow_pos hlt 2)] using sq_le_sq' hx1.le hx2.le }, field_simp, rw [h, mul_left_comm, ← sq, neg_mul_eq_mul_neg, mul_div_mul_left (-x^2) _ two_ne_zero, add_left_comm, div_add_div_same, tactic.ring.add_neg_eq_sub, div_sqrt, two_mul] }, { suffices : -(1:ℝ) < r⁻¹ * x, by exact this.ne', calc -(1:ℝ) = r⁻¹ * -r : by simp [hlt.ne'] ... < r⁻¹ * x : by nlinarith [inv_pos.mpr hlt] }, { suffices : (r:ℝ)⁻¹ * x < 1, by exact this.ne, calc (r:ℝ)⁻¹ * x < r⁻¹ * r : by nlinarith [inv_pos.mpr hlt] ... = 1 : inv_mul_cancel hlt.ne' }, { nlinarith } }, have hcont := (by continuity : continuous F).continuous_on, calc ∫ x in -r..r, 2 * f x = F r - F (-r) : integral_eq_sub_of_has_deriv_at_of_le (neg_le_self r.2) hcont hderiv (continuous_const.mul hf).continuous_on.interval_integrable ... = nnreal.pi * r ^ 2 : by norm_num [F, inv_mul_cancel hlt.ne', ← mul_div_assoc, mul_comm π], end